[X86] Remove useless target specific combine on TRUNCATE dag nodes.
[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 "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.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/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 static cl::opt<int> ReciprocalEstimateRefinementSteps(
71     "x86-recip-refinement-steps", cl::init(1),
72     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
73              "result of the hardware reciprocal estimate instruction."),
74     cl::NotHidden);
75
76 // Forward declarations.
77 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
78                        SDValue V2);
79
80 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
81                                      const X86Subtarget &STI)
82     : TargetLowering(TM), Subtarget(&STI) {
83   X86ScalarSSEf64 = Subtarget->hasSSE2();
84   X86ScalarSSEf32 = Subtarget->hasSSE1();
85   TD = getDataLayout();
86
87   // Set up the TargetLowering object.
88   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
89
90   // X86 is weird. It always uses i8 for shift amounts and setcc results.
91   setBooleanContents(ZeroOrOneBooleanContent);
92   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
93   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
94
95   // For 64-bit, since we have so many registers, use the ILP scheduler.
96   // For 32-bit, use the register pressure specific scheduling.
97   // For Atom, always use ILP scheduling.
98   if (Subtarget->isAtom())
99     setSchedulingPreference(Sched::ILP);
100   else if (Subtarget->is64Bit())
101     setSchedulingPreference(Sched::ILP);
102   else
103     setSchedulingPreference(Sched::RegPressure);
104   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
105   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
106
107   // Bypass expensive divides on Atom when compiling with O2.
108   if (TM.getOptLevel() >= CodeGenOpt::Default) {
109     if (Subtarget->hasSlowDivide32())
110       addBypassSlowDiv(32, 8);
111     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
112       addBypassSlowDiv(64, 16);
113   }
114
115   if (Subtarget->isTargetKnownWindowsMSVC()) {
116     // Setup Windows compiler runtime calls.
117     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
118     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
119     setLibcallName(RTLIB::SREM_I64, "_allrem");
120     setLibcallName(RTLIB::UREM_I64, "_aullrem");
121     setLibcallName(RTLIB::MUL_I64, "_allmul");
122     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
123     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
124     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
125     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
126     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
127
128     // The _ftol2 runtime function has an unusual calling conv, which
129     // is modeled by a special pseudo-instruction.
130     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
131     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
132     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
133     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
134   }
135
136   if (Subtarget->isTargetDarwin()) {
137     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
138     setUseUnderscoreSetJmp(false);
139     setUseUnderscoreLongJmp(false);
140   } else if (Subtarget->isTargetWindowsGNU()) {
141     // MS runtime is weird: it exports _setjmp, but longjmp!
142     setUseUnderscoreSetJmp(true);
143     setUseUnderscoreLongJmp(false);
144   } else {
145     setUseUnderscoreSetJmp(true);
146     setUseUnderscoreLongJmp(true);
147   }
148
149   // Set up the register classes.
150   addRegisterClass(MVT::i8, &X86::GR8RegClass);
151   addRegisterClass(MVT::i16, &X86::GR16RegClass);
152   addRegisterClass(MVT::i32, &X86::GR32RegClass);
153   if (Subtarget->is64Bit())
154     addRegisterClass(MVT::i64, &X86::GR64RegClass);
155
156   for (MVT VT : MVT::integer_valuetypes())
157     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
158
159   // We don't accept any truncstore of integer registers.
160   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
161   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
162   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
163   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
164   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
165   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
166
167   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
168
169   // SETOEQ and SETUNE require checking two conditions.
170   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
171   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
172   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
173   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
174   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
175   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
176
177   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
178   // operation.
179   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
180   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
181   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
182
183   if (Subtarget->is64Bit()) {
184     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
185     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
186   } else if (!Subtarget->useSoftFloat()) {
187     // We have an algorithm for SSE2->double, and we turn this into a
188     // 64-bit FILD followed by conditional FADD for other targets.
189     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
190     // We have an algorithm for SSE2, and we turn this into a 64-bit
191     // FILD for other targets.
192     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
193   }
194
195   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
196   // this operation.
197   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
198   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
199
200   if (!Subtarget->useSoftFloat()) {
201     // SSE has no i16 to fp conversion, only i32
202     if (X86ScalarSSEf32) {
203       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
204       // f32 and f64 cases are Legal, f80 case is not
205       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
206     } else {
207       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
208       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
209     }
210   } else {
211     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
212     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
213   }
214
215   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
216   // are Legal, f80 is custom lowered.
217   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
218   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
219
220   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
221   // this operation.
222   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
223   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
224
225   if (X86ScalarSSEf32) {
226     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
227     // f32 and f64 cases are Legal, f80 case is not
228     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
229   } else {
230     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
231     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
232   }
233
234   // Handle FP_TO_UINT by promoting the destination to a larger signed
235   // conversion.
236   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
237   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
238   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
239
240   if (Subtarget->is64Bit()) {
241     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
242     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
243   } else if (!Subtarget->useSoftFloat()) {
244     // Since AVX is a superset of SSE3, only check for SSE here.
245     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246       // Expand FP_TO_UINT into a select.
247       // FIXME: We would like to use a Custom expander here eventually to do
248       // the optimal thing for SSE vs. the default expansion in the legalizer.
249       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
250     else
251       // With SSE3 we can use fisttpll to convert to a signed i64; without
252       // SSE, we're stuck with a fistpll.
253       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
254   }
255
256   if (isTargetFTOL()) {
257     // Use the _ftol2 runtime function, which has a pseudo-instruction
258     // to handle its weird calling convention.
259     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
260   }
261
262   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
263   if (!X86ScalarSSEf64) {
264     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
265     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
266     if (Subtarget->is64Bit()) {
267       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
268       // Without SSE, i64->f64 goes through memory.
269       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
270     }
271   }
272
273   // Scalar integer divide and remainder are lowered to use operations that
274   // produce two results, to match the available instructions. This exposes
275   // the two-result form to trivial CSE, which is able to combine x/y and x%y
276   // into a single instruction.
277   //
278   // Scalar integer multiply-high is also lowered to use two-result
279   // operations, to match the available instructions. However, plain multiply
280   // (low) operations are left as Legal, as there are single-result
281   // instructions for this in x86. Using the two-result multiply instructions
282   // when both high and low results are needed must be arranged by dagcombine.
283   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
284     MVT VT = IntVTs[i];
285     setOperationAction(ISD::MULHS, VT, Expand);
286     setOperationAction(ISD::MULHU, VT, Expand);
287     setOperationAction(ISD::SDIV, VT, Expand);
288     setOperationAction(ISD::UDIV, VT, Expand);
289     setOperationAction(ISD::SREM, VT, Expand);
290     setOperationAction(ISD::UREM, VT, Expand);
291
292     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
293     setOperationAction(ISD::ADDC, VT, Custom);
294     setOperationAction(ISD::ADDE, VT, Custom);
295     setOperationAction(ISD::SUBC, VT, Custom);
296     setOperationAction(ISD::SUBE, VT, Custom);
297   }
298
299   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
300   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
301   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
302   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
303   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
305   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
306   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
307   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
313   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
314   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
315   if (Subtarget->is64Bit())
316     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
318   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
319   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
320   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
321   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
322   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
323   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
324   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
325
326   // Promote the i8 variants and force them on up to i32 which has a shorter
327   // encoding.
328   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
329   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
330   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
331   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
332   if (Subtarget->hasBMI()) {
333     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
334     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
335     if (Subtarget->is64Bit())
336       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
337   } else {
338     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
339     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
340     if (Subtarget->is64Bit())
341       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
342   }
343
344   if (Subtarget->hasLZCNT()) {
345     // When promoting the i8 variants, force them to i32 for a shorter
346     // encoding.
347     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
348     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
350     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
352     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
353     if (Subtarget->is64Bit())
354       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
355   } else {
356     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
357     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
358     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
361     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
362     if (Subtarget->is64Bit()) {
363       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
364       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
365     }
366   }
367
368   // Special handling for half-precision floating point conversions.
369   // If we don't have F16C support, then lower half float conversions
370   // into library calls.
371   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
372     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
374   }
375
376   // There's never any support for operations beyond MVT::f32.
377   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
381
382   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
388
389   if (Subtarget->hasPOPCNT()) {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
391   } else {
392     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
397   }
398
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400
401   if (!Subtarget->hasMOVBE())
402     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
403
404   // These should be promoted to a larger select which is supported.
405   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
406   // X86 wants to expand cmov itself.
407   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
412   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
421     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
422   }
423   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
424   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426   // support continuation, user-level threading, and etc.. As a result, no
427   // other SjLj exception interfaces are implemented and please don't build
428   // your own exception handling based on them.
429   // LLVM/Clang supports zero-cost DWARF exception handling.
430   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
432
433   // Darwin ABI issue.
434   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
435   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
437   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
438   if (Subtarget->is64Bit())
439     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
441   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
442   if (Subtarget->is64Bit()) {
443     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
444     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
445     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
446     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
447     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
448   }
449   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
452   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
456     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
457   }
458
459   if (Subtarget->hasSSE1())
460     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
461
462   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
463
464   // Expand certain atomics
465   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
466     MVT VT = IntVTs[i];
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
470   }
471
472   if (Subtarget->hasCmpxchg16b()) {
473     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
474   }
475
476   // FIXME - use subtarget debug flags
477   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480   }
481
482   if (Subtarget->is64Bit()) {
483     setExceptionPointerRegister(X86::RAX);
484     setExceptionSelectorRegister(X86::RDX);
485   } else {
486     setExceptionPointerRegister(X86::EAX);
487     setExceptionSelectorRegister(X86::EDX);
488   }
489   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
491
492   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
494
495   setOperationAction(ISD::TRAP, MVT::Other, Legal);
496   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
497
498   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
500   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
501   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
502     // TargetInfo::X86_64ABIBuiltinVaList
503     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
505   } else {
506     // TargetInfo::CharPtrBuiltinVaList
507     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
508     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
509   }
510
511   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
512   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
513
514   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
515
516   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
517   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
518   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
519
520   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
521     // f32 and f64 use SSE.
522     // Set up the FP register classes.
523     addRegisterClass(MVT::f32, &X86::FR32RegClass);
524     addRegisterClass(MVT::f64, &X86::FR64RegClass);
525
526     // Use ANDPD to simulate FABS.
527     setOperationAction(ISD::FABS , MVT::f64, Custom);
528     setOperationAction(ISD::FABS , MVT::f32, Custom);
529
530     // Use XORP to simulate FNEG.
531     setOperationAction(ISD::FNEG , MVT::f64, Custom);
532     setOperationAction(ISD::FNEG , MVT::f32, Custom);
533
534     // Use ANDPD and ORPD to simulate FCOPYSIGN.
535     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
536     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
537
538     // Lower this to FGETSIGNx86 plus an AND.
539     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
540     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
541
542     // We don't support sin/cos/fmod
543     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
544     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
546     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
547     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
548     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
549
550     // Expand FP immediates into loads from the stack, except for the special
551     // cases we handle.
552     addLegalFPImmediate(APFloat(+0.0)); // xorpd
553     addLegalFPImmediate(APFloat(+0.0f)); // xorps
554   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
555     // Use SSE for f32, x87 for f64.
556     // Set up the FP register classes.
557     addRegisterClass(MVT::f32, &X86::FR32RegClass);
558     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
559
560     // Use ANDPS to simulate FABS.
561     setOperationAction(ISD::FABS , MVT::f32, Custom);
562
563     // Use XORP to simulate FNEG.
564     setOperationAction(ISD::FNEG , MVT::f32, Custom);
565
566     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
567
568     // Use ANDPS and ORPS to simulate FCOPYSIGN.
569     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
570     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571
572     // We don't support sin/cos/fmod
573     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
574     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
575     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
576
577     // Special cases we handle for FP constants.
578     addLegalFPImmediate(APFloat(+0.0f)); // xorps
579     addLegalFPImmediate(APFloat(+0.0)); // FLD0
580     addLegalFPImmediate(APFloat(+1.0)); // FLD1
581     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
583
584     if (!TM.Options.UnsafeFPMath) {
585       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
586       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
587       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
588     }
589   } else if (!Subtarget->useSoftFloat()) {
590     // f32 and f64 in x87.
591     // Set up the FP register classes.
592     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
593     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
594
595     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
596     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
599
600     if (!TM.Options.UnsafeFPMath) {
601       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
602       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
603       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
604       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
605       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
606       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
607     }
608     addLegalFPImmediate(APFloat(+0.0)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
612     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
613     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
614     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
615     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
616   }
617
618   // We don't support FMA.
619   setOperationAction(ISD::FMA, MVT::f64, Expand);
620   setOperationAction(ISD::FMA, MVT::f32, Expand);
621
622   // Long double always uses X87.
623   if (!Subtarget->useSoftFloat()) {
624     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
625     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
626     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
627     {
628       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
629       addLegalFPImmediate(TmpFlt);  // FLD0
630       TmpFlt.changeSign();
631       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
632
633       bool ignored;
634       APFloat TmpFlt2(+1.0);
635       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
636                       &ignored);
637       addLegalFPImmediate(TmpFlt2);  // FLD1
638       TmpFlt2.changeSign();
639       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
640     }
641
642     if (!TM.Options.UnsafeFPMath) {
643       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
644       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
645       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
646     }
647
648     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
649     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
650     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
651     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
652     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
653     setOperationAction(ISD::FMA, MVT::f80, Expand);
654   }
655
656   // Always use a library call for pow.
657   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
658   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
659   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
660
661   setOperationAction(ISD::FLOG, MVT::f80, Expand);
662   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
663   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
664   setOperationAction(ISD::FEXP, MVT::f80, Expand);
665   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
666   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
667   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
668
669   // First set operation action for all vector types to either promote
670   // (for widening) or expand (for scalarization). Then we will selectively
671   // turn on ones that can be effectively codegen'd.
672   for (MVT VT : MVT::vector_valuetypes()) {
673     setOperationAction(ISD::ADD , VT, Expand);
674     setOperationAction(ISD::SUB , VT, Expand);
675     setOperationAction(ISD::FADD, VT, Expand);
676     setOperationAction(ISD::FNEG, VT, Expand);
677     setOperationAction(ISD::FSUB, VT, Expand);
678     setOperationAction(ISD::MUL , VT, Expand);
679     setOperationAction(ISD::FMUL, VT, Expand);
680     setOperationAction(ISD::SDIV, VT, Expand);
681     setOperationAction(ISD::UDIV, VT, Expand);
682     setOperationAction(ISD::FDIV, VT, Expand);
683     setOperationAction(ISD::SREM, VT, Expand);
684     setOperationAction(ISD::UREM, VT, Expand);
685     setOperationAction(ISD::LOAD, VT, Expand);
686     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
687     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
688     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
689     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
690     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
691     setOperationAction(ISD::FABS, VT, Expand);
692     setOperationAction(ISD::FSIN, VT, Expand);
693     setOperationAction(ISD::FSINCOS, VT, Expand);
694     setOperationAction(ISD::FCOS, VT, Expand);
695     setOperationAction(ISD::FSINCOS, VT, Expand);
696     setOperationAction(ISD::FREM, VT, Expand);
697     setOperationAction(ISD::FMA,  VT, Expand);
698     setOperationAction(ISD::FPOWI, VT, Expand);
699     setOperationAction(ISD::FSQRT, VT, Expand);
700     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
701     setOperationAction(ISD::FFLOOR, VT, Expand);
702     setOperationAction(ISD::FCEIL, VT, Expand);
703     setOperationAction(ISD::FTRUNC, VT, Expand);
704     setOperationAction(ISD::FRINT, VT, Expand);
705     setOperationAction(ISD::FNEARBYINT, VT, Expand);
706     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
707     setOperationAction(ISD::MULHS, VT, Expand);
708     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
709     setOperationAction(ISD::MULHU, VT, Expand);
710     setOperationAction(ISD::SDIVREM, VT, Expand);
711     setOperationAction(ISD::UDIVREM, VT, Expand);
712     setOperationAction(ISD::FPOW, VT, Expand);
713     setOperationAction(ISD::CTPOP, VT, Expand);
714     setOperationAction(ISD::CTTZ, VT, Expand);
715     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
716     setOperationAction(ISD::CTLZ, VT, Expand);
717     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
718     setOperationAction(ISD::SHL, VT, Expand);
719     setOperationAction(ISD::SRA, VT, Expand);
720     setOperationAction(ISD::SRL, VT, Expand);
721     setOperationAction(ISD::ROTL, VT, Expand);
722     setOperationAction(ISD::ROTR, VT, Expand);
723     setOperationAction(ISD::BSWAP, VT, Expand);
724     setOperationAction(ISD::SETCC, VT, Expand);
725     setOperationAction(ISD::FLOG, VT, Expand);
726     setOperationAction(ISD::FLOG2, VT, Expand);
727     setOperationAction(ISD::FLOG10, VT, Expand);
728     setOperationAction(ISD::FEXP, VT, Expand);
729     setOperationAction(ISD::FEXP2, VT, Expand);
730     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
731     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
732     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
733     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
734     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
735     setOperationAction(ISD::TRUNCATE, VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
737     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
738     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
739     setOperationAction(ISD::VSELECT, VT, Expand);
740     setOperationAction(ISD::SELECT_CC, VT, Expand);
741     for (MVT InnerVT : MVT::vector_valuetypes()) {
742       setTruncStoreAction(InnerVT, VT, Expand);
743
744       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
745       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
746
747       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
748       // types, we have to deal with them whether we ask for Expansion or not.
749       // Setting Expand causes its own optimisation problems though, so leave
750       // them legal.
751       if (VT.getVectorElementType() == MVT::i1)
752         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
753
754       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
755       // split/scalarized right now.
756       if (VT.getVectorElementType() == MVT::f16)
757         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
758     }
759   }
760
761   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
762   // with -msoft-float, disable use of MMX as well.
763   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
764     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
765     // No operations on x86mmx supported, everything uses intrinsics.
766   }
767
768   // MMX-sized vectors (other than x86mmx) are expected to be expanded
769   // into smaller operations.
770   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
771     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
772     setOperationAction(ISD::AND,                MMXTy,      Expand);
773     setOperationAction(ISD::OR,                 MMXTy,      Expand);
774     setOperationAction(ISD::XOR,                MMXTy,      Expand);
775     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
776     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
777     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
778   }
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780
781   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
782     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
783
784     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
786     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
787     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
788     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
789     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
790     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
791     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
792     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
793     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
794     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
795     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
796     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
797     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
798   }
799
800   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
801     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
802
803     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
804     // registers cannot be used even for integer operations.
805     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
806     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
807     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
808     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
809
810     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
811     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
812     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
813     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
814     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
815     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
816     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
817     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
818     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
819     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
820     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
833
834     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
837     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
838
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
840     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
844
845     // Only provide customized ctpop vector bit twiddling for vector types we
846     // know to perform better than using the popcnt instructions on each vector
847     // element. If popcnt isn't supported, always provide the custom version.
848     if (!Subtarget->hasPOPCNT()) {
849       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
850       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
851     }
852
853     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
854     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
855       MVT VT = (MVT::SimpleValueType)i;
856       // Do not attempt to custom lower non-power-of-2 vectors
857       if (!isPowerOf2_32(VT.getVectorNumElements()))
858         continue;
859       // Do not attempt to custom lower non-128-bit vectors
860       if (!VT.is128BitVector())
861         continue;
862       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
863       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
864       setOperationAction(ISD::VSELECT,            VT, Custom);
865       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
866     }
867
868     // We support custom legalizing of sext and anyext loads for specific
869     // memory vector types which we can load as a scalar (or sequence of
870     // scalars) and extend in-register to a legal 128-bit vector type. For sext
871     // loads these must work with a single scalar load.
872     for (MVT VT : MVT::integer_vector_valuetypes()) {
873       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
874       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
875       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
878       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
879       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
880       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
881       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
882     }
883
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
885     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
887     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
888     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
889     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
891     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
892
893     if (Subtarget->is64Bit()) {
894       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
895       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
896     }
897
898     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
900       MVT VT = (MVT::SimpleValueType)i;
901
902       // Do not attempt to promote non-128-bit vectors
903       if (!VT.is128BitVector())
904         continue;
905
906       setOperationAction(ISD::AND,    VT, Promote);
907       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
908       setOperationAction(ISD::OR,     VT, Promote);
909       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
910       setOperationAction(ISD::XOR,    VT, Promote);
911       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
912       setOperationAction(ISD::LOAD,   VT, Promote);
913       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
914       setOperationAction(ISD::SELECT, VT, Promote);
915       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
916     }
917
918     // Custom lower v2i64 and v2f64 selects.
919     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
920     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
921     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
922     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
923
924     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
925     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
926
927     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
928     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
929     // As there is no 64-bit GPR available, we need build a special custom
930     // sequence to convert from v2i32 to v2f32.
931     if (!Subtarget->is64Bit())
932       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
933
934     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
935     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
936
937     for (MVT VT : MVT::fp_vector_valuetypes())
938       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
939
940     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
941     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
942     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
943   }
944
945   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
946     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
947       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
948       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
949       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
950       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
951       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
952     }
953
954     // FIXME: Do we need to handle scalar-to-vector here?
955     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
956
957     // We directly match byte blends in the backend as they match the VSELECT
958     // condition form.
959     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
960
961     // SSE41 brings specific instructions for doing vector sign extend even in
962     // cases where we don't have SRA.
963     for (MVT VT : MVT::integer_vector_valuetypes()) {
964       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
965       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
966       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
967     }
968
969     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
970     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
971     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
972     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
973     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
974     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
975     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
976
977     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     // i8 and i16 vectors are custom because the source register and source
985     // source memory operand types are not the same width.  f32 vectors are
986     // custom since the immediate controlling the insert encodes additional
987     // information.
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
989     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
990     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
992
993     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
994     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
995     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
996     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
997
998     // FIXME: these should be Legal, but that's only for the case where
999     // the index is constant.  For now custom expand to deal with that.
1000     if (Subtarget->is64Bit()) {
1001       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1002       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1003     }
1004   }
1005
1006   if (Subtarget->hasSSE2()) {
1007     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1008     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1009
1010     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1011     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1012
1013     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1014     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1015
1016     // In the customized shift lowering, the legal cases in AVX2 will be
1017     // recognized.
1018     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1025   }
1026
1027   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1028     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1029     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1030     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1031     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1032     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1033     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1034
1035     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1036     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1037     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1038
1039     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1041     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1042     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1043     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1044     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1045     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1046     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1047     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1048     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1049     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1050     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1051
1052     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1053     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1054     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1055     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1056     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1057     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1058     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1059     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1060     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1061     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1062     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1063     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1064
1065     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1066     // even though v8i16 is a legal type.
1067     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1068     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1069     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1070
1071     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1072     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1073     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1074
1075     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1076     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1077
1078     for (MVT VT : MVT::fp_vector_valuetypes())
1079       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1080
1081     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1082     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1083
1084     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1085     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1086
1087     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1088     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1089
1090     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1091     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1092     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1093     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1094
1095     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1096     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1097     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1098
1099     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1100     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1101     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1102     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1103     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1104     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1105     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1106     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1107     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1108     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1109     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1110     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1111
1112     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1113       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1114       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1115       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1116       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1117       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1118       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1119     }
1120
1121     if (Subtarget->hasInt256()) {
1122       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1123       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1124       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1125       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1126
1127       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1128       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1129       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1130       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1131
1132       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1133       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1134       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1135       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1136
1137       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1138       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1139       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1140       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1141
1142       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1143       // when we have a 256bit-wide blend with immediate.
1144       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1145
1146       // Only provide customized ctpop vector bit twiddling for vector types we
1147       // know to perform better than using the popcnt instructions on each
1148       // vector element. If popcnt isn't supported, always provide the custom
1149       // version.
1150       if (!Subtarget->hasPOPCNT())
1151         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1152
1153       // Custom CTPOP always performs better on natively supported v8i32
1154       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1155
1156       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1157       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1158       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1159       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1160       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1161       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1162       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1163
1164       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1165       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1166       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1167       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1168       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1169       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1170     } else {
1171       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1172       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1173       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1174       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1175
1176       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1177       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1178       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1179       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1180
1181       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1182       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1183       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1184       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1185     }
1186
1187     // In the customized shift lowering, the legal cases in AVX2 will be
1188     // recognized.
1189     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1190     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1191
1192     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1193     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1194
1195     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1196
1197     // Custom lower several nodes for 256-bit types.
1198     for (MVT VT : MVT::vector_valuetypes()) {
1199       if (VT.getScalarSizeInBits() >= 32) {
1200         setOperationAction(ISD::MLOAD,  VT, Legal);
1201         setOperationAction(ISD::MSTORE, VT, Legal);
1202       }
1203       // Extract subvector is special because the value type
1204       // (result) is 128-bit but the source is 256-bit wide.
1205       if (VT.is128BitVector()) {
1206         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1207       }
1208       // Do not attempt to custom lower other non-256-bit vectors
1209       if (!VT.is256BitVector())
1210         continue;
1211
1212       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1213       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1214       setOperationAction(ISD::VSELECT,            VT, Custom);
1215       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1216       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1217       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1218       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1219       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1220     }
1221
1222     if (Subtarget->hasInt256())
1223       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1224
1225
1226     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1227     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1228       MVT VT = (MVT::SimpleValueType)i;
1229
1230       // Do not attempt to promote non-256-bit vectors
1231       if (!VT.is256BitVector())
1232         continue;
1233
1234       setOperationAction(ISD::AND,    VT, Promote);
1235       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1236       setOperationAction(ISD::OR,     VT, Promote);
1237       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1238       setOperationAction(ISD::XOR,    VT, Promote);
1239       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1240       setOperationAction(ISD::LOAD,   VT, Promote);
1241       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1242       setOperationAction(ISD::SELECT, VT, Promote);
1243       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1244     }
1245   }
1246
1247   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1248     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1249     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1250     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1251     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1252
1253     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1254     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1255     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1256
1257     for (MVT VT : MVT::fp_vector_valuetypes())
1258       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1259
1260     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1261     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1262     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1263     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1264     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1265     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1266     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1267     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1268     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1269     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1270
1271     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1272     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1273     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1274     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1275     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1276     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1277
1278     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1279     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1280     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1281     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1282     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1283     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1284     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1285     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1286
1287     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1288     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1289     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1290     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1291     if (Subtarget->is64Bit()) {
1292       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1293       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1294       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1295       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1296     }
1297     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1298     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1299     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1300     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1301     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1302     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1303     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1304     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1305     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1306     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1307     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1308     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1309     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1310     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1311     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1312     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1313
1314     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1315     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1316     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1317     if (Subtarget->hasDQI()) {
1318       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1319       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1320     }
1321     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1322     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1323     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1324     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1325     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1326     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1327     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1328     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1329     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1330     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1331     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1332     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1333     if (Subtarget->hasDQI()) {
1334       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1335       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1336     }
1337     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1338     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1339     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1340     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1341     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1342     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1343     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1344     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1345     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1346     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1347
1348     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1349     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1350     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1351     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1352     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1353
1354     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1355     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1356
1357     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1358
1359     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1360     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1361     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1362     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1363     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1364     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1365     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1366     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1367     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1368     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1369     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1370
1371     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1372     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1373
1374     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1375     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1376
1377     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1378
1379     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1380     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1381
1382     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1383     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1384
1385     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1386     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1387
1388     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1389     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1390     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1391     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1392     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1393     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1394
1395     if (Subtarget->hasCDI()) {
1396       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1397       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1398     }
1399     if (Subtarget->hasDQI()) {
1400       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1401       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1402       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1403     }
1404     // Custom lower several nodes.
1405     for (MVT VT : MVT::vector_valuetypes()) {
1406       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1407       if (EltSize == 1) {
1408         setOperationAction(ISD::AND, VT, Legal);
1409         setOperationAction(ISD::OR,  VT, Legal);
1410         setOperationAction(ISD::XOR,  VT, Legal);
1411       }
1412       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1413         setOperationAction(ISD::MGATHER,  VT, Custom);
1414         setOperationAction(ISD::MSCATTER, VT, Custom);
1415       }
1416       // Extract subvector is special because the value type
1417       // (result) is 256/128-bit but the source is 512-bit wide.
1418       if (VT.is128BitVector() || VT.is256BitVector()) {
1419         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1420       }
1421       if (VT.getVectorElementType() == MVT::i1)
1422         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1423
1424       // Do not attempt to custom lower other non-512-bit vectors
1425       if (!VT.is512BitVector())
1426         continue;
1427
1428       if (EltSize >= 32) {
1429         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1430         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1431         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1432         setOperationAction(ISD::VSELECT,             VT, Legal);
1433         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1434         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1435         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1436         setOperationAction(ISD::MLOAD,               VT, Legal);
1437         setOperationAction(ISD::MSTORE,              VT, Legal);
1438       }
1439     }
1440     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1441       MVT VT = (MVT::SimpleValueType)i;
1442
1443       // Do not attempt to promote non-512-bit vectors.
1444       if (!VT.is512BitVector())
1445         continue;
1446
1447       setOperationAction(ISD::SELECT, VT, Promote);
1448       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1449     }
1450   }// has  AVX-512
1451
1452   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1453     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1454     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1455
1456     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1457     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1458
1459     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1460     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1461     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1462     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1463     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1464     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1465     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1466     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1467     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1468     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1469     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1470     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1471     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1472     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1473     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1474
1475     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1476       const MVT VT = (MVT::SimpleValueType)i;
1477
1478       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1479
1480       // Do not attempt to promote non-512-bit vectors.
1481       if (!VT.is512BitVector())
1482         continue;
1483
1484       if (EltSize < 32) {
1485         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1486         setOperationAction(ISD::VSELECT,             VT, Legal);
1487       }
1488     }
1489   }
1490
1491   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1492     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1493     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1494
1495     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1496     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1497     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1498     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1499     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1500     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1501     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1502     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1503
1504     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1505     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1506     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1507     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1508     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1509     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1510   }
1511
1512   // We want to custom lower some of our intrinsics.
1513   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1514   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1515   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1516   if (!Subtarget->is64Bit())
1517     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1518
1519   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1520   // handle type legalization for these operations here.
1521   //
1522   // FIXME: We really should do custom legalization for addition and
1523   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1524   // than generic legalization for 64-bit multiplication-with-overflow, though.
1525   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1526     // Add/Sub/Mul with overflow operations are custom lowered.
1527     MVT VT = IntVTs[i];
1528     setOperationAction(ISD::SADDO, VT, Custom);
1529     setOperationAction(ISD::UADDO, VT, Custom);
1530     setOperationAction(ISD::SSUBO, VT, Custom);
1531     setOperationAction(ISD::USUBO, VT, Custom);
1532     setOperationAction(ISD::SMULO, VT, Custom);
1533     setOperationAction(ISD::UMULO, VT, Custom);
1534   }
1535
1536
1537   if (!Subtarget->is64Bit()) {
1538     // These libcalls are not available in 32-bit.
1539     setLibcallName(RTLIB::SHL_I128, nullptr);
1540     setLibcallName(RTLIB::SRL_I128, nullptr);
1541     setLibcallName(RTLIB::SRA_I128, nullptr);
1542   }
1543
1544   // Combine sin / cos into one node or libcall if possible.
1545   if (Subtarget->hasSinCos()) {
1546     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1547     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1548     if (Subtarget->isTargetDarwin()) {
1549       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1550       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1551       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1552       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1553     }
1554   }
1555
1556   if (Subtarget->isTargetWin64()) {
1557     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1558     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1559     setOperationAction(ISD::SREM, MVT::i128, Custom);
1560     setOperationAction(ISD::UREM, MVT::i128, Custom);
1561     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1562     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1563   }
1564
1565   // We have target-specific dag combine patterns for the following nodes:
1566   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1567   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1568   setTargetDAGCombine(ISD::BITCAST);
1569   setTargetDAGCombine(ISD::VSELECT);
1570   setTargetDAGCombine(ISD::SELECT);
1571   setTargetDAGCombine(ISD::SHL);
1572   setTargetDAGCombine(ISD::SRA);
1573   setTargetDAGCombine(ISD::SRL);
1574   setTargetDAGCombine(ISD::OR);
1575   setTargetDAGCombine(ISD::AND);
1576   setTargetDAGCombine(ISD::ADD);
1577   setTargetDAGCombine(ISD::FADD);
1578   setTargetDAGCombine(ISD::FSUB);
1579   setTargetDAGCombine(ISD::FMA);
1580   setTargetDAGCombine(ISD::SUB);
1581   setTargetDAGCombine(ISD::LOAD);
1582   setTargetDAGCombine(ISD::MLOAD);
1583   setTargetDAGCombine(ISD::STORE);
1584   setTargetDAGCombine(ISD::MSTORE);
1585   setTargetDAGCombine(ISD::ZERO_EXTEND);
1586   setTargetDAGCombine(ISD::ANY_EXTEND);
1587   setTargetDAGCombine(ISD::SIGN_EXTEND);
1588   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1589   setTargetDAGCombine(ISD::SINT_TO_FP);
1590   setTargetDAGCombine(ISD::SETCC);
1591   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1592   setTargetDAGCombine(ISD::BUILD_VECTOR);
1593   setTargetDAGCombine(ISD::MUL);
1594   setTargetDAGCombine(ISD::XOR);
1595
1596   computeRegisterProperties(Subtarget->getRegisterInfo());
1597
1598   // On Darwin, -Os means optimize for size without hurting performance,
1599   // do not reduce the limit.
1600   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1601   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1602   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1603   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1604   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1605   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1606   setPrefLoopAlignment(4); // 2^4 bytes.
1607
1608   // Predictable cmov don't hurt on atom because it's in-order.
1609   PredictableSelectIsExpensive = !Subtarget->isAtom();
1610   EnableExtLdPromotion = true;
1611   setPrefFunctionAlignment(4); // 2^4 bytes.
1612
1613   verifyIntrinsicTables();
1614 }
1615
1616 // This has so far only been implemented for 64-bit MachO.
1617 bool X86TargetLowering::useLoadStackGuardNode() const {
1618   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1619 }
1620
1621 TargetLoweringBase::LegalizeTypeAction
1622 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1623   if (ExperimentalVectorWideningLegalization &&
1624       VT.getVectorNumElements() != 1 &&
1625       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1626     return TypeWidenVector;
1627
1628   return TargetLoweringBase::getPreferredVectorAction(VT);
1629 }
1630
1631 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1632   if (!VT.isVector())
1633     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1634
1635   const unsigned NumElts = VT.getVectorNumElements();
1636   const EVT EltVT = VT.getVectorElementType();
1637   if (VT.is512BitVector()) {
1638     if (Subtarget->hasAVX512())
1639       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1640           EltVT == MVT::f32 || EltVT == MVT::f64)
1641         switch(NumElts) {
1642         case  8: return MVT::v8i1;
1643         case 16: return MVT::v16i1;
1644       }
1645     if (Subtarget->hasBWI())
1646       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1647         switch(NumElts) {
1648         case 32: return MVT::v32i1;
1649         case 64: return MVT::v64i1;
1650       }
1651   }
1652
1653   if (VT.is256BitVector() || VT.is128BitVector()) {
1654     if (Subtarget->hasVLX())
1655       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1656           EltVT == MVT::f32 || EltVT == MVT::f64)
1657         switch(NumElts) {
1658         case 2: return MVT::v2i1;
1659         case 4: return MVT::v4i1;
1660         case 8: return MVT::v8i1;
1661       }
1662     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1663       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1664         switch(NumElts) {
1665         case  8: return MVT::v8i1;
1666         case 16: return MVT::v16i1;
1667         case 32: return MVT::v32i1;
1668       }
1669   }
1670
1671   return VT.changeVectorElementTypeToInteger();
1672 }
1673
1674 /// Helper for getByValTypeAlignment to determine
1675 /// the desired ByVal argument alignment.
1676 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1677   if (MaxAlign == 16)
1678     return;
1679   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1680     if (VTy->getBitWidth() == 128)
1681       MaxAlign = 16;
1682   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1683     unsigned EltAlign = 0;
1684     getMaxByValAlign(ATy->getElementType(), EltAlign);
1685     if (EltAlign > MaxAlign)
1686       MaxAlign = EltAlign;
1687   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1688     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1689       unsigned EltAlign = 0;
1690       getMaxByValAlign(STy->getElementType(i), EltAlign);
1691       if (EltAlign > MaxAlign)
1692         MaxAlign = EltAlign;
1693       if (MaxAlign == 16)
1694         break;
1695     }
1696   }
1697 }
1698
1699 /// Return the desired alignment for ByVal aggregate
1700 /// function arguments in the caller parameter area. For X86, aggregates
1701 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1702 /// are at 4-byte boundaries.
1703 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1704   if (Subtarget->is64Bit()) {
1705     // Max of 8 and alignment of type.
1706     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1707     if (TyAlign > 8)
1708       return TyAlign;
1709     return 8;
1710   }
1711
1712   unsigned Align = 4;
1713   if (Subtarget->hasSSE1())
1714     getMaxByValAlign(Ty, Align);
1715   return Align;
1716 }
1717
1718 /// Returns the target specific optimal type for load
1719 /// and store operations as a result of memset, memcpy, and memmove
1720 /// lowering. If DstAlign is zero that means it's safe to destination
1721 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1722 /// means there isn't a need to check it against alignment requirement,
1723 /// probably because the source does not need to be loaded. If 'IsMemset' is
1724 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1725 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1726 /// source is constant so it does not need to be loaded.
1727 /// It returns EVT::Other if the type should be determined using generic
1728 /// target-independent logic.
1729 EVT
1730 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1731                                        unsigned DstAlign, unsigned SrcAlign,
1732                                        bool IsMemset, bool ZeroMemset,
1733                                        bool MemcpyStrSrc,
1734                                        MachineFunction &MF) const {
1735   const Function *F = MF.getFunction();
1736   if ((!IsMemset || ZeroMemset) &&
1737       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1738     if (Size >= 16 &&
1739         (Subtarget->isUnalignedMemAccessFast() ||
1740          ((DstAlign == 0 || DstAlign >= 16) &&
1741           (SrcAlign == 0 || SrcAlign >= 16)))) {
1742       if (Size >= 32) {
1743         if (Subtarget->hasInt256())
1744           return MVT::v8i32;
1745         if (Subtarget->hasFp256())
1746           return MVT::v8f32;
1747       }
1748       if (Subtarget->hasSSE2())
1749         return MVT::v4i32;
1750       if (Subtarget->hasSSE1())
1751         return MVT::v4f32;
1752     } else if (!MemcpyStrSrc && Size >= 8 &&
1753                !Subtarget->is64Bit() &&
1754                Subtarget->hasSSE2()) {
1755       // Do not use f64 to lower memcpy if source is string constant. It's
1756       // better to use i32 to avoid the loads.
1757       return MVT::f64;
1758     }
1759   }
1760   if (Subtarget->is64Bit() && Size >= 8)
1761     return MVT::i64;
1762   return MVT::i32;
1763 }
1764
1765 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1766   if (VT == MVT::f32)
1767     return X86ScalarSSEf32;
1768   else if (VT == MVT::f64)
1769     return X86ScalarSSEf64;
1770   return true;
1771 }
1772
1773 bool
1774 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1775                                                   unsigned,
1776                                                   unsigned,
1777                                                   bool *Fast) const {
1778   if (Fast)
1779     *Fast = Subtarget->isUnalignedMemAccessFast();
1780   return true;
1781 }
1782
1783 /// Return the entry encoding for a jump table in the
1784 /// current function.  The returned value is a member of the
1785 /// MachineJumpTableInfo::JTEntryKind enum.
1786 unsigned X86TargetLowering::getJumpTableEncoding() const {
1787   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1788   // symbol.
1789   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1790       Subtarget->isPICStyleGOT())
1791     return MachineJumpTableInfo::EK_Custom32;
1792
1793   // Otherwise, use the normal jump table encoding heuristics.
1794   return TargetLowering::getJumpTableEncoding();
1795 }
1796
1797 bool X86TargetLowering::useSoftFloat() const {
1798   return Subtarget->useSoftFloat();
1799 }
1800
1801 const MCExpr *
1802 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1803                                              const MachineBasicBlock *MBB,
1804                                              unsigned uid,MCContext &Ctx) const{
1805   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1806          Subtarget->isPICStyleGOT());
1807   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1808   // entries.
1809   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1810                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1811 }
1812
1813 /// Returns relocation base for the given PIC jumptable.
1814 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1815                                                     SelectionDAG &DAG) const {
1816   if (!Subtarget->is64Bit())
1817     // This doesn't have SDLoc associated with it, but is not really the
1818     // same as a Register.
1819     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1820   return Table;
1821 }
1822
1823 /// This returns the relocation base for the given PIC jumptable,
1824 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1825 const MCExpr *X86TargetLowering::
1826 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1827                              MCContext &Ctx) const {
1828   // X86-64 uses RIP relative addressing based on the jump table label.
1829   if (Subtarget->isPICStyleRIPRel())
1830     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1831
1832   // Otherwise, the reference is relative to the PIC base.
1833   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1834 }
1835
1836 std::pair<const TargetRegisterClass *, uint8_t>
1837 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1838                                            MVT VT) const {
1839   const TargetRegisterClass *RRC = nullptr;
1840   uint8_t Cost = 1;
1841   switch (VT.SimpleTy) {
1842   default:
1843     return TargetLowering::findRepresentativeClass(TRI, VT);
1844   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1845     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1846     break;
1847   case MVT::x86mmx:
1848     RRC = &X86::VR64RegClass;
1849     break;
1850   case MVT::f32: case MVT::f64:
1851   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1852   case MVT::v4f32: case MVT::v2f64:
1853   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1854   case MVT::v4f64:
1855     RRC = &X86::VR128RegClass;
1856     break;
1857   }
1858   return std::make_pair(RRC, Cost);
1859 }
1860
1861 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1862                                                unsigned &Offset) const {
1863   if (!Subtarget->isTargetLinux())
1864     return false;
1865
1866   if (Subtarget->is64Bit()) {
1867     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1868     Offset = 0x28;
1869     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1870       AddressSpace = 256;
1871     else
1872       AddressSpace = 257;
1873   } else {
1874     // %gs:0x14 on i386
1875     Offset = 0x14;
1876     AddressSpace = 256;
1877   }
1878   return true;
1879 }
1880
1881 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1882                                             unsigned DestAS) const {
1883   assert(SrcAS != DestAS && "Expected different address spaces!");
1884
1885   return SrcAS < 256 && DestAS < 256;
1886 }
1887
1888 //===----------------------------------------------------------------------===//
1889 //               Return Value Calling Convention Implementation
1890 //===----------------------------------------------------------------------===//
1891
1892 #include "X86GenCallingConv.inc"
1893
1894 bool
1895 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1896                                   MachineFunction &MF, bool isVarArg,
1897                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1898                         LLVMContext &Context) const {
1899   SmallVector<CCValAssign, 16> RVLocs;
1900   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1901   return CCInfo.CheckReturn(Outs, RetCC_X86);
1902 }
1903
1904 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1905   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1906   return ScratchRegs;
1907 }
1908
1909 SDValue
1910 X86TargetLowering::LowerReturn(SDValue Chain,
1911                                CallingConv::ID CallConv, bool isVarArg,
1912                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1913                                const SmallVectorImpl<SDValue> &OutVals,
1914                                SDLoc dl, SelectionDAG &DAG) const {
1915   MachineFunction &MF = DAG.getMachineFunction();
1916   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1917
1918   SmallVector<CCValAssign, 16> RVLocs;
1919   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1920   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1921
1922   SDValue Flag;
1923   SmallVector<SDValue, 6> RetOps;
1924   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1925   // Operand #1 = Bytes To Pop
1926   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1927                    MVT::i16));
1928
1929   // Copy the result values into the output registers.
1930   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1931     CCValAssign &VA = RVLocs[i];
1932     assert(VA.isRegLoc() && "Can only return in registers!");
1933     SDValue ValToCopy = OutVals[i];
1934     EVT ValVT = ValToCopy.getValueType();
1935
1936     // Promote values to the appropriate types.
1937     if (VA.getLocInfo() == CCValAssign::SExt)
1938       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1939     else if (VA.getLocInfo() == CCValAssign::ZExt)
1940       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1941     else if (VA.getLocInfo() == CCValAssign::AExt) {
1942       if (ValVT.getScalarType() == MVT::i1)
1943         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1944       else
1945         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1946     }   
1947     else if (VA.getLocInfo() == CCValAssign::BCvt)
1948       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1949
1950     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1951            "Unexpected FP-extend for return value.");
1952
1953     // If this is x86-64, and we disabled SSE, we can't return FP values,
1954     // or SSE or MMX vectors.
1955     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1956          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1957           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1958       report_fatal_error("SSE register return with SSE disabled");
1959     }
1960     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1961     // llvm-gcc has never done it right and no one has noticed, so this
1962     // should be OK for now.
1963     if (ValVT == MVT::f64 &&
1964         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1965       report_fatal_error("SSE2 register return with SSE2 disabled");
1966
1967     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1968     // the RET instruction and handled by the FP Stackifier.
1969     if (VA.getLocReg() == X86::FP0 ||
1970         VA.getLocReg() == X86::FP1) {
1971       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1972       // change the value to the FP stack register class.
1973       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1974         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1975       RetOps.push_back(ValToCopy);
1976       // Don't emit a copytoreg.
1977       continue;
1978     }
1979
1980     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1981     // which is returned in RAX / RDX.
1982     if (Subtarget->is64Bit()) {
1983       if (ValVT == MVT::x86mmx) {
1984         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1985           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1986           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1987                                   ValToCopy);
1988           // If we don't have SSE2 available, convert to v4f32 so the generated
1989           // register is legal.
1990           if (!Subtarget->hasSSE2())
1991             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1992         }
1993       }
1994     }
1995
1996     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1997     Flag = Chain.getValue(1);
1998     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1999   }
2000
2001   // The x86-64 ABIs require that for returning structs by value we copy
2002   // the sret argument into %rax/%eax (depending on ABI) for the return.
2003   // Win32 requires us to put the sret argument to %eax as well.
2004   // We saved the argument into a virtual register in the entry block,
2005   // so now we copy the value out and into %rax/%eax.
2006   //
2007   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2008   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2009   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2010   // either case FuncInfo->setSRetReturnReg() will have been called.
2011   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2012     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2013            "No need for an sret register");
2014     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2015
2016     unsigned RetValReg
2017         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2018           X86::RAX : X86::EAX;
2019     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2020     Flag = Chain.getValue(1);
2021
2022     // RAX/EAX now acts like a return value.
2023     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2024   }
2025
2026   RetOps[0] = Chain;  // Update chain.
2027
2028   // Add the flag if we have it.
2029   if (Flag.getNode())
2030     RetOps.push_back(Flag);
2031
2032   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2033 }
2034
2035 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2036   if (N->getNumValues() != 1)
2037     return false;
2038   if (!N->hasNUsesOfValue(1, 0))
2039     return false;
2040
2041   SDValue TCChain = Chain;
2042   SDNode *Copy = *N->use_begin();
2043   if (Copy->getOpcode() == ISD::CopyToReg) {
2044     // If the copy has a glue operand, we conservatively assume it isn't safe to
2045     // perform a tail call.
2046     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2047       return false;
2048     TCChain = Copy->getOperand(0);
2049   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2050     return false;
2051
2052   bool HasRet = false;
2053   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2054        UI != UE; ++UI) {
2055     if (UI->getOpcode() != X86ISD::RET_FLAG)
2056       return false;
2057     // If we are returning more than one value, we can definitely
2058     // not make a tail call see PR19530
2059     if (UI->getNumOperands() > 4)
2060       return false;
2061     if (UI->getNumOperands() == 4 &&
2062         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2063       return false;
2064     HasRet = true;
2065   }
2066
2067   if (!HasRet)
2068     return false;
2069
2070   Chain = TCChain;
2071   return true;
2072 }
2073
2074 EVT
2075 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2076                                             ISD::NodeType ExtendKind) const {
2077   MVT ReturnMVT;
2078   // TODO: Is this also valid on 32-bit?
2079   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2080     ReturnMVT = MVT::i8;
2081   else
2082     ReturnMVT = MVT::i32;
2083
2084   EVT MinVT = getRegisterType(Context, ReturnMVT);
2085   return VT.bitsLT(MinVT) ? MinVT : VT;
2086 }
2087
2088 /// Lower the result values of a call into the
2089 /// appropriate copies out of appropriate physical registers.
2090 ///
2091 SDValue
2092 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2093                                    CallingConv::ID CallConv, bool isVarArg,
2094                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2095                                    SDLoc dl, SelectionDAG &DAG,
2096                                    SmallVectorImpl<SDValue> &InVals) const {
2097
2098   // Assign locations to each value returned by this call.
2099   SmallVector<CCValAssign, 16> RVLocs;
2100   bool Is64Bit = Subtarget->is64Bit();
2101   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2102                  *DAG.getContext());
2103   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2104
2105   // Copy all of the result registers out of their specified physreg.
2106   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2107     CCValAssign &VA = RVLocs[i];
2108     EVT CopyVT = VA.getLocVT();
2109
2110     // If this is x86-64, and we disabled SSE, we can't return FP values
2111     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2112         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2113       report_fatal_error("SSE register return with SSE disabled");
2114     }
2115
2116     // If we prefer to use the value in xmm registers, copy it out as f80 and
2117     // use a truncate to move it from fp stack reg to xmm reg.
2118     bool RoundAfterCopy = false;
2119     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2120         isScalarFPTypeInSSEReg(VA.getValVT())) {
2121       CopyVT = MVT::f80;
2122       RoundAfterCopy = (CopyVT != VA.getLocVT());
2123     }
2124
2125     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2126                                CopyVT, InFlag).getValue(1);
2127     SDValue Val = Chain.getValue(0);
2128
2129     if (RoundAfterCopy)
2130       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2131                         // This truncation won't change the value.
2132                         DAG.getIntPtrConstant(1, dl));
2133
2134     InFlag = Chain.getValue(2);
2135     InVals.push_back(Val);
2136   }
2137
2138   return Chain;
2139 }
2140
2141 //===----------------------------------------------------------------------===//
2142 //                C & StdCall & Fast Calling Convention implementation
2143 //===----------------------------------------------------------------------===//
2144 //  StdCall calling convention seems to be standard for many Windows' API
2145 //  routines and around. It differs from C calling convention just a little:
2146 //  callee should clean up the stack, not caller. Symbols should be also
2147 //  decorated in some fancy way :) It doesn't support any vector arguments.
2148 //  For info on fast calling convention see Fast Calling Convention (tail call)
2149 //  implementation LowerX86_32FastCCCallTo.
2150
2151 /// CallIsStructReturn - Determines whether a call uses struct return
2152 /// semantics.
2153 enum StructReturnType {
2154   NotStructReturn,
2155   RegStructReturn,
2156   StackStructReturn
2157 };
2158 static StructReturnType
2159 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2160   if (Outs.empty())
2161     return NotStructReturn;
2162
2163   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2164   if (!Flags.isSRet())
2165     return NotStructReturn;
2166   if (Flags.isInReg())
2167     return RegStructReturn;
2168   return StackStructReturn;
2169 }
2170
2171 /// Determines whether a function uses struct return semantics.
2172 static StructReturnType
2173 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2174   if (Ins.empty())
2175     return NotStructReturn;
2176
2177   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2178   if (!Flags.isSRet())
2179     return NotStructReturn;
2180   if (Flags.isInReg())
2181     return RegStructReturn;
2182   return StackStructReturn;
2183 }
2184
2185 /// Make a copy of an aggregate at address specified by "Src" to address
2186 /// "Dst" with size and alignment information specified by the specific
2187 /// parameter attribute. The copy will be passed as a byval function parameter.
2188 static SDValue
2189 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2190                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2191                           SDLoc dl) {
2192   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2193
2194   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2195                        /*isVolatile*/false, /*AlwaysInline=*/true,
2196                        /*isTailCall*/false,
2197                        MachinePointerInfo(), MachinePointerInfo());
2198 }
2199
2200 /// Return true if the calling convention is one that
2201 /// supports tail call optimization.
2202 static bool IsTailCallConvention(CallingConv::ID CC) {
2203   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2204           CC == CallingConv::HiPE);
2205 }
2206
2207 /// \brief Return true if the calling convention is a C calling convention.
2208 static bool IsCCallConvention(CallingConv::ID CC) {
2209   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2210           CC == CallingConv::X86_64_SysV);
2211 }
2212
2213 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2214   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2215     return false;
2216
2217   CallSite CS(CI);
2218   CallingConv::ID CalleeCC = CS.getCallingConv();
2219   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2220     return false;
2221
2222   return true;
2223 }
2224
2225 /// Return true if the function is being made into
2226 /// a tailcall target by changing its ABI.
2227 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2228                                    bool GuaranteedTailCallOpt) {
2229   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2230 }
2231
2232 SDValue
2233 X86TargetLowering::LowerMemArgument(SDValue Chain,
2234                                     CallingConv::ID CallConv,
2235                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2236                                     SDLoc dl, SelectionDAG &DAG,
2237                                     const CCValAssign &VA,
2238                                     MachineFrameInfo *MFI,
2239                                     unsigned i) const {
2240   // Create the nodes corresponding to a load from this parameter slot.
2241   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2242   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2243       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2244   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2245   EVT ValVT;
2246
2247   // If value is passed by pointer we have address passed instead of the value
2248   // itself.
2249   if (VA.getLocInfo() == CCValAssign::Indirect)
2250     ValVT = VA.getLocVT();
2251   else
2252     ValVT = VA.getValVT();
2253
2254   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2255   // changed with more analysis.
2256   // In case of tail call optimization mark all arguments mutable. Since they
2257   // could be overwritten by lowering of arguments in case of a tail call.
2258   if (Flags.isByVal()) {
2259     unsigned Bytes = Flags.getByValSize();
2260     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2261     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2262     return DAG.getFrameIndex(FI, getPointerTy());
2263   } else {
2264     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2265                                     VA.getLocMemOffset(), isImmutable);
2266     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2267     return DAG.getLoad(ValVT, dl, Chain, FIN,
2268                        MachinePointerInfo::getFixedStack(FI),
2269                        false, false, false, 0);
2270   }
2271 }
2272
2273 // FIXME: Get this from tablegen.
2274 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2275                                                 const X86Subtarget *Subtarget) {
2276   assert(Subtarget->is64Bit());
2277
2278   if (Subtarget->isCallingConvWin64(CallConv)) {
2279     static const MCPhysReg GPR64ArgRegsWin64[] = {
2280       X86::RCX, X86::RDX, X86::R8,  X86::R9
2281     };
2282     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2283   }
2284
2285   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2286     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2287   };
2288   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2289 }
2290
2291 // FIXME: Get this from tablegen.
2292 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2293                                                 CallingConv::ID CallConv,
2294                                                 const X86Subtarget *Subtarget) {
2295   assert(Subtarget->is64Bit());
2296   if (Subtarget->isCallingConvWin64(CallConv)) {
2297     // The XMM registers which might contain var arg parameters are shadowed
2298     // in their paired GPR.  So we only need to save the GPR to their home
2299     // slots.
2300     // TODO: __vectorcall will change this.
2301     return None;
2302   }
2303
2304   const Function *Fn = MF.getFunction();
2305   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2306   bool isSoftFloat = Subtarget->useSoftFloat();
2307   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2308          "SSE register cannot be used when SSE is disabled!");
2309   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2310     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2311     // registers.
2312     return None;
2313
2314   static const MCPhysReg XMMArgRegs64Bit[] = {
2315     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2316     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2317   };
2318   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2319 }
2320
2321 SDValue
2322 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2323                                         CallingConv::ID CallConv,
2324                                         bool isVarArg,
2325                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2326                                         SDLoc dl,
2327                                         SelectionDAG &DAG,
2328                                         SmallVectorImpl<SDValue> &InVals)
2329                                           const {
2330   MachineFunction &MF = DAG.getMachineFunction();
2331   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2332   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2333
2334   const Function* Fn = MF.getFunction();
2335   if (Fn->hasExternalLinkage() &&
2336       Subtarget->isTargetCygMing() &&
2337       Fn->getName() == "main")
2338     FuncInfo->setForceFramePointer(true);
2339
2340   MachineFrameInfo *MFI = MF.getFrameInfo();
2341   bool Is64Bit = Subtarget->is64Bit();
2342   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2343
2344   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2345          "Var args not supported with calling convention fastcc, ghc or hipe");
2346
2347   // Assign locations to all of the incoming arguments.
2348   SmallVector<CCValAssign, 16> ArgLocs;
2349   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2350
2351   // Allocate shadow area for Win64
2352   if (IsWin64)
2353     CCInfo.AllocateStack(32, 8);
2354
2355   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2356
2357   unsigned LastVal = ~0U;
2358   SDValue ArgValue;
2359   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2360     CCValAssign &VA = ArgLocs[i];
2361     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2362     // places.
2363     assert(VA.getValNo() != LastVal &&
2364            "Don't support value assigned to multiple locs yet");
2365     (void)LastVal;
2366     LastVal = VA.getValNo();
2367
2368     if (VA.isRegLoc()) {
2369       EVT RegVT = VA.getLocVT();
2370       const TargetRegisterClass *RC;
2371       if (RegVT == MVT::i32)
2372         RC = &X86::GR32RegClass;
2373       else if (Is64Bit && RegVT == MVT::i64)
2374         RC = &X86::GR64RegClass;
2375       else if (RegVT == MVT::f32)
2376         RC = &X86::FR32RegClass;
2377       else if (RegVT == MVT::f64)
2378         RC = &X86::FR64RegClass;
2379       else if (RegVT.is512BitVector())
2380         RC = &X86::VR512RegClass;
2381       else if (RegVT.is256BitVector())
2382         RC = &X86::VR256RegClass;
2383       else if (RegVT.is128BitVector())
2384         RC = &X86::VR128RegClass;
2385       else if (RegVT == MVT::x86mmx)
2386         RC = &X86::VR64RegClass;
2387       else if (RegVT == MVT::i1)
2388         RC = &X86::VK1RegClass;
2389       else if (RegVT == MVT::v8i1)
2390         RC = &X86::VK8RegClass;
2391       else if (RegVT == MVT::v16i1)
2392         RC = &X86::VK16RegClass;
2393       else if (RegVT == MVT::v32i1)
2394         RC = &X86::VK32RegClass;
2395       else if (RegVT == MVT::v64i1)
2396         RC = &X86::VK64RegClass;
2397       else
2398         llvm_unreachable("Unknown argument type!");
2399
2400       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2401       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2402
2403       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2404       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2405       // right size.
2406       if (VA.getLocInfo() == CCValAssign::SExt)
2407         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2408                                DAG.getValueType(VA.getValVT()));
2409       else if (VA.getLocInfo() == CCValAssign::ZExt)
2410         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2411                                DAG.getValueType(VA.getValVT()));
2412       else if (VA.getLocInfo() == CCValAssign::BCvt)
2413         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2414
2415       if (VA.isExtInLoc()) {
2416         // Handle MMX values passed in XMM regs.
2417         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2418           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2419         else
2420           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2421       }
2422     } else {
2423       assert(VA.isMemLoc());
2424       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2425     }
2426
2427     // If value is passed via pointer - do a load.
2428     if (VA.getLocInfo() == CCValAssign::Indirect)
2429       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2430                              MachinePointerInfo(), false, false, false, 0);
2431
2432     InVals.push_back(ArgValue);
2433   }
2434
2435   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2436     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2437       // The x86-64 ABIs require that for returning structs by value we copy
2438       // the sret argument into %rax/%eax (depending on ABI) for the return.
2439       // Win32 requires us to put the sret argument to %eax as well.
2440       // Save the argument into a virtual register so that we can access it
2441       // from the return points.
2442       if (Ins[i].Flags.isSRet()) {
2443         unsigned Reg = FuncInfo->getSRetReturnReg();
2444         if (!Reg) {
2445           MVT PtrTy = getPointerTy();
2446           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2447           FuncInfo->setSRetReturnReg(Reg);
2448         }
2449         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2450         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2451         break;
2452       }
2453     }
2454   }
2455
2456   unsigned StackSize = CCInfo.getNextStackOffset();
2457   // Align stack specially for tail calls.
2458   if (FuncIsMadeTailCallSafe(CallConv,
2459                              MF.getTarget().Options.GuaranteedTailCallOpt))
2460     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2461
2462   // If the function takes variable number of arguments, make a frame index for
2463   // the start of the first vararg value... for expansion of llvm.va_start. We
2464   // can skip this if there are no va_start calls.
2465   if (MFI->hasVAStart() &&
2466       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2467                    CallConv != CallingConv::X86_ThisCall))) {
2468     FuncInfo->setVarArgsFrameIndex(
2469         MFI->CreateFixedObject(1, StackSize, true));
2470   }
2471
2472   MachineModuleInfo &MMI = MF.getMMI();
2473   const Function *WinEHParent = nullptr;
2474   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2475     WinEHParent = MMI.getWinEHParent(Fn);
2476   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2477   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2478
2479   // Figure out if XMM registers are in use.
2480   assert(!(Subtarget->useSoftFloat() &&
2481            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2482          "SSE register cannot be used when SSE is disabled!");
2483
2484   // 64-bit calling conventions support varargs and register parameters, so we
2485   // have to do extra work to spill them in the prologue.
2486   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2487     // Find the first unallocated argument registers.
2488     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2489     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2490     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2491     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2492     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2493            "SSE register cannot be used when SSE is disabled!");
2494
2495     // Gather all the live in physical registers.
2496     SmallVector<SDValue, 6> LiveGPRs;
2497     SmallVector<SDValue, 8> LiveXMMRegs;
2498     SDValue ALVal;
2499     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2500       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2501       LiveGPRs.push_back(
2502           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2503     }
2504     if (!ArgXMMs.empty()) {
2505       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2506       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2507       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2508         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2509         LiveXMMRegs.push_back(
2510             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2511       }
2512     }
2513
2514     if (IsWin64) {
2515       // Get to the caller-allocated home save location.  Add 8 to account
2516       // for the return address.
2517       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2518       FuncInfo->setRegSaveFrameIndex(
2519           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2520       // Fixup to set vararg frame on shadow area (4 x i64).
2521       if (NumIntRegs < 4)
2522         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2523     } else {
2524       // For X86-64, if there are vararg parameters that are passed via
2525       // registers, then we must store them to their spots on the stack so
2526       // they may be loaded by deferencing the result of va_next.
2527       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2528       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2529       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2530           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2531     }
2532
2533     // Store the integer parameter registers.
2534     SmallVector<SDValue, 8> MemOps;
2535     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2536                                       getPointerTy());
2537     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2538     for (SDValue Val : LiveGPRs) {
2539       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2540                                 DAG.getIntPtrConstant(Offset, dl));
2541       SDValue Store =
2542         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2543                      MachinePointerInfo::getFixedStack(
2544                        FuncInfo->getRegSaveFrameIndex(), Offset),
2545                      false, false, 0);
2546       MemOps.push_back(Store);
2547       Offset += 8;
2548     }
2549
2550     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2551       // Now store the XMM (fp + vector) parameter registers.
2552       SmallVector<SDValue, 12> SaveXMMOps;
2553       SaveXMMOps.push_back(Chain);
2554       SaveXMMOps.push_back(ALVal);
2555       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2556                              FuncInfo->getRegSaveFrameIndex(), dl));
2557       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2558                              FuncInfo->getVarArgsFPOffset(), dl));
2559       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2560                         LiveXMMRegs.end());
2561       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2562                                    MVT::Other, SaveXMMOps));
2563     }
2564
2565     if (!MemOps.empty())
2566       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2567   } else if (IsWinEHOutlined) {
2568     // Get to the caller-allocated home save location.  Add 8 to account
2569     // for the return address.
2570     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2571     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2572         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2573
2574     MMI.getWinEHFuncInfo(Fn)
2575         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2576         FuncInfo->getRegSaveFrameIndex();
2577
2578     // Store the second integer parameter (rdx) into rsp+16 relative to the
2579     // stack pointer at the entry of the function.
2580     SDValue RSFIN =
2581         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2582     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2583     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2584     Chain = DAG.getStore(
2585         Val.getValue(1), dl, Val, RSFIN,
2586         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2587         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2588   }
2589
2590   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2591     // Find the largest legal vector type.
2592     MVT VecVT = MVT::Other;
2593     // FIXME: Only some x86_32 calling conventions support AVX512.
2594     if (Subtarget->hasAVX512() &&
2595         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2596                      CallConv == CallingConv::Intel_OCL_BI)))
2597       VecVT = MVT::v16f32;
2598     else if (Subtarget->hasAVX())
2599       VecVT = MVT::v8f32;
2600     else if (Subtarget->hasSSE2())
2601       VecVT = MVT::v4f32;
2602
2603     // We forward some GPRs and some vector types.
2604     SmallVector<MVT, 2> RegParmTypes;
2605     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2606     RegParmTypes.push_back(IntVT);
2607     if (VecVT != MVT::Other)
2608       RegParmTypes.push_back(VecVT);
2609
2610     // Compute the set of forwarded registers. The rest are scratch.
2611     SmallVectorImpl<ForwardedRegister> &Forwards =
2612         FuncInfo->getForwardedMustTailRegParms();
2613     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2614
2615     // Conservatively forward AL on x86_64, since it might be used for varargs.
2616     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2617       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2618       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2619     }
2620
2621     // Copy all forwards from physical to virtual registers.
2622     for (ForwardedRegister &F : Forwards) {
2623       // FIXME: Can we use a less constrained schedule?
2624       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2625       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2626       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2627     }
2628   }
2629
2630   // Some CCs need callee pop.
2631   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2632                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2633     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2634   } else {
2635     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2636     // If this is an sret function, the return should pop the hidden pointer.
2637     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2638         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2639         argsAreStructReturn(Ins) == StackStructReturn)
2640       FuncInfo->setBytesToPopOnReturn(4);
2641   }
2642
2643   if (!Is64Bit) {
2644     // RegSaveFrameIndex is X86-64 only.
2645     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2646     if (CallConv == CallingConv::X86_FastCall ||
2647         CallConv == CallingConv::X86_ThisCall)
2648       // fastcc functions can't have varargs.
2649       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2650   }
2651
2652   FuncInfo->setArgumentStackSize(StackSize);
2653
2654   if (IsWinEHParent) {
2655     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2656     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2657     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2658     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2659     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2660                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2661                          /*isVolatile=*/true,
2662                          /*isNonTemporal=*/false, /*Alignment=*/0);
2663   }
2664
2665   return Chain;
2666 }
2667
2668 SDValue
2669 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2670                                     SDValue StackPtr, SDValue Arg,
2671                                     SDLoc dl, SelectionDAG &DAG,
2672                                     const CCValAssign &VA,
2673                                     ISD::ArgFlagsTy Flags) const {
2674   unsigned LocMemOffset = VA.getLocMemOffset();
2675   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2676   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2677   if (Flags.isByVal())
2678     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2679
2680   return DAG.getStore(Chain, dl, Arg, PtrOff,
2681                       MachinePointerInfo::getStack(LocMemOffset),
2682                       false, false, 0);
2683 }
2684
2685 /// Emit a load of return address if tail call
2686 /// optimization is performed and it is required.
2687 SDValue
2688 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2689                                            SDValue &OutRetAddr, SDValue Chain,
2690                                            bool IsTailCall, bool Is64Bit,
2691                                            int FPDiff, SDLoc dl) const {
2692   // Adjust the Return address stack slot.
2693   EVT VT = getPointerTy();
2694   OutRetAddr = getReturnAddressFrameIndex(DAG);
2695
2696   // Load the "old" Return address.
2697   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2698                            false, false, false, 0);
2699   return SDValue(OutRetAddr.getNode(), 1);
2700 }
2701
2702 /// Emit a store of the return address if tail call
2703 /// optimization is performed and it is required (FPDiff!=0).
2704 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2705                                         SDValue Chain, SDValue RetAddrFrIdx,
2706                                         EVT PtrVT, unsigned SlotSize,
2707                                         int FPDiff, SDLoc dl) {
2708   // Store the return address to the appropriate stack slot.
2709   if (!FPDiff) return Chain;
2710   // Calculate the new stack slot for the return address.
2711   int NewReturnAddrFI =
2712     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2713                                          false);
2714   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2715   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2716                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2717                        false, false, 0);
2718   return Chain;
2719 }
2720
2721 SDValue
2722 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2723                              SmallVectorImpl<SDValue> &InVals) const {
2724   SelectionDAG &DAG                     = CLI.DAG;
2725   SDLoc &dl                             = CLI.DL;
2726   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2727   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2728   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2729   SDValue Chain                         = CLI.Chain;
2730   SDValue Callee                        = CLI.Callee;
2731   CallingConv::ID CallConv              = CLI.CallConv;
2732   bool &isTailCall                      = CLI.IsTailCall;
2733   bool isVarArg                         = CLI.IsVarArg;
2734
2735   MachineFunction &MF = DAG.getMachineFunction();
2736   bool Is64Bit        = Subtarget->is64Bit();
2737   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2738   StructReturnType SR = callIsStructReturn(Outs);
2739   bool IsSibcall      = false;
2740   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2741
2742   if (MF.getTarget().Options.DisableTailCalls)
2743     isTailCall = false;
2744
2745   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2746   if (IsMustTail) {
2747     // Force this to be a tail call.  The verifier rules are enough to ensure
2748     // that we can lower this successfully without moving the return address
2749     // around.
2750     isTailCall = true;
2751   } else if (isTailCall) {
2752     // Check if it's really possible to do a tail call.
2753     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2754                     isVarArg, SR != NotStructReturn,
2755                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2756                     Outs, OutVals, Ins, DAG);
2757
2758     // Sibcalls are automatically detected tailcalls which do not require
2759     // ABI changes.
2760     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2761       IsSibcall = true;
2762
2763     if (isTailCall)
2764       ++NumTailCalls;
2765   }
2766
2767   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2768          "Var args not supported with calling convention fastcc, ghc or hipe");
2769
2770   // Analyze operands of the call, assigning locations to each operand.
2771   SmallVector<CCValAssign, 16> ArgLocs;
2772   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2773
2774   // Allocate shadow area for Win64
2775   if (IsWin64)
2776     CCInfo.AllocateStack(32, 8);
2777
2778   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2779
2780   // Get a count of how many bytes are to be pushed on the stack.
2781   unsigned NumBytes = CCInfo.getNextStackOffset();
2782   if (IsSibcall)
2783     // This is a sibcall. The memory operands are available in caller's
2784     // own caller's stack.
2785     NumBytes = 0;
2786   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2787            IsTailCallConvention(CallConv))
2788     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2789
2790   int FPDiff = 0;
2791   if (isTailCall && !IsSibcall && !IsMustTail) {
2792     // Lower arguments at fp - stackoffset + fpdiff.
2793     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2794
2795     FPDiff = NumBytesCallerPushed - NumBytes;
2796
2797     // Set the delta of movement of the returnaddr stackslot.
2798     // But only set if delta is greater than previous delta.
2799     if (FPDiff < X86Info->getTCReturnAddrDelta())
2800       X86Info->setTCReturnAddrDelta(FPDiff);
2801   }
2802
2803   unsigned NumBytesToPush = NumBytes;
2804   unsigned NumBytesToPop = NumBytes;
2805
2806   // If we have an inalloca argument, all stack space has already been allocated
2807   // for us and be right at the top of the stack.  We don't support multiple
2808   // arguments passed in memory when using inalloca.
2809   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2810     NumBytesToPush = 0;
2811     if (!ArgLocs.back().isMemLoc())
2812       report_fatal_error("cannot use inalloca attribute on a register "
2813                          "parameter");
2814     if (ArgLocs.back().getLocMemOffset() != 0)
2815       report_fatal_error("any parameter with the inalloca attribute must be "
2816                          "the only memory argument");
2817   }
2818
2819   if (!IsSibcall)
2820     Chain = DAG.getCALLSEQ_START(
2821         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2822
2823   SDValue RetAddrFrIdx;
2824   // Load return address for tail calls.
2825   if (isTailCall && FPDiff)
2826     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2827                                     Is64Bit, FPDiff, dl);
2828
2829   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2830   SmallVector<SDValue, 8> MemOpChains;
2831   SDValue StackPtr;
2832
2833   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2834   // of tail call optimization arguments are handle later.
2835   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2836   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2837     // Skip inalloca arguments, they have already been written.
2838     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2839     if (Flags.isInAlloca())
2840       continue;
2841
2842     CCValAssign &VA = ArgLocs[i];
2843     EVT RegVT = VA.getLocVT();
2844     SDValue Arg = OutVals[i];
2845     bool isByVal = Flags.isByVal();
2846
2847     // Promote the value if needed.
2848     switch (VA.getLocInfo()) {
2849     default: llvm_unreachable("Unknown loc info!");
2850     case CCValAssign::Full: break;
2851     case CCValAssign::SExt:
2852       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2853       break;
2854     case CCValAssign::ZExt:
2855       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2856       break;
2857     case CCValAssign::AExt:
2858       if (Arg.getValueType().getScalarType() == MVT::i1)
2859         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2860       else if (RegVT.is128BitVector()) {
2861         // Special case: passing MMX values in XMM registers.
2862         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2863         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2864         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2865       } else
2866         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2867       break;
2868     case CCValAssign::BCvt:
2869       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2870       break;
2871     case CCValAssign::Indirect: {
2872       // Store the argument.
2873       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2874       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2875       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2876                            MachinePointerInfo::getFixedStack(FI),
2877                            false, false, 0);
2878       Arg = SpillSlot;
2879       break;
2880     }
2881     }
2882
2883     if (VA.isRegLoc()) {
2884       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2885       if (isVarArg && IsWin64) {
2886         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2887         // shadow reg if callee is a varargs function.
2888         unsigned ShadowReg = 0;
2889         switch (VA.getLocReg()) {
2890         case X86::XMM0: ShadowReg = X86::RCX; break;
2891         case X86::XMM1: ShadowReg = X86::RDX; break;
2892         case X86::XMM2: ShadowReg = X86::R8; break;
2893         case X86::XMM3: ShadowReg = X86::R9; break;
2894         }
2895         if (ShadowReg)
2896           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2897       }
2898     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2899       assert(VA.isMemLoc());
2900       if (!StackPtr.getNode())
2901         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2902                                       getPointerTy());
2903       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2904                                              dl, DAG, VA, Flags));
2905     }
2906   }
2907
2908   if (!MemOpChains.empty())
2909     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2910
2911   if (Subtarget->isPICStyleGOT()) {
2912     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2913     // GOT pointer.
2914     if (!isTailCall) {
2915       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2916                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2917     } else {
2918       // If we are tail calling and generating PIC/GOT style code load the
2919       // address of the callee into ECX. The value in ecx is used as target of
2920       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2921       // for tail calls on PIC/GOT architectures. Normally we would just put the
2922       // address of GOT into ebx and then call target@PLT. But for tail calls
2923       // ebx would be restored (since ebx is callee saved) before jumping to the
2924       // target@PLT.
2925
2926       // Note: The actual moving to ECX is done further down.
2927       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2928       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2929           !G->getGlobal()->hasProtectedVisibility())
2930         Callee = LowerGlobalAddress(Callee, DAG);
2931       else if (isa<ExternalSymbolSDNode>(Callee))
2932         Callee = LowerExternalSymbol(Callee, DAG);
2933     }
2934   }
2935
2936   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2937     // From AMD64 ABI document:
2938     // For calls that may call functions that use varargs or stdargs
2939     // (prototype-less calls or calls to functions containing ellipsis (...) in
2940     // the declaration) %al is used as hidden argument to specify the number
2941     // of SSE registers used. The contents of %al do not need to match exactly
2942     // the number of registers, but must be an ubound on the number of SSE
2943     // registers used and is in the range 0 - 8 inclusive.
2944
2945     // Count the number of XMM registers allocated.
2946     static const MCPhysReg XMMArgRegs[] = {
2947       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2948       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2949     };
2950     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2951     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2952            && "SSE registers cannot be used when SSE is disabled");
2953
2954     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2955                                         DAG.getConstant(NumXMMRegs, dl,
2956                                                         MVT::i8)));
2957   }
2958
2959   if (isVarArg && IsMustTail) {
2960     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2961     for (const auto &F : Forwards) {
2962       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2963       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2964     }
2965   }
2966
2967   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2968   // don't need this because the eligibility check rejects calls that require
2969   // shuffling arguments passed in memory.
2970   if (!IsSibcall && isTailCall) {
2971     // Force all the incoming stack arguments to be loaded from the stack
2972     // before any new outgoing arguments are stored to the stack, because the
2973     // outgoing stack slots may alias the incoming argument stack slots, and
2974     // the alias isn't otherwise explicit. This is slightly more conservative
2975     // than necessary, because it means that each store effectively depends
2976     // on every argument instead of just those arguments it would clobber.
2977     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2978
2979     SmallVector<SDValue, 8> MemOpChains2;
2980     SDValue FIN;
2981     int FI = 0;
2982     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2983       CCValAssign &VA = ArgLocs[i];
2984       if (VA.isRegLoc())
2985         continue;
2986       assert(VA.isMemLoc());
2987       SDValue Arg = OutVals[i];
2988       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2989       // Skip inalloca arguments.  They don't require any work.
2990       if (Flags.isInAlloca())
2991         continue;
2992       // Create frame index.
2993       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2994       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2995       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2996       FIN = DAG.getFrameIndex(FI, getPointerTy());
2997
2998       if (Flags.isByVal()) {
2999         // Copy relative to framepointer.
3000         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3001         if (!StackPtr.getNode())
3002           StackPtr = DAG.getCopyFromReg(Chain, dl,
3003                                         RegInfo->getStackRegister(),
3004                                         getPointerTy());
3005         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3006
3007         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3008                                                          ArgChain,
3009                                                          Flags, DAG, dl));
3010       } else {
3011         // Store relative to framepointer.
3012         MemOpChains2.push_back(
3013           DAG.getStore(ArgChain, dl, Arg, FIN,
3014                        MachinePointerInfo::getFixedStack(FI),
3015                        false, false, 0));
3016       }
3017     }
3018
3019     if (!MemOpChains2.empty())
3020       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3021
3022     // Store the return address to the appropriate stack slot.
3023     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3024                                      getPointerTy(), RegInfo->getSlotSize(),
3025                                      FPDiff, dl);
3026   }
3027
3028   // Build a sequence of copy-to-reg nodes chained together with token chain
3029   // and flag operands which copy the outgoing args into registers.
3030   SDValue InFlag;
3031   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3032     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3033                              RegsToPass[i].second, InFlag);
3034     InFlag = Chain.getValue(1);
3035   }
3036
3037   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3038     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3039     // In the 64-bit large code model, we have to make all calls
3040     // through a register, since the call instruction's 32-bit
3041     // pc-relative offset may not be large enough to hold the whole
3042     // address.
3043   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3044     // If the callee is a GlobalAddress node (quite common, every direct call
3045     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3046     // it.
3047     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3048
3049     // We should use extra load for direct calls to dllimported functions in
3050     // non-JIT mode.
3051     const GlobalValue *GV = G->getGlobal();
3052     if (!GV->hasDLLImportStorageClass()) {
3053       unsigned char OpFlags = 0;
3054       bool ExtraLoad = false;
3055       unsigned WrapperKind = ISD::DELETED_NODE;
3056
3057       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3058       // external symbols most go through the PLT in PIC mode.  If the symbol
3059       // has hidden or protected visibility, or if it is static or local, then
3060       // we don't need to use the PLT - we can directly call it.
3061       if (Subtarget->isTargetELF() &&
3062           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3063           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3064         OpFlags = X86II::MO_PLT;
3065       } else if (Subtarget->isPICStyleStubAny() &&
3066                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3067                  (!Subtarget->getTargetTriple().isMacOSX() ||
3068                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3069         // PC-relative references to external symbols should go through $stub,
3070         // unless we're building with the leopard linker or later, which
3071         // automatically synthesizes these stubs.
3072         OpFlags = X86II::MO_DARWIN_STUB;
3073       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3074                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3075         // If the function is marked as non-lazy, generate an indirect call
3076         // which loads from the GOT directly. This avoids runtime overhead
3077         // at the cost of eager binding (and one extra byte of encoding).
3078         OpFlags = X86II::MO_GOTPCREL;
3079         WrapperKind = X86ISD::WrapperRIP;
3080         ExtraLoad = true;
3081       }
3082
3083       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3084                                           G->getOffset(), OpFlags);
3085
3086       // Add a wrapper if needed.
3087       if (WrapperKind != ISD::DELETED_NODE)
3088         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3089       // Add extra indirection if needed.
3090       if (ExtraLoad)
3091         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3092                              MachinePointerInfo::getGOT(),
3093                              false, false, false, 0);
3094     }
3095   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3096     unsigned char OpFlags = 0;
3097
3098     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3099     // external symbols should go through the PLT.
3100     if (Subtarget->isTargetELF() &&
3101         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3102       OpFlags = X86II::MO_PLT;
3103     } else if (Subtarget->isPICStyleStubAny() &&
3104                (!Subtarget->getTargetTriple().isMacOSX() ||
3105                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3106       // PC-relative references to external symbols should go through $stub,
3107       // unless we're building with the leopard linker or later, which
3108       // automatically synthesizes these stubs.
3109       OpFlags = X86II::MO_DARWIN_STUB;
3110     }
3111
3112     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3113                                          OpFlags);
3114   } else if (Subtarget->isTarget64BitILP32() &&
3115              Callee->getValueType(0) == MVT::i32) {
3116     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3117     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3118   }
3119
3120   // Returns a chain & a flag for retval copy to use.
3121   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3122   SmallVector<SDValue, 8> Ops;
3123
3124   if (!IsSibcall && isTailCall) {
3125     Chain = DAG.getCALLSEQ_END(Chain,
3126                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3127                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3128     InFlag = Chain.getValue(1);
3129   }
3130
3131   Ops.push_back(Chain);
3132   Ops.push_back(Callee);
3133
3134   if (isTailCall)
3135     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3136
3137   // Add argument registers to the end of the list so that they are known live
3138   // into the call.
3139   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3140     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3141                                   RegsToPass[i].second.getValueType()));
3142
3143   // Add a register mask operand representing the call-preserved registers.
3144   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3145   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3146   assert(Mask && "Missing call preserved mask for calling convention");
3147   Ops.push_back(DAG.getRegisterMask(Mask));
3148
3149   if (InFlag.getNode())
3150     Ops.push_back(InFlag);
3151
3152   if (isTailCall) {
3153     // We used to do:
3154     //// If this is the first return lowered for this function, add the regs
3155     //// to the liveout set for the function.
3156     // This isn't right, although it's probably harmless on x86; liveouts
3157     // should be computed from returns not tail calls.  Consider a void
3158     // function making a tail call to a function returning int.
3159     MF.getFrameInfo()->setHasTailCall();
3160     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3161   }
3162
3163   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3164   InFlag = Chain.getValue(1);
3165
3166   // Create the CALLSEQ_END node.
3167   unsigned NumBytesForCalleeToPop;
3168   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3169                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3170     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3171   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3172            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3173            SR == StackStructReturn)
3174     // If this is a call to a struct-return function, the callee
3175     // pops the hidden struct pointer, so we have to push it back.
3176     // This is common for Darwin/X86, Linux & Mingw32 targets.
3177     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3178     NumBytesForCalleeToPop = 4;
3179   else
3180     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3181
3182   // Returns a flag for retval copy to use.
3183   if (!IsSibcall) {
3184     Chain = DAG.getCALLSEQ_END(Chain,
3185                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3186                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3187                                                      true),
3188                                InFlag, dl);
3189     InFlag = Chain.getValue(1);
3190   }
3191
3192   // Handle result values, copying them out of physregs into vregs that we
3193   // return.
3194   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3195                          Ins, dl, DAG, InVals);
3196 }
3197
3198 //===----------------------------------------------------------------------===//
3199 //                Fast Calling Convention (tail call) implementation
3200 //===----------------------------------------------------------------------===//
3201
3202 //  Like std call, callee cleans arguments, convention except that ECX is
3203 //  reserved for storing the tail called function address. Only 2 registers are
3204 //  free for argument passing (inreg). Tail call optimization is performed
3205 //  provided:
3206 //                * tailcallopt is enabled
3207 //                * caller/callee are fastcc
3208 //  On X86_64 architecture with GOT-style position independent code only local
3209 //  (within module) calls are supported at the moment.
3210 //  To keep the stack aligned according to platform abi the function
3211 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3212 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3213 //  If a tail called function callee has more arguments than the caller the
3214 //  caller needs to make sure that there is room to move the RETADDR to. This is
3215 //  achieved by reserving an area the size of the argument delta right after the
3216 //  original RETADDR, but before the saved framepointer or the spilled registers
3217 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3218 //  stack layout:
3219 //    arg1
3220 //    arg2
3221 //    RETADDR
3222 //    [ new RETADDR
3223 //      move area ]
3224 //    (possible EBP)
3225 //    ESI
3226 //    EDI
3227 //    local1 ..
3228
3229 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3230 /// for a 16 byte align requirement.
3231 unsigned
3232 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3233                                                SelectionDAG& DAG) const {
3234   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3235   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3236   unsigned StackAlignment = TFI.getStackAlignment();
3237   uint64_t AlignMask = StackAlignment - 1;
3238   int64_t Offset = StackSize;
3239   unsigned SlotSize = RegInfo->getSlotSize();
3240   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3241     // Number smaller than 12 so just add the difference.
3242     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3243   } else {
3244     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3245     Offset = ((~AlignMask) & Offset) + StackAlignment +
3246       (StackAlignment-SlotSize);
3247   }
3248   return Offset;
3249 }
3250
3251 /// MatchingStackOffset - Return true if the given stack call argument is
3252 /// already available in the same position (relatively) of the caller's
3253 /// incoming argument stack.
3254 static
3255 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3256                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3257                          const X86InstrInfo *TII) {
3258   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3259   int FI = INT_MAX;
3260   if (Arg.getOpcode() == ISD::CopyFromReg) {
3261     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3262     if (!TargetRegisterInfo::isVirtualRegister(VR))
3263       return false;
3264     MachineInstr *Def = MRI->getVRegDef(VR);
3265     if (!Def)
3266       return false;
3267     if (!Flags.isByVal()) {
3268       if (!TII->isLoadFromStackSlot(Def, FI))
3269         return false;
3270     } else {
3271       unsigned Opcode = Def->getOpcode();
3272       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3273            Opcode == X86::LEA64_32r) &&
3274           Def->getOperand(1).isFI()) {
3275         FI = Def->getOperand(1).getIndex();
3276         Bytes = Flags.getByValSize();
3277       } else
3278         return false;
3279     }
3280   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3281     if (Flags.isByVal())
3282       // ByVal argument is passed in as a pointer but it's now being
3283       // dereferenced. e.g.
3284       // define @foo(%struct.X* %A) {
3285       //   tail call @bar(%struct.X* byval %A)
3286       // }
3287       return false;
3288     SDValue Ptr = Ld->getBasePtr();
3289     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3290     if (!FINode)
3291       return false;
3292     FI = FINode->getIndex();
3293   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3294     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3295     FI = FINode->getIndex();
3296     Bytes = Flags.getByValSize();
3297   } else
3298     return false;
3299
3300   assert(FI != INT_MAX);
3301   if (!MFI->isFixedObjectIndex(FI))
3302     return false;
3303   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3304 }
3305
3306 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3307 /// for tail call optimization. Targets which want to do tail call
3308 /// optimization should implement this function.
3309 bool
3310 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3311                                                      CallingConv::ID CalleeCC,
3312                                                      bool isVarArg,
3313                                                      bool isCalleeStructRet,
3314                                                      bool isCallerStructRet,
3315                                                      Type *RetTy,
3316                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3317                                     const SmallVectorImpl<SDValue> &OutVals,
3318                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3319                                                      SelectionDAG &DAG) const {
3320   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3321     return false;
3322
3323   // If -tailcallopt is specified, make fastcc functions tail-callable.
3324   const MachineFunction &MF = DAG.getMachineFunction();
3325   const Function *CallerF = MF.getFunction();
3326
3327   // If the function return type is x86_fp80 and the callee return type is not,
3328   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3329   // perform a tailcall optimization here.
3330   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3331     return false;
3332
3333   CallingConv::ID CallerCC = CallerF->getCallingConv();
3334   bool CCMatch = CallerCC == CalleeCC;
3335   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3336   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3337
3338   // Win64 functions have extra shadow space for argument homing. Don't do the
3339   // sibcall if the caller and callee have mismatched expectations for this
3340   // space.
3341   if (IsCalleeWin64 != IsCallerWin64)
3342     return false;
3343
3344   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3345     if (IsTailCallConvention(CalleeCC) && CCMatch)
3346       return true;
3347     return false;
3348   }
3349
3350   // Look for obvious safe cases to perform tail call optimization that do not
3351   // require ABI changes. This is what gcc calls sibcall.
3352
3353   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3354   // emit a special epilogue.
3355   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3356   if (RegInfo->needsStackRealignment(MF))
3357     return false;
3358
3359   // Also avoid sibcall optimization if either caller or callee uses struct
3360   // return semantics.
3361   if (isCalleeStructRet || isCallerStructRet)
3362     return false;
3363
3364   // An stdcall/thiscall caller is expected to clean up its arguments; the
3365   // callee isn't going to do that.
3366   // FIXME: this is more restrictive than needed. We could produce a tailcall
3367   // when the stack adjustment matches. For example, with a thiscall that takes
3368   // only one argument.
3369   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3370                    CallerCC == CallingConv::X86_ThisCall))
3371     return false;
3372
3373   // Do not sibcall optimize vararg calls unless all arguments are passed via
3374   // registers.
3375   if (isVarArg && !Outs.empty()) {
3376
3377     // Optimizing for varargs on Win64 is unlikely to be safe without
3378     // additional testing.
3379     if (IsCalleeWin64 || IsCallerWin64)
3380       return false;
3381
3382     SmallVector<CCValAssign, 16> ArgLocs;
3383     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3384                    *DAG.getContext());
3385
3386     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3387     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3388       if (!ArgLocs[i].isRegLoc())
3389         return false;
3390   }
3391
3392   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3393   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3394   // this into a sibcall.
3395   bool Unused = false;
3396   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3397     if (!Ins[i].Used) {
3398       Unused = true;
3399       break;
3400     }
3401   }
3402   if (Unused) {
3403     SmallVector<CCValAssign, 16> RVLocs;
3404     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3405                    *DAG.getContext());
3406     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3407     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3408       CCValAssign &VA = RVLocs[i];
3409       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3410         return false;
3411     }
3412   }
3413
3414   // If the calling conventions do not match, then we'd better make sure the
3415   // results are returned in the same way as what the caller expects.
3416   if (!CCMatch) {
3417     SmallVector<CCValAssign, 16> RVLocs1;
3418     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3419                     *DAG.getContext());
3420     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3421
3422     SmallVector<CCValAssign, 16> RVLocs2;
3423     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3424                     *DAG.getContext());
3425     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3426
3427     if (RVLocs1.size() != RVLocs2.size())
3428       return false;
3429     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3430       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3431         return false;
3432       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3433         return false;
3434       if (RVLocs1[i].isRegLoc()) {
3435         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3436           return false;
3437       } else {
3438         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3439           return false;
3440       }
3441     }
3442   }
3443
3444   // If the callee takes no arguments then go on to check the results of the
3445   // call.
3446   if (!Outs.empty()) {
3447     // Check if stack adjustment is needed. For now, do not do this if any
3448     // argument is passed on the stack.
3449     SmallVector<CCValAssign, 16> ArgLocs;
3450     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3451                    *DAG.getContext());
3452
3453     // Allocate shadow area for Win64
3454     if (IsCalleeWin64)
3455       CCInfo.AllocateStack(32, 8);
3456
3457     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3458     if (CCInfo.getNextStackOffset()) {
3459       MachineFunction &MF = DAG.getMachineFunction();
3460       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3461         return false;
3462
3463       // Check if the arguments are already laid out in the right way as
3464       // the caller's fixed stack objects.
3465       MachineFrameInfo *MFI = MF.getFrameInfo();
3466       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3467       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3468       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3469         CCValAssign &VA = ArgLocs[i];
3470         SDValue Arg = OutVals[i];
3471         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3472         if (VA.getLocInfo() == CCValAssign::Indirect)
3473           return false;
3474         if (!VA.isRegLoc()) {
3475           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3476                                    MFI, MRI, TII))
3477             return false;
3478         }
3479       }
3480     }
3481
3482     // If the tailcall address may be in a register, then make sure it's
3483     // possible to register allocate for it. In 32-bit, the call address can
3484     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3485     // callee-saved registers are restored. These happen to be the same
3486     // registers used to pass 'inreg' arguments so watch out for those.
3487     if (!Subtarget->is64Bit() &&
3488         ((!isa<GlobalAddressSDNode>(Callee) &&
3489           !isa<ExternalSymbolSDNode>(Callee)) ||
3490          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3491       unsigned NumInRegs = 0;
3492       // In PIC we need an extra register to formulate the address computation
3493       // for the callee.
3494       unsigned MaxInRegs =
3495         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3496
3497       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3498         CCValAssign &VA = ArgLocs[i];
3499         if (!VA.isRegLoc())
3500           continue;
3501         unsigned Reg = VA.getLocReg();
3502         switch (Reg) {
3503         default: break;
3504         case X86::EAX: case X86::EDX: case X86::ECX:
3505           if (++NumInRegs == MaxInRegs)
3506             return false;
3507           break;
3508         }
3509       }
3510     }
3511   }
3512
3513   return true;
3514 }
3515
3516 FastISel *
3517 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3518                                   const TargetLibraryInfo *libInfo) const {
3519   return X86::createFastISel(funcInfo, libInfo);
3520 }
3521
3522 //===----------------------------------------------------------------------===//
3523 //                           Other Lowering Hooks
3524 //===----------------------------------------------------------------------===//
3525
3526 static bool MayFoldLoad(SDValue Op) {
3527   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3528 }
3529
3530 static bool MayFoldIntoStore(SDValue Op) {
3531   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3532 }
3533
3534 static bool isTargetShuffle(unsigned Opcode) {
3535   switch(Opcode) {
3536   default: return false;
3537   case X86ISD::BLENDI:
3538   case X86ISD::PSHUFB:
3539   case X86ISD::PSHUFD:
3540   case X86ISD::PSHUFHW:
3541   case X86ISD::PSHUFLW:
3542   case X86ISD::SHUFP:
3543   case X86ISD::PALIGNR:
3544   case X86ISD::MOVLHPS:
3545   case X86ISD::MOVLHPD:
3546   case X86ISD::MOVHLPS:
3547   case X86ISD::MOVLPS:
3548   case X86ISD::MOVLPD:
3549   case X86ISD::MOVSHDUP:
3550   case X86ISD::MOVSLDUP:
3551   case X86ISD::MOVDDUP:
3552   case X86ISD::MOVSS:
3553   case X86ISD::MOVSD:
3554   case X86ISD::UNPCKL:
3555   case X86ISD::UNPCKH:
3556   case X86ISD::VPERMILPI:
3557   case X86ISD::VPERM2X128:
3558   case X86ISD::VPERMI:
3559     return true;
3560   }
3561 }
3562
3563 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3564                                     SDValue V1, unsigned TargetMask,
3565                                     SelectionDAG &DAG) {
3566   switch(Opc) {
3567   default: llvm_unreachable("Unknown x86 shuffle node");
3568   case X86ISD::PSHUFD:
3569   case X86ISD::PSHUFHW:
3570   case X86ISD::PSHUFLW:
3571   case X86ISD::VPERMILPI:
3572   case X86ISD::VPERMI:
3573     return DAG.getNode(Opc, dl, VT, V1,
3574                        DAG.getConstant(TargetMask, dl, MVT::i8));
3575   }
3576 }
3577
3578 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3579                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3580   switch(Opc) {
3581   default: llvm_unreachable("Unknown x86 shuffle node");
3582   case X86ISD::MOVLHPS:
3583   case X86ISD::MOVLHPD:
3584   case X86ISD::MOVHLPS:
3585   case X86ISD::MOVLPS:
3586   case X86ISD::MOVLPD:
3587   case X86ISD::MOVSS:
3588   case X86ISD::MOVSD:
3589   case X86ISD::UNPCKL:
3590   case X86ISD::UNPCKH:
3591     return DAG.getNode(Opc, dl, VT, V1, V2);
3592   }
3593 }
3594
3595 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3596   MachineFunction &MF = DAG.getMachineFunction();
3597   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3598   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3599   int ReturnAddrIndex = FuncInfo->getRAIndex();
3600
3601   if (ReturnAddrIndex == 0) {
3602     // Set up a frame object for the return address.
3603     unsigned SlotSize = RegInfo->getSlotSize();
3604     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3605                                                            -(int64_t)SlotSize,
3606                                                            false);
3607     FuncInfo->setRAIndex(ReturnAddrIndex);
3608   }
3609
3610   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3611 }
3612
3613 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3614                                        bool hasSymbolicDisplacement) {
3615   // Offset should fit into 32 bit immediate field.
3616   if (!isInt<32>(Offset))
3617     return false;
3618
3619   // If we don't have a symbolic displacement - we don't have any extra
3620   // restrictions.
3621   if (!hasSymbolicDisplacement)
3622     return true;
3623
3624   // FIXME: Some tweaks might be needed for medium code model.
3625   if (M != CodeModel::Small && M != CodeModel::Kernel)
3626     return false;
3627
3628   // For small code model we assume that latest object is 16MB before end of 31
3629   // bits boundary. We may also accept pretty large negative constants knowing
3630   // that all objects are in the positive half of address space.
3631   if (M == CodeModel::Small && Offset < 16*1024*1024)
3632     return true;
3633
3634   // For kernel code model we know that all object resist in the negative half
3635   // of 32bits address space. We may not accept negative offsets, since they may
3636   // be just off and we may accept pretty large positive ones.
3637   if (M == CodeModel::Kernel && Offset >= 0)
3638     return true;
3639
3640   return false;
3641 }
3642
3643 /// isCalleePop - Determines whether the callee is required to pop its
3644 /// own arguments. Callee pop is necessary to support tail calls.
3645 bool X86::isCalleePop(CallingConv::ID CallingConv,
3646                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3647   switch (CallingConv) {
3648   default:
3649     return false;
3650   case CallingConv::X86_StdCall:
3651   case CallingConv::X86_FastCall:
3652   case CallingConv::X86_ThisCall:
3653     return !is64Bit;
3654   case CallingConv::Fast:
3655   case CallingConv::GHC:
3656   case CallingConv::HiPE:
3657     if (IsVarArg)
3658       return false;
3659     return TailCallOpt;
3660   }
3661 }
3662
3663 /// \brief Return true if the condition is an unsigned comparison operation.
3664 static bool isX86CCUnsigned(unsigned X86CC) {
3665   switch (X86CC) {
3666   default: llvm_unreachable("Invalid integer condition!");
3667   case X86::COND_E:     return true;
3668   case X86::COND_G:     return false;
3669   case X86::COND_GE:    return false;
3670   case X86::COND_L:     return false;
3671   case X86::COND_LE:    return false;
3672   case X86::COND_NE:    return true;
3673   case X86::COND_B:     return true;
3674   case X86::COND_A:     return true;
3675   case X86::COND_BE:    return true;
3676   case X86::COND_AE:    return true;
3677   }
3678   llvm_unreachable("covered switch fell through?!");
3679 }
3680
3681 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3682 /// specific condition code, returning the condition code and the LHS/RHS of the
3683 /// comparison to make.
3684 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3685                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3686   if (!isFP) {
3687     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3688       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3689         // X > -1   -> X == 0, jump !sign.
3690         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3691         return X86::COND_NS;
3692       }
3693       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3694         // X < 0   -> X == 0, jump on sign.
3695         return X86::COND_S;
3696       }
3697       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3698         // X < 1   -> X <= 0
3699         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3700         return X86::COND_LE;
3701       }
3702     }
3703
3704     switch (SetCCOpcode) {
3705     default: llvm_unreachable("Invalid integer condition!");
3706     case ISD::SETEQ:  return X86::COND_E;
3707     case ISD::SETGT:  return X86::COND_G;
3708     case ISD::SETGE:  return X86::COND_GE;
3709     case ISD::SETLT:  return X86::COND_L;
3710     case ISD::SETLE:  return X86::COND_LE;
3711     case ISD::SETNE:  return X86::COND_NE;
3712     case ISD::SETULT: return X86::COND_B;
3713     case ISD::SETUGT: return X86::COND_A;
3714     case ISD::SETULE: return X86::COND_BE;
3715     case ISD::SETUGE: return X86::COND_AE;
3716     }
3717   }
3718
3719   // First determine if it is required or is profitable to flip the operands.
3720
3721   // If LHS is a foldable load, but RHS is not, flip the condition.
3722   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3723       !ISD::isNON_EXTLoad(RHS.getNode())) {
3724     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3725     std::swap(LHS, RHS);
3726   }
3727
3728   switch (SetCCOpcode) {
3729   default: break;
3730   case ISD::SETOLT:
3731   case ISD::SETOLE:
3732   case ISD::SETUGT:
3733   case ISD::SETUGE:
3734     std::swap(LHS, RHS);
3735     break;
3736   }
3737
3738   // On a floating point condition, the flags are set as follows:
3739   // ZF  PF  CF   op
3740   //  0 | 0 | 0 | X > Y
3741   //  0 | 0 | 1 | X < Y
3742   //  1 | 0 | 0 | X == Y
3743   //  1 | 1 | 1 | unordered
3744   switch (SetCCOpcode) {
3745   default: llvm_unreachable("Condcode should be pre-legalized away");
3746   case ISD::SETUEQ:
3747   case ISD::SETEQ:   return X86::COND_E;
3748   case ISD::SETOLT:              // flipped
3749   case ISD::SETOGT:
3750   case ISD::SETGT:   return X86::COND_A;
3751   case ISD::SETOLE:              // flipped
3752   case ISD::SETOGE:
3753   case ISD::SETGE:   return X86::COND_AE;
3754   case ISD::SETUGT:              // flipped
3755   case ISD::SETULT:
3756   case ISD::SETLT:   return X86::COND_B;
3757   case ISD::SETUGE:              // flipped
3758   case ISD::SETULE:
3759   case ISD::SETLE:   return X86::COND_BE;
3760   case ISD::SETONE:
3761   case ISD::SETNE:   return X86::COND_NE;
3762   case ISD::SETUO:   return X86::COND_P;
3763   case ISD::SETO:    return X86::COND_NP;
3764   case ISD::SETOEQ:
3765   case ISD::SETUNE:  return X86::COND_INVALID;
3766   }
3767 }
3768
3769 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3770 /// code. Current x86 isa includes the following FP cmov instructions:
3771 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3772 static bool hasFPCMov(unsigned X86CC) {
3773   switch (X86CC) {
3774   default:
3775     return false;
3776   case X86::COND_B:
3777   case X86::COND_BE:
3778   case X86::COND_E:
3779   case X86::COND_P:
3780   case X86::COND_A:
3781   case X86::COND_AE:
3782   case X86::COND_NE:
3783   case X86::COND_NP:
3784     return true;
3785   }
3786 }
3787
3788 /// isFPImmLegal - Returns true if the target can instruction select the
3789 /// specified FP immediate natively. If false, the legalizer will
3790 /// materialize the FP immediate as a load from a constant pool.
3791 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3792   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3793     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3794       return true;
3795   }
3796   return false;
3797 }
3798
3799 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3800                                               ISD::LoadExtType ExtTy,
3801                                               EVT NewVT) const {
3802   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3803   // relocation target a movq or addq instruction: don't let the load shrink.
3804   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3805   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3806     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3807       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3808   return true;
3809 }
3810
3811 /// \brief Returns true if it is beneficial to convert a load of a constant
3812 /// to just the constant itself.
3813 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3814                                                           Type *Ty) const {
3815   assert(Ty->isIntegerTy());
3816
3817   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3818   if (BitSize == 0 || BitSize > 64)
3819     return false;
3820   return true;
3821 }
3822
3823 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3824                                                 unsigned Index) const {
3825   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3826     return false;
3827
3828   return (Index == 0 || Index == ResVT.getVectorNumElements());
3829 }
3830
3831 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3832   // Speculate cttz only if we can directly use TZCNT.
3833   return Subtarget->hasBMI();
3834 }
3835
3836 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3837   // Speculate ctlz only if we can directly use LZCNT.
3838   return Subtarget->hasLZCNT();
3839 }
3840
3841 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3842 /// the specified range (L, H].
3843 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3844   return (Val < 0) || (Val >= Low && Val < Hi);
3845 }
3846
3847 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3848 /// specified value.
3849 static bool isUndefOrEqual(int Val, int CmpVal) {
3850   return (Val < 0 || Val == CmpVal);
3851 }
3852
3853 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3854 /// from position Pos and ending in Pos+Size, falls within the specified
3855 /// sequential range (Low, Low+Size]. or is undef.
3856 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3857                                        unsigned Pos, unsigned Size, int Low) {
3858   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3859     if (!isUndefOrEqual(Mask[i], Low))
3860       return false;
3861   return true;
3862 }
3863
3864 /// isVEXTRACTIndex - Return true if the specified
3865 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3866 /// suitable for instruction that extract 128 or 256 bit vectors
3867 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3868   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3869   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3870     return false;
3871
3872   // The index should be aligned on a vecWidth-bit boundary.
3873   uint64_t Index =
3874     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3875
3876   MVT VT = N->getSimpleValueType(0);
3877   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3878   bool Result = (Index * ElSize) % vecWidth == 0;
3879
3880   return Result;
3881 }
3882
3883 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3884 /// operand specifies a subvector insert that is suitable for input to
3885 /// insertion of 128 or 256-bit subvectors
3886 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3887   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3888   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3889     return false;
3890   // The index should be aligned on a vecWidth-bit boundary.
3891   uint64_t Index =
3892     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3893
3894   MVT VT = N->getSimpleValueType(0);
3895   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3896   bool Result = (Index * ElSize) % vecWidth == 0;
3897
3898   return Result;
3899 }
3900
3901 bool X86::isVINSERT128Index(SDNode *N) {
3902   return isVINSERTIndex(N, 128);
3903 }
3904
3905 bool X86::isVINSERT256Index(SDNode *N) {
3906   return isVINSERTIndex(N, 256);
3907 }
3908
3909 bool X86::isVEXTRACT128Index(SDNode *N) {
3910   return isVEXTRACTIndex(N, 128);
3911 }
3912
3913 bool X86::isVEXTRACT256Index(SDNode *N) {
3914   return isVEXTRACTIndex(N, 256);
3915 }
3916
3917 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3918   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3919   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3920     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3921
3922   uint64_t Index =
3923     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3924
3925   MVT VecVT = N->getOperand(0).getSimpleValueType();
3926   MVT ElVT = VecVT.getVectorElementType();
3927
3928   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3929   return Index / NumElemsPerChunk;
3930 }
3931
3932 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3933   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3934   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3935     llvm_unreachable("Illegal insert subvector for VINSERT");
3936
3937   uint64_t Index =
3938     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3939
3940   MVT VecVT = N->getSimpleValueType(0);
3941   MVT ElVT = VecVT.getVectorElementType();
3942
3943   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3944   return Index / NumElemsPerChunk;
3945 }
3946
3947 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3948 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3949 /// and VINSERTI128 instructions.
3950 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3951   return getExtractVEXTRACTImmediate(N, 128);
3952 }
3953
3954 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3955 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3956 /// and VINSERTI64x4 instructions.
3957 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3958   return getExtractVEXTRACTImmediate(N, 256);
3959 }
3960
3961 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3962 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3963 /// and VINSERTI128 instructions.
3964 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3965   return getInsertVINSERTImmediate(N, 128);
3966 }
3967
3968 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3969 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3970 /// and VINSERTI64x4 instructions.
3971 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3972   return getInsertVINSERTImmediate(N, 256);
3973 }
3974
3975 /// isZero - Returns true if Elt is a constant integer zero
3976 static bool isZero(SDValue V) {
3977   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3978   return C && C->isNullValue();
3979 }
3980
3981 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3982 /// constant +0.0.
3983 bool X86::isZeroNode(SDValue Elt) {
3984   if (isZero(Elt))
3985     return true;
3986   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3987     return CFP->getValueAPF().isPosZero();
3988   return false;
3989 }
3990
3991 /// getZeroVector - Returns a vector of specified type with all zero elements.
3992 ///
3993 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
3994                              SelectionDAG &DAG, SDLoc dl) {
3995   assert(VT.isVector() && "Expected a vector type");
3996
3997   // Always build SSE zero vectors as <4 x i32> bitcasted
3998   // to their dest type. This ensures they get CSE'd.
3999   SDValue Vec;
4000   if (VT.is128BitVector()) {  // SSE
4001     if (Subtarget->hasSSE2()) {  // SSE2
4002       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4003       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4004     } else { // SSE1
4005       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4006       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4007     }
4008   } else if (VT.is256BitVector()) { // AVX
4009     if (Subtarget->hasInt256()) { // AVX2
4010       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4011       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4012       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4013     } else {
4014       // 256-bit logic and arithmetic instructions in AVX are all
4015       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4016       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4017       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4018       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4019     }
4020   } else if (VT.is512BitVector()) { // AVX-512
4021       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4022       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4023                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4024       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4025   } else if (VT.getScalarType() == MVT::i1) {
4026
4027     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4028             && "Unexpected vector type");
4029     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4030             && "Unexpected vector type");
4031     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4032     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4033     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4034   } else
4035     llvm_unreachable("Unexpected vector type");
4036
4037   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4038 }
4039
4040 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4041                                 SelectionDAG &DAG, SDLoc dl,
4042                                 unsigned vectorWidth) {
4043   assert((vectorWidth == 128 || vectorWidth == 256) &&
4044          "Unsupported vector width");
4045   EVT VT = Vec.getValueType();
4046   EVT ElVT = VT.getVectorElementType();
4047   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4048   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4049                                   VT.getVectorNumElements()/Factor);
4050
4051   // Extract from UNDEF is UNDEF.
4052   if (Vec.getOpcode() == ISD::UNDEF)
4053     return DAG.getUNDEF(ResultVT);
4054
4055   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4056   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4057
4058   // This is the index of the first element of the vectorWidth-bit chunk
4059   // we want.
4060   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4061                                * ElemsPerChunk);
4062
4063   // If the input is a buildvector just emit a smaller one.
4064   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4065     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4066                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4067                                     ElemsPerChunk));
4068
4069   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4070   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4071 }
4072
4073 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4074 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4075 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4076 /// instructions or a simple subregister reference. Idx is an index in the
4077 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4078 /// lowering EXTRACT_VECTOR_ELT operations easier.
4079 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4080                                    SelectionDAG &DAG, SDLoc dl) {
4081   assert((Vec.getValueType().is256BitVector() ||
4082           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4083   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4084 }
4085
4086 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4087 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4088                                    SelectionDAG &DAG, SDLoc dl) {
4089   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4090   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4091 }
4092
4093 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4094                                unsigned IdxVal, SelectionDAG &DAG,
4095                                SDLoc dl, unsigned vectorWidth) {
4096   assert((vectorWidth == 128 || vectorWidth == 256) &&
4097          "Unsupported vector width");
4098   // Inserting UNDEF is Result
4099   if (Vec.getOpcode() == ISD::UNDEF)
4100     return Result;
4101   EVT VT = Vec.getValueType();
4102   EVT ElVT = VT.getVectorElementType();
4103   EVT ResultVT = Result.getValueType();
4104
4105   // Insert the relevant vectorWidth bits.
4106   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4107
4108   // This is the index of the first element of the vectorWidth-bit chunk
4109   // we want.
4110   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4111                                * ElemsPerChunk);
4112
4113   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4114   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4115 }
4116
4117 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4118 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4119 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4120 /// simple superregister reference.  Idx is an index in the 128 bits
4121 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4122 /// lowering INSERT_VECTOR_ELT operations easier.
4123 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4124                                   SelectionDAG &DAG, SDLoc dl) {
4125   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4126
4127   // For insertion into the zero index (low half) of a 256-bit vector, it is
4128   // more efficient to generate a blend with immediate instead of an insert*128.
4129   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4130   // extend the subvector to the size of the result vector. Make sure that
4131   // we are not recursing on that node by checking for undef here.
4132   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4133       Result.getOpcode() != ISD::UNDEF) {
4134     EVT ResultVT = Result.getValueType();
4135     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4136     SDValue Undef = DAG.getUNDEF(ResultVT);
4137     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4138                                  Vec, ZeroIndex);
4139
4140     // The blend instruction, and therefore its mask, depend on the data type.
4141     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4142     if (ScalarType.isFloatingPoint()) {
4143       // Choose either vblendps (float) or vblendpd (double).
4144       unsigned ScalarSize = ScalarType.getSizeInBits();
4145       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4146       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4147       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4148       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4149     }
4150
4151     const X86Subtarget &Subtarget =
4152     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4153
4154     // AVX2 is needed for 256-bit integer blend support.
4155     // Integers must be cast to 32-bit because there is only vpblendd;
4156     // vpblendw can't be used for this because it has a handicapped mask.
4157
4158     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4159     // is still more efficient than using the wrong domain vinsertf128 that
4160     // will be created by InsertSubVector().
4161     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4162
4163     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4164     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4165     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4166     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4167   }
4168
4169   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4170 }
4171
4172 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4173                                   SelectionDAG &DAG, SDLoc dl) {
4174   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4175   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4176 }
4177
4178 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4179 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4180 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4181 /// large BUILD_VECTORS.
4182 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4183                                    unsigned NumElems, SelectionDAG &DAG,
4184                                    SDLoc dl) {
4185   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4186   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4187 }
4188
4189 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4190                                    unsigned NumElems, SelectionDAG &DAG,
4191                                    SDLoc dl) {
4192   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4193   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4194 }
4195
4196 /// getOnesVector - Returns a vector of specified type with all bits set.
4197 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4198 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4199 /// Then bitcast to their original type, ensuring they get CSE'd.
4200 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4201                              SDLoc dl) {
4202   assert(VT.isVector() && "Expected a vector type");
4203
4204   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4205   SDValue Vec;
4206   if (VT.is256BitVector()) {
4207     if (HasInt256) { // AVX2
4208       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4209       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4210     } else { // AVX
4211       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4212       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4213     }
4214   } else if (VT.is128BitVector()) {
4215     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4216   } else
4217     llvm_unreachable("Unexpected vector type");
4218
4219   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4220 }
4221
4222 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4223 /// operation of specified width.
4224 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4225                        SDValue V2) {
4226   unsigned NumElems = VT.getVectorNumElements();
4227   SmallVector<int, 8> Mask;
4228   Mask.push_back(NumElems);
4229   for (unsigned i = 1; i != NumElems; ++i)
4230     Mask.push_back(i);
4231   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4232 }
4233
4234 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4235 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4236                           SDValue V2) {
4237   unsigned NumElems = VT.getVectorNumElements();
4238   SmallVector<int, 8> Mask;
4239   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4240     Mask.push_back(i);
4241     Mask.push_back(i + NumElems);
4242   }
4243   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4244 }
4245
4246 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4247 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4248                           SDValue V2) {
4249   unsigned NumElems = VT.getVectorNumElements();
4250   SmallVector<int, 8> Mask;
4251   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4252     Mask.push_back(i + Half);
4253     Mask.push_back(i + NumElems + Half);
4254   }
4255   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4256 }
4257
4258 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4259 /// vector of zero or undef vector.  This produces a shuffle where the low
4260 /// element of V2 is swizzled into the zero/undef vector, landing at element
4261 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4262 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4263                                            bool IsZero,
4264                                            const X86Subtarget *Subtarget,
4265                                            SelectionDAG &DAG) {
4266   MVT VT = V2.getSimpleValueType();
4267   SDValue V1 = IsZero
4268     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4269   unsigned NumElems = VT.getVectorNumElements();
4270   SmallVector<int, 16> MaskVec;
4271   for (unsigned i = 0; i != NumElems; ++i)
4272     // If this is the insertion idx, put the low elt of V2 here.
4273     MaskVec.push_back(i == Idx ? NumElems : i);
4274   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4275 }
4276
4277 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4278 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4279 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4280 /// shuffles which use a single input multiple times, and in those cases it will
4281 /// adjust the mask to only have indices within that single input.
4282 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4283                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4284   unsigned NumElems = VT.getVectorNumElements();
4285   SDValue ImmN;
4286
4287   IsUnary = false;
4288   bool IsFakeUnary = false;
4289   switch(N->getOpcode()) {
4290   case X86ISD::BLENDI:
4291     ImmN = N->getOperand(N->getNumOperands()-1);
4292     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4293     break;
4294   case X86ISD::SHUFP:
4295     ImmN = N->getOperand(N->getNumOperands()-1);
4296     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4297     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4298     break;
4299   case X86ISD::UNPCKH:
4300     DecodeUNPCKHMask(VT, Mask);
4301     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4302     break;
4303   case X86ISD::UNPCKL:
4304     DecodeUNPCKLMask(VT, Mask);
4305     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4306     break;
4307   case X86ISD::MOVHLPS:
4308     DecodeMOVHLPSMask(NumElems, Mask);
4309     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4310     break;
4311   case X86ISD::MOVLHPS:
4312     DecodeMOVLHPSMask(NumElems, Mask);
4313     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4314     break;
4315   case X86ISD::PALIGNR:
4316     ImmN = N->getOperand(N->getNumOperands()-1);
4317     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4318     break;
4319   case X86ISD::PSHUFD:
4320   case X86ISD::VPERMILPI:
4321     ImmN = N->getOperand(N->getNumOperands()-1);
4322     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4323     IsUnary = true;
4324     break;
4325   case X86ISD::PSHUFHW:
4326     ImmN = N->getOperand(N->getNumOperands()-1);
4327     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4328     IsUnary = true;
4329     break;
4330   case X86ISD::PSHUFLW:
4331     ImmN = N->getOperand(N->getNumOperands()-1);
4332     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4333     IsUnary = true;
4334     break;
4335   case X86ISD::PSHUFB: {
4336     IsUnary = true;
4337     SDValue MaskNode = N->getOperand(1);
4338     while (MaskNode->getOpcode() == ISD::BITCAST)
4339       MaskNode = MaskNode->getOperand(0);
4340
4341     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4342       // If we have a build-vector, then things are easy.
4343       EVT VT = MaskNode.getValueType();
4344       assert(VT.isVector() &&
4345              "Can't produce a non-vector with a build_vector!");
4346       if (!VT.isInteger())
4347         return false;
4348
4349       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4350
4351       SmallVector<uint64_t, 32> RawMask;
4352       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4353         SDValue Op = MaskNode->getOperand(i);
4354         if (Op->getOpcode() == ISD::UNDEF) {
4355           RawMask.push_back((uint64_t)SM_SentinelUndef);
4356           continue;
4357         }
4358         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4359         if (!CN)
4360           return false;
4361         APInt MaskElement = CN->getAPIntValue();
4362
4363         // We now have to decode the element which could be any integer size and
4364         // extract each byte of it.
4365         for (int j = 0; j < NumBytesPerElement; ++j) {
4366           // Note that this is x86 and so always little endian: the low byte is
4367           // the first byte of the mask.
4368           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4369           MaskElement = MaskElement.lshr(8);
4370         }
4371       }
4372       DecodePSHUFBMask(RawMask, Mask);
4373       break;
4374     }
4375
4376     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4377     if (!MaskLoad)
4378       return false;
4379
4380     SDValue Ptr = MaskLoad->getBasePtr();
4381     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4382         Ptr->getOpcode() == X86ISD::WrapperRIP)
4383       Ptr = Ptr->getOperand(0);
4384
4385     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4386     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4387       return false;
4388
4389     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4390       DecodePSHUFBMask(C, Mask);
4391       if (Mask.empty())
4392         return false;
4393       break;
4394     }
4395
4396     return false;
4397   }
4398   case X86ISD::VPERMI:
4399     ImmN = N->getOperand(N->getNumOperands()-1);
4400     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4401     IsUnary = true;
4402     break;
4403   case X86ISD::MOVSS:
4404   case X86ISD::MOVSD:
4405     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4406     break;
4407   case X86ISD::VPERM2X128:
4408     ImmN = N->getOperand(N->getNumOperands()-1);
4409     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4410     if (Mask.empty()) return false;
4411     break;
4412   case X86ISD::MOVSLDUP:
4413     DecodeMOVSLDUPMask(VT, Mask);
4414     IsUnary = true;
4415     break;
4416   case X86ISD::MOVSHDUP:
4417     DecodeMOVSHDUPMask(VT, Mask);
4418     IsUnary = true;
4419     break;
4420   case X86ISD::MOVDDUP:
4421     DecodeMOVDDUPMask(VT, Mask);
4422     IsUnary = true;
4423     break;
4424   case X86ISD::MOVLHPD:
4425   case X86ISD::MOVLPD:
4426   case X86ISD::MOVLPS:
4427     // Not yet implemented
4428     return false;
4429   default: llvm_unreachable("unknown target shuffle node");
4430   }
4431
4432   // If we have a fake unary shuffle, the shuffle mask is spread across two
4433   // inputs that are actually the same node. Re-map the mask to always point
4434   // into the first input.
4435   if (IsFakeUnary)
4436     for (int &M : Mask)
4437       if (M >= (int)Mask.size())
4438         M -= Mask.size();
4439
4440   return true;
4441 }
4442
4443 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4444 /// element of the result of the vector shuffle.
4445 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4446                                    unsigned Depth) {
4447   if (Depth == 6)
4448     return SDValue();  // Limit search depth.
4449
4450   SDValue V = SDValue(N, 0);
4451   EVT VT = V.getValueType();
4452   unsigned Opcode = V.getOpcode();
4453
4454   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4455   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4456     int Elt = SV->getMaskElt(Index);
4457
4458     if (Elt < 0)
4459       return DAG.getUNDEF(VT.getVectorElementType());
4460
4461     unsigned NumElems = VT.getVectorNumElements();
4462     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4463                                          : SV->getOperand(1);
4464     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4465   }
4466
4467   // Recurse into target specific vector shuffles to find scalars.
4468   if (isTargetShuffle(Opcode)) {
4469     MVT ShufVT = V.getSimpleValueType();
4470     unsigned NumElems = ShufVT.getVectorNumElements();
4471     SmallVector<int, 16> ShuffleMask;
4472     bool IsUnary;
4473
4474     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4475       return SDValue();
4476
4477     int Elt = ShuffleMask[Index];
4478     if (Elt < 0)
4479       return DAG.getUNDEF(ShufVT.getVectorElementType());
4480
4481     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4482                                          : N->getOperand(1);
4483     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4484                                Depth+1);
4485   }
4486
4487   // Actual nodes that may contain scalar elements
4488   if (Opcode == ISD::BITCAST) {
4489     V = V.getOperand(0);
4490     EVT SrcVT = V.getValueType();
4491     unsigned NumElems = VT.getVectorNumElements();
4492
4493     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4494       return SDValue();
4495   }
4496
4497   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4498     return (Index == 0) ? V.getOperand(0)
4499                         : DAG.getUNDEF(VT.getVectorElementType());
4500
4501   if (V.getOpcode() == ISD::BUILD_VECTOR)
4502     return V.getOperand(Index);
4503
4504   return SDValue();
4505 }
4506
4507 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4508 ///
4509 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4510                                        unsigned NumNonZero, unsigned NumZero,
4511                                        SelectionDAG &DAG,
4512                                        const X86Subtarget* Subtarget,
4513                                        const TargetLowering &TLI) {
4514   if (NumNonZero > 8)
4515     return SDValue();
4516
4517   SDLoc dl(Op);
4518   SDValue V;
4519   bool First = true;
4520
4521   // SSE4.1 - use PINSRB to insert each byte directly.
4522   if (Subtarget->hasSSE41()) {
4523     for (unsigned i = 0; i < 16; ++i) {
4524       bool isNonZero = (NonZeros & (1 << i)) != 0;
4525       if (isNonZero) {
4526         if (First) {
4527           if (NumZero)
4528             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4529           else
4530             V = DAG.getUNDEF(MVT::v16i8);
4531           First = false;
4532         }
4533         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4534                         MVT::v16i8, V, Op.getOperand(i),
4535                         DAG.getIntPtrConstant(i, dl));
4536       }
4537     }
4538
4539     return V;
4540   }
4541
4542   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4543   for (unsigned i = 0; i < 16; ++i) {
4544     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4545     if (ThisIsNonZero && First) {
4546       if (NumZero)
4547         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4548       else
4549         V = DAG.getUNDEF(MVT::v8i16);
4550       First = false;
4551     }
4552
4553     if ((i & 1) != 0) {
4554       SDValue ThisElt, LastElt;
4555       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4556       if (LastIsNonZero) {
4557         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4558                               MVT::i16, Op.getOperand(i-1));
4559       }
4560       if (ThisIsNonZero) {
4561         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4562         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4563                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4564         if (LastIsNonZero)
4565           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4566       } else
4567         ThisElt = LastElt;
4568
4569       if (ThisElt.getNode())
4570         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4571                         DAG.getIntPtrConstant(i/2, dl));
4572     }
4573   }
4574
4575   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4576 }
4577
4578 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4579 ///
4580 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4581                                      unsigned NumNonZero, unsigned NumZero,
4582                                      SelectionDAG &DAG,
4583                                      const X86Subtarget* Subtarget,
4584                                      const TargetLowering &TLI) {
4585   if (NumNonZero > 4)
4586     return SDValue();
4587
4588   SDLoc dl(Op);
4589   SDValue V;
4590   bool First = true;
4591   for (unsigned i = 0; i < 8; ++i) {
4592     bool isNonZero = (NonZeros & (1 << i)) != 0;
4593     if (isNonZero) {
4594       if (First) {
4595         if (NumZero)
4596           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4597         else
4598           V = DAG.getUNDEF(MVT::v8i16);
4599         First = false;
4600       }
4601       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4602                       MVT::v8i16, V, Op.getOperand(i),
4603                       DAG.getIntPtrConstant(i, dl));
4604     }
4605   }
4606
4607   return V;
4608 }
4609
4610 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4611 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4612                                      const X86Subtarget *Subtarget,
4613                                      const TargetLowering &TLI) {
4614   // Find all zeroable elements.
4615   std::bitset<4> Zeroable;
4616   for (int i=0; i < 4; ++i) {
4617     SDValue Elt = Op->getOperand(i);
4618     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4619   }
4620   assert(Zeroable.size() - Zeroable.count() > 1 &&
4621          "We expect at least two non-zero elements!");
4622
4623   // We only know how to deal with build_vector nodes where elements are either
4624   // zeroable or extract_vector_elt with constant index.
4625   SDValue FirstNonZero;
4626   unsigned FirstNonZeroIdx;
4627   for (unsigned i=0; i < 4; ++i) {
4628     if (Zeroable[i])
4629       continue;
4630     SDValue Elt = Op->getOperand(i);
4631     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4632         !isa<ConstantSDNode>(Elt.getOperand(1)))
4633       return SDValue();
4634     // Make sure that this node is extracting from a 128-bit vector.
4635     MVT VT = Elt.getOperand(0).getSimpleValueType();
4636     if (!VT.is128BitVector())
4637       return SDValue();
4638     if (!FirstNonZero.getNode()) {
4639       FirstNonZero = Elt;
4640       FirstNonZeroIdx = i;
4641     }
4642   }
4643
4644   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4645   SDValue V1 = FirstNonZero.getOperand(0);
4646   MVT VT = V1.getSimpleValueType();
4647
4648   // See if this build_vector can be lowered as a blend with zero.
4649   SDValue Elt;
4650   unsigned EltMaskIdx, EltIdx;
4651   int Mask[4];
4652   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4653     if (Zeroable[EltIdx]) {
4654       // The zero vector will be on the right hand side.
4655       Mask[EltIdx] = EltIdx+4;
4656       continue;
4657     }
4658
4659     Elt = Op->getOperand(EltIdx);
4660     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4661     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4662     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4663       break;
4664     Mask[EltIdx] = EltIdx;
4665   }
4666
4667   if (EltIdx == 4) {
4668     // Let the shuffle legalizer deal with blend operations.
4669     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4670     if (V1.getSimpleValueType() != VT)
4671       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4672     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4673   }
4674
4675   // See if we can lower this build_vector to a INSERTPS.
4676   if (!Subtarget->hasSSE41())
4677     return SDValue();
4678
4679   SDValue V2 = Elt.getOperand(0);
4680   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4681     V1 = SDValue();
4682
4683   bool CanFold = true;
4684   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4685     if (Zeroable[i])
4686       continue;
4687
4688     SDValue Current = Op->getOperand(i);
4689     SDValue SrcVector = Current->getOperand(0);
4690     if (!V1.getNode())
4691       V1 = SrcVector;
4692     CanFold = SrcVector == V1 &&
4693       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4694   }
4695
4696   if (!CanFold)
4697     return SDValue();
4698
4699   assert(V1.getNode() && "Expected at least two non-zero elements!");
4700   if (V1.getSimpleValueType() != MVT::v4f32)
4701     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4702   if (V2.getSimpleValueType() != MVT::v4f32)
4703     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4704
4705   // Ok, we can emit an INSERTPS instruction.
4706   unsigned ZMask = Zeroable.to_ulong();
4707
4708   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4709   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4710   SDLoc DL(Op);
4711   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4712                                DAG.getIntPtrConstant(InsertPSMask, DL));
4713   return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4714 }
4715
4716 /// Return a vector logical shift node.
4717 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4718                          unsigned NumBits, SelectionDAG &DAG,
4719                          const TargetLowering &TLI, SDLoc dl) {
4720   assert(VT.is128BitVector() && "Unknown type for VShift");
4721   MVT ShVT = MVT::v2i64;
4722   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4723   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4724   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4725   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4726   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4727   return DAG.getNode(ISD::BITCAST, dl, VT,
4728                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4729 }
4730
4731 static SDValue
4732 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4733
4734   // Check if the scalar load can be widened into a vector load. And if
4735   // the address is "base + cst" see if the cst can be "absorbed" into
4736   // the shuffle mask.
4737   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4738     SDValue Ptr = LD->getBasePtr();
4739     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4740       return SDValue();
4741     EVT PVT = LD->getValueType(0);
4742     if (PVT != MVT::i32 && PVT != MVT::f32)
4743       return SDValue();
4744
4745     int FI = -1;
4746     int64_t Offset = 0;
4747     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4748       FI = FINode->getIndex();
4749       Offset = 0;
4750     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4751                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4752       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4753       Offset = Ptr.getConstantOperandVal(1);
4754       Ptr = Ptr.getOperand(0);
4755     } else {
4756       return SDValue();
4757     }
4758
4759     // FIXME: 256-bit vector instructions don't require a strict alignment,
4760     // improve this code to support it better.
4761     unsigned RequiredAlign = VT.getSizeInBits()/8;
4762     SDValue Chain = LD->getChain();
4763     // Make sure the stack object alignment is at least 16 or 32.
4764     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4765     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4766       if (MFI->isFixedObjectIndex(FI)) {
4767         // Can't change the alignment. FIXME: It's possible to compute
4768         // the exact stack offset and reference FI + adjust offset instead.
4769         // If someone *really* cares about this. That's the way to implement it.
4770         return SDValue();
4771       } else {
4772         MFI->setObjectAlignment(FI, RequiredAlign);
4773       }
4774     }
4775
4776     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4777     // Ptr + (Offset & ~15).
4778     if (Offset < 0)
4779       return SDValue();
4780     if ((Offset % RequiredAlign) & 3)
4781       return SDValue();
4782     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4783     if (StartOffset) {
4784       SDLoc DL(Ptr);
4785       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4786                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4787     }
4788
4789     int EltNo = (Offset - StartOffset) >> 2;
4790     unsigned NumElems = VT.getVectorNumElements();
4791
4792     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4793     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4794                              LD->getPointerInfo().getWithOffset(StartOffset),
4795                              false, false, false, 0);
4796
4797     SmallVector<int, 8> Mask(NumElems, EltNo);
4798
4799     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4800   }
4801
4802   return SDValue();
4803 }
4804
4805 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4806 /// elements can be replaced by a single large load which has the same value as
4807 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4808 ///
4809 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4810 ///
4811 /// FIXME: we'd also like to handle the case where the last elements are zero
4812 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4813 /// There's even a handy isZeroNode for that purpose.
4814 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4815                                         SDLoc &DL, SelectionDAG &DAG,
4816                                         bool isAfterLegalize) {
4817   unsigned NumElems = Elts.size();
4818
4819   LoadSDNode *LDBase = nullptr;
4820   unsigned LastLoadedElt = -1U;
4821
4822   // For each element in the initializer, see if we've found a load or an undef.
4823   // If we don't find an initial load element, or later load elements are
4824   // non-consecutive, bail out.
4825   for (unsigned i = 0; i < NumElems; ++i) {
4826     SDValue Elt = Elts[i];
4827     // Look through a bitcast.
4828     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4829       Elt = Elt.getOperand(0);
4830     if (!Elt.getNode() ||
4831         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4832       return SDValue();
4833     if (!LDBase) {
4834       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4835         return SDValue();
4836       LDBase = cast<LoadSDNode>(Elt.getNode());
4837       LastLoadedElt = i;
4838       continue;
4839     }
4840     if (Elt.getOpcode() == ISD::UNDEF)
4841       continue;
4842
4843     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4844     EVT LdVT = Elt.getValueType();
4845     // Each loaded element must be the correct fractional portion of the
4846     // requested vector load.
4847     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4848       return SDValue();
4849     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4850       return SDValue();
4851     LastLoadedElt = i;
4852   }
4853
4854   // If we have found an entire vector of loads and undefs, then return a large
4855   // load of the entire vector width starting at the base pointer.  If we found
4856   // consecutive loads for the low half, generate a vzext_load node.
4857   if (LastLoadedElt == NumElems - 1) {
4858     assert(LDBase && "Did not find base load for merging consecutive loads");
4859     EVT EltVT = LDBase->getValueType(0);
4860     // Ensure that the input vector size for the merged loads matches the
4861     // cumulative size of the input elements.
4862     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4863       return SDValue();
4864
4865     if (isAfterLegalize &&
4866         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4867       return SDValue();
4868
4869     SDValue NewLd = SDValue();
4870
4871     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4872                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4873                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4874                         LDBase->getAlignment());
4875
4876     if (LDBase->hasAnyUseOfValue(1)) {
4877       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4878                                      SDValue(LDBase, 1),
4879                                      SDValue(NewLd.getNode(), 1));
4880       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4881       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4882                              SDValue(NewLd.getNode(), 1));
4883     }
4884
4885     return NewLd;
4886   }
4887
4888   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4889   //of a v4i32 / v4f32. It's probably worth generalizing.
4890   EVT EltVT = VT.getVectorElementType();
4891   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4892       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4893     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4894     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4895     SDValue ResNode =
4896         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4897                                 LDBase->getPointerInfo(),
4898                                 LDBase->getAlignment(),
4899                                 false/*isVolatile*/, true/*ReadMem*/,
4900                                 false/*WriteMem*/);
4901
4902     // Make sure the newly-created LOAD is in the same position as LDBase in
4903     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4904     // update uses of LDBase's output chain to use the TokenFactor.
4905     if (LDBase->hasAnyUseOfValue(1)) {
4906       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4907                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4908       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4909       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4910                              SDValue(ResNode.getNode(), 1));
4911     }
4912
4913     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4914   }
4915   return SDValue();
4916 }
4917
4918 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4919 /// to generate a splat value for the following cases:
4920 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4921 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4922 /// a scalar load, or a constant.
4923 /// The VBROADCAST node is returned when a pattern is found,
4924 /// or SDValue() otherwise.
4925 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4926                                     SelectionDAG &DAG) {
4927   // VBROADCAST requires AVX.
4928   // TODO: Splats could be generated for non-AVX CPUs using SSE
4929   // instructions, but there's less potential gain for only 128-bit vectors.
4930   if (!Subtarget->hasAVX())
4931     return SDValue();
4932
4933   MVT VT = Op.getSimpleValueType();
4934   SDLoc dl(Op);
4935
4936   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4937          "Unsupported vector type for broadcast.");
4938
4939   SDValue Ld;
4940   bool ConstSplatVal;
4941
4942   switch (Op.getOpcode()) {
4943     default:
4944       // Unknown pattern found.
4945       return SDValue();
4946
4947     case ISD::BUILD_VECTOR: {
4948       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4949       BitVector UndefElements;
4950       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4951
4952       // We need a splat of a single value to use broadcast, and it doesn't
4953       // make any sense if the value is only in one element of the vector.
4954       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4955         return SDValue();
4956
4957       Ld = Splat;
4958       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4959                        Ld.getOpcode() == ISD::ConstantFP);
4960
4961       // Make sure that all of the users of a non-constant load are from the
4962       // BUILD_VECTOR node.
4963       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4964         return SDValue();
4965       break;
4966     }
4967
4968     case ISD::VECTOR_SHUFFLE: {
4969       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4970
4971       // Shuffles must have a splat mask where the first element is
4972       // broadcasted.
4973       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4974         return SDValue();
4975
4976       SDValue Sc = Op.getOperand(0);
4977       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4978           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4979
4980         if (!Subtarget->hasInt256())
4981           return SDValue();
4982
4983         // Use the register form of the broadcast instruction available on AVX2.
4984         if (VT.getSizeInBits() >= 256)
4985           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4986         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4987       }
4988
4989       Ld = Sc.getOperand(0);
4990       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4991                        Ld.getOpcode() == ISD::ConstantFP);
4992
4993       // The scalar_to_vector node and the suspected
4994       // load node must have exactly one user.
4995       // Constants may have multiple users.
4996
4997       // AVX-512 has register version of the broadcast
4998       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4999         Ld.getValueType().getSizeInBits() >= 32;
5000       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5001           !hasRegVer))
5002         return SDValue();
5003       break;
5004     }
5005   }
5006
5007   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5008   bool IsGE256 = (VT.getSizeInBits() >= 256);
5009
5010   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5011   // instruction to save 8 or more bytes of constant pool data.
5012   // TODO: If multiple splats are generated to load the same constant,
5013   // it may be detrimental to overall size. There needs to be a way to detect
5014   // that condition to know if this is truly a size win.
5015   const Function *F = DAG.getMachineFunction().getFunction();
5016   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5017
5018   // Handle broadcasting a single constant scalar from the constant pool
5019   // into a vector.
5020   // On Sandybridge (no AVX2), it is still better to load a constant vector
5021   // from the constant pool and not to broadcast it from a scalar.
5022   // But override that restriction when optimizing for size.
5023   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5024   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5025     EVT CVT = Ld.getValueType();
5026     assert(!CVT.isVector() && "Must not broadcast a vector type");
5027
5028     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5029     // For size optimization, also splat v2f64 and v2i64, and for size opt
5030     // with AVX2, also splat i8 and i16.
5031     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5032     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5033         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5034       const Constant *C = nullptr;
5035       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5036         C = CI->getConstantIntValue();
5037       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5038         C = CF->getConstantFPValue();
5039
5040       assert(C && "Invalid constant type");
5041
5042       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5043       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5044       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5045       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5046                        MachinePointerInfo::getConstantPool(),
5047                        false, false, false, Alignment);
5048
5049       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5050     }
5051   }
5052
5053   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5054
5055   // Handle AVX2 in-register broadcasts.
5056   if (!IsLoad && Subtarget->hasInt256() &&
5057       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5058     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5059
5060   // The scalar source must be a normal load.
5061   if (!IsLoad)
5062     return SDValue();
5063
5064   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5065       (Subtarget->hasVLX() && ScalarSize == 64))
5066     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5067
5068   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5069   // double since there is no vbroadcastsd xmm
5070   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5071     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5072       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5073   }
5074
5075   // Unsupported broadcast.
5076   return SDValue();
5077 }
5078
5079 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5080 /// underlying vector and index.
5081 ///
5082 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5083 /// index.
5084 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5085                                          SDValue ExtIdx) {
5086   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5087   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5088     return Idx;
5089
5090   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5091   // lowered this:
5092   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5093   // to:
5094   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5095   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5096   //                           undef)
5097   //                       Constant<0>)
5098   // In this case the vector is the extract_subvector expression and the index
5099   // is 2, as specified by the shuffle.
5100   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5101   SDValue ShuffleVec = SVOp->getOperand(0);
5102   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5103   assert(ShuffleVecVT.getVectorElementType() ==
5104          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5105
5106   int ShuffleIdx = SVOp->getMaskElt(Idx);
5107   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5108     ExtractedFromVec = ShuffleVec;
5109     return ShuffleIdx;
5110   }
5111   return Idx;
5112 }
5113
5114 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5115   MVT VT = Op.getSimpleValueType();
5116
5117   // Skip if insert_vec_elt is not supported.
5118   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5119   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5120     return SDValue();
5121
5122   SDLoc DL(Op);
5123   unsigned NumElems = Op.getNumOperands();
5124
5125   SDValue VecIn1;
5126   SDValue VecIn2;
5127   SmallVector<unsigned, 4> InsertIndices;
5128   SmallVector<int, 8> Mask(NumElems, -1);
5129
5130   for (unsigned i = 0; i != NumElems; ++i) {
5131     unsigned Opc = Op.getOperand(i).getOpcode();
5132
5133     if (Opc == ISD::UNDEF)
5134       continue;
5135
5136     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5137       // Quit if more than 1 elements need inserting.
5138       if (InsertIndices.size() > 1)
5139         return SDValue();
5140
5141       InsertIndices.push_back(i);
5142       continue;
5143     }
5144
5145     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5146     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5147     // Quit if non-constant index.
5148     if (!isa<ConstantSDNode>(ExtIdx))
5149       return SDValue();
5150     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5151
5152     // Quit if extracted from vector of different type.
5153     if (ExtractedFromVec.getValueType() != VT)
5154       return SDValue();
5155
5156     if (!VecIn1.getNode())
5157       VecIn1 = ExtractedFromVec;
5158     else if (VecIn1 != ExtractedFromVec) {
5159       if (!VecIn2.getNode())
5160         VecIn2 = ExtractedFromVec;
5161       else if (VecIn2 != ExtractedFromVec)
5162         // Quit if more than 2 vectors to shuffle
5163         return SDValue();
5164     }
5165
5166     if (ExtractedFromVec == VecIn1)
5167       Mask[i] = Idx;
5168     else if (ExtractedFromVec == VecIn2)
5169       Mask[i] = Idx + NumElems;
5170   }
5171
5172   if (!VecIn1.getNode())
5173     return SDValue();
5174
5175   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5176   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5177   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5178     unsigned Idx = InsertIndices[i];
5179     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5180                      DAG.getIntPtrConstant(Idx, DL));
5181   }
5182
5183   return NV;
5184 }
5185
5186 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5187 SDValue
5188 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5189
5190   MVT VT = Op.getSimpleValueType();
5191   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5192          "Unexpected type in LowerBUILD_VECTORvXi1!");
5193
5194   SDLoc dl(Op);
5195   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5196     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5197     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5198     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5199   }
5200
5201   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5202     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5203     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5204     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5205   }
5206
5207   bool AllContants = true;
5208   uint64_t Immediate = 0;
5209   int NonConstIdx = -1;
5210   bool IsSplat = true;
5211   unsigned NumNonConsts = 0;
5212   unsigned NumConsts = 0;
5213   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5214     SDValue In = Op.getOperand(idx);
5215     if (In.getOpcode() == ISD::UNDEF)
5216       continue;
5217     if (!isa<ConstantSDNode>(In)) {
5218       AllContants = false;
5219       NonConstIdx = idx;
5220       NumNonConsts++;
5221     } else {
5222       NumConsts++;
5223       if (cast<ConstantSDNode>(In)->getZExtValue())
5224       Immediate |= (1ULL << idx);
5225     }
5226     if (In != Op.getOperand(0))
5227       IsSplat = false;
5228   }
5229
5230   if (AllContants) {
5231     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5232       DAG.getConstant(Immediate, dl, MVT::i16));
5233     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5234                        DAG.getIntPtrConstant(0, dl));
5235   }
5236
5237   if (NumNonConsts == 1 && NonConstIdx != 0) {
5238     SDValue DstVec;
5239     if (NumConsts) {
5240       SDValue VecAsImm = DAG.getConstant(Immediate, dl,
5241                                          MVT::getIntegerVT(VT.getSizeInBits()));
5242       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5243     }
5244     else
5245       DstVec = DAG.getUNDEF(VT);
5246     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5247                        Op.getOperand(NonConstIdx),
5248                        DAG.getIntPtrConstant(NonConstIdx, dl));
5249   }
5250   if (!IsSplat && (NonConstIdx != 0))
5251     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5252   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5253   SDValue Select;
5254   if (IsSplat)
5255     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5256                           DAG.getConstant(-1, dl, SelectVT),
5257                           DAG.getConstant(0, dl, SelectVT));
5258   else
5259     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5260                          DAG.getConstant((Immediate | 1), dl, SelectVT),
5261                          DAG.getConstant(Immediate, dl, SelectVT));
5262   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5263 }
5264
5265 /// \brief Return true if \p N implements a horizontal binop and return the
5266 /// operands for the horizontal binop into V0 and V1.
5267 ///
5268 /// This is a helper function of LowerToHorizontalOp().
5269 /// This function checks that the build_vector \p N in input implements a
5270 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5271 /// operation to match.
5272 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5273 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5274 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5275 /// arithmetic sub.
5276 ///
5277 /// This function only analyzes elements of \p N whose indices are
5278 /// in range [BaseIdx, LastIdx).
5279 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5280                               SelectionDAG &DAG,
5281                               unsigned BaseIdx, unsigned LastIdx,
5282                               SDValue &V0, SDValue &V1) {
5283   EVT VT = N->getValueType(0);
5284
5285   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5286   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5287          "Invalid Vector in input!");
5288
5289   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5290   bool CanFold = true;
5291   unsigned ExpectedVExtractIdx = BaseIdx;
5292   unsigned NumElts = LastIdx - BaseIdx;
5293   V0 = DAG.getUNDEF(VT);
5294   V1 = DAG.getUNDEF(VT);
5295
5296   // Check if N implements a horizontal binop.
5297   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5298     SDValue Op = N->getOperand(i + BaseIdx);
5299
5300     // Skip UNDEFs.
5301     if (Op->getOpcode() == ISD::UNDEF) {
5302       // Update the expected vector extract index.
5303       if (i * 2 == NumElts)
5304         ExpectedVExtractIdx = BaseIdx;
5305       ExpectedVExtractIdx += 2;
5306       continue;
5307     }
5308
5309     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5310
5311     if (!CanFold)
5312       break;
5313
5314     SDValue Op0 = Op.getOperand(0);
5315     SDValue Op1 = Op.getOperand(1);
5316
5317     // Try to match the following pattern:
5318     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5319     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5320         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5321         Op0.getOperand(0) == Op1.getOperand(0) &&
5322         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5323         isa<ConstantSDNode>(Op1.getOperand(1)));
5324     if (!CanFold)
5325       break;
5326
5327     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5328     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5329
5330     if (i * 2 < NumElts) {
5331       if (V0.getOpcode() == ISD::UNDEF) {
5332         V0 = Op0.getOperand(0);
5333         if (V0.getValueType() != VT)
5334           return false;
5335       }
5336     } else {
5337       if (V1.getOpcode() == ISD::UNDEF) {
5338         V1 = Op0.getOperand(0);
5339         if (V1.getValueType() != VT)
5340           return false;
5341       }
5342       if (i * 2 == NumElts)
5343         ExpectedVExtractIdx = BaseIdx;
5344     }
5345
5346     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5347     if (I0 == ExpectedVExtractIdx)
5348       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5349     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5350       // Try to match the following dag sequence:
5351       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5352       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5353     } else
5354       CanFold = false;
5355
5356     ExpectedVExtractIdx += 2;
5357   }
5358
5359   return CanFold;
5360 }
5361
5362 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5363 /// a concat_vector.
5364 ///
5365 /// This is a helper function of LowerToHorizontalOp().
5366 /// This function expects two 256-bit vectors called V0 and V1.
5367 /// At first, each vector is split into two separate 128-bit vectors.
5368 /// Then, the resulting 128-bit vectors are used to implement two
5369 /// horizontal binary operations.
5370 ///
5371 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5372 ///
5373 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5374 /// the two new horizontal binop.
5375 /// When Mode is set, the first horizontal binop dag node would take as input
5376 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5377 /// horizontal binop dag node would take as input the lower 128-bit of V1
5378 /// and the upper 128-bit of V1.
5379 ///   Example:
5380 ///     HADD V0_LO, V0_HI
5381 ///     HADD V1_LO, V1_HI
5382 ///
5383 /// Otherwise, the first horizontal binop dag node takes as input the lower
5384 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5385 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5386 ///   Example:
5387 ///     HADD V0_LO, V1_LO
5388 ///     HADD V0_HI, V1_HI
5389 ///
5390 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5391 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5392 /// the upper 128-bits of the result.
5393 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5394                                      SDLoc DL, SelectionDAG &DAG,
5395                                      unsigned X86Opcode, bool Mode,
5396                                      bool isUndefLO, bool isUndefHI) {
5397   EVT VT = V0.getValueType();
5398   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5399          "Invalid nodes in input!");
5400
5401   unsigned NumElts = VT.getVectorNumElements();
5402   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5403   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5404   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5405   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5406   EVT NewVT = V0_LO.getValueType();
5407
5408   SDValue LO = DAG.getUNDEF(NewVT);
5409   SDValue HI = DAG.getUNDEF(NewVT);
5410
5411   if (Mode) {
5412     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5413     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5414       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5415     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5416       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5417   } else {
5418     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5419     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5420                        V1_LO->getOpcode() != ISD::UNDEF))
5421       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5422
5423     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5424                        V1_HI->getOpcode() != ISD::UNDEF))
5425       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5426   }
5427
5428   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5429 }
5430
5431 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5432 /// node.
5433 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5434                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5435   EVT VT = BV->getValueType(0);
5436   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5437       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5438     return SDValue();
5439
5440   SDLoc DL(BV);
5441   unsigned NumElts = VT.getVectorNumElements();
5442   SDValue InVec0 = DAG.getUNDEF(VT);
5443   SDValue InVec1 = DAG.getUNDEF(VT);
5444
5445   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5446           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5447
5448   // Odd-numbered elements in the input build vector are obtained from
5449   // adding two integer/float elements.
5450   // Even-numbered elements in the input build vector are obtained from
5451   // subtracting two integer/float elements.
5452   unsigned ExpectedOpcode = ISD::FSUB;
5453   unsigned NextExpectedOpcode = ISD::FADD;
5454   bool AddFound = false;
5455   bool SubFound = false;
5456
5457   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5458     SDValue Op = BV->getOperand(i);
5459
5460     // Skip 'undef' values.
5461     unsigned Opcode = Op.getOpcode();
5462     if (Opcode == ISD::UNDEF) {
5463       std::swap(ExpectedOpcode, NextExpectedOpcode);
5464       continue;
5465     }
5466
5467     // Early exit if we found an unexpected opcode.
5468     if (Opcode != ExpectedOpcode)
5469       return SDValue();
5470
5471     SDValue Op0 = Op.getOperand(0);
5472     SDValue Op1 = Op.getOperand(1);
5473
5474     // Try to match the following pattern:
5475     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5476     // Early exit if we cannot match that sequence.
5477     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5478         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5479         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5480         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5481         Op0.getOperand(1) != Op1.getOperand(1))
5482       return SDValue();
5483
5484     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5485     if (I0 != i)
5486       return SDValue();
5487
5488     // We found a valid add/sub node. Update the information accordingly.
5489     if (i & 1)
5490       AddFound = true;
5491     else
5492       SubFound = true;
5493
5494     // Update InVec0 and InVec1.
5495     if (InVec0.getOpcode() == ISD::UNDEF) {
5496       InVec0 = Op0.getOperand(0);
5497       if (InVec0.getValueType() != VT)
5498         return SDValue();
5499     }
5500     if (InVec1.getOpcode() == ISD::UNDEF) {
5501       InVec1 = Op1.getOperand(0);
5502       if (InVec1.getValueType() != VT)
5503         return SDValue();
5504     }
5505
5506     // Make sure that operands in input to each add/sub node always
5507     // come from a same pair of vectors.
5508     if (InVec0 != Op0.getOperand(0)) {
5509       if (ExpectedOpcode == ISD::FSUB)
5510         return SDValue();
5511
5512       // FADD is commutable. Try to commute the operands
5513       // and then test again.
5514       std::swap(Op0, Op1);
5515       if (InVec0 != Op0.getOperand(0))
5516         return SDValue();
5517     }
5518
5519     if (InVec1 != Op1.getOperand(0))
5520       return SDValue();
5521
5522     // Update the pair of expected opcodes.
5523     std::swap(ExpectedOpcode, NextExpectedOpcode);
5524   }
5525
5526   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5527   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5528       InVec1.getOpcode() != ISD::UNDEF)
5529     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5530
5531   return SDValue();
5532 }
5533
5534 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5535 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5536                                    const X86Subtarget *Subtarget,
5537                                    SelectionDAG &DAG) {
5538   EVT VT = BV->getValueType(0);
5539   unsigned NumElts = VT.getVectorNumElements();
5540   unsigned NumUndefsLO = 0;
5541   unsigned NumUndefsHI = 0;
5542   unsigned Half = NumElts/2;
5543
5544   // Count the number of UNDEF operands in the build_vector in input.
5545   for (unsigned i = 0, e = Half; i != e; ++i)
5546     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5547       NumUndefsLO++;
5548
5549   for (unsigned i = Half, e = NumElts; i != e; ++i)
5550     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5551       NumUndefsHI++;
5552
5553   // Early exit if this is either a build_vector of all UNDEFs or all the
5554   // operands but one are UNDEF.
5555   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5556     return SDValue();
5557
5558   SDLoc DL(BV);
5559   SDValue InVec0, InVec1;
5560   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5561     // Try to match an SSE3 float HADD/HSUB.
5562     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5563       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5564
5565     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5566       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5567   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5568     // Try to match an SSSE3 integer HADD/HSUB.
5569     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5570       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5571
5572     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5573       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5574   }
5575
5576   if (!Subtarget->hasAVX())
5577     return SDValue();
5578
5579   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5580     // Try to match an AVX horizontal add/sub of packed single/double
5581     // precision floating point values from 256-bit vectors.
5582     SDValue InVec2, InVec3;
5583     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5584         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5585         ((InVec0.getOpcode() == ISD::UNDEF ||
5586           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5587         ((InVec1.getOpcode() == ISD::UNDEF ||
5588           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5589       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5590
5591     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5592         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5593         ((InVec0.getOpcode() == ISD::UNDEF ||
5594           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5595         ((InVec1.getOpcode() == ISD::UNDEF ||
5596           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5597       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5598   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5599     // Try to match an AVX2 horizontal add/sub of signed integers.
5600     SDValue InVec2, InVec3;
5601     unsigned X86Opcode;
5602     bool CanFold = true;
5603
5604     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5605         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5606         ((InVec0.getOpcode() == ISD::UNDEF ||
5607           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5608         ((InVec1.getOpcode() == ISD::UNDEF ||
5609           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5610       X86Opcode = X86ISD::HADD;
5611     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5612         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5613         ((InVec0.getOpcode() == ISD::UNDEF ||
5614           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5615         ((InVec1.getOpcode() == ISD::UNDEF ||
5616           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5617       X86Opcode = X86ISD::HSUB;
5618     else
5619       CanFold = false;
5620
5621     if (CanFold) {
5622       // Fold this build_vector into a single horizontal add/sub.
5623       // Do this only if the target has AVX2.
5624       if (Subtarget->hasAVX2())
5625         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5626
5627       // Do not try to expand this build_vector into a pair of horizontal
5628       // add/sub if we can emit a pair of scalar add/sub.
5629       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5630         return SDValue();
5631
5632       // Convert this build_vector into a pair of horizontal binop followed by
5633       // a concat vector.
5634       bool isUndefLO = NumUndefsLO == Half;
5635       bool isUndefHI = NumUndefsHI == Half;
5636       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5637                                    isUndefLO, isUndefHI);
5638     }
5639   }
5640
5641   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5642        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5643     unsigned X86Opcode;
5644     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5645       X86Opcode = X86ISD::HADD;
5646     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5647       X86Opcode = X86ISD::HSUB;
5648     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5649       X86Opcode = X86ISD::FHADD;
5650     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5651       X86Opcode = X86ISD::FHSUB;
5652     else
5653       return SDValue();
5654
5655     // Don't try to expand this build_vector into a pair of horizontal add/sub
5656     // if we can simply emit a pair of scalar add/sub.
5657     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5658       return SDValue();
5659
5660     // Convert this build_vector into two horizontal add/sub followed by
5661     // a concat vector.
5662     bool isUndefLO = NumUndefsLO == Half;
5663     bool isUndefHI = NumUndefsHI == Half;
5664     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5665                                  isUndefLO, isUndefHI);
5666   }
5667
5668   return SDValue();
5669 }
5670
5671 SDValue
5672 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5673   SDLoc dl(Op);
5674
5675   MVT VT = Op.getSimpleValueType();
5676   MVT ExtVT = VT.getVectorElementType();
5677   unsigned NumElems = Op.getNumOperands();
5678
5679   // Generate vectors for predicate vectors.
5680   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5681     return LowerBUILD_VECTORvXi1(Op, DAG);
5682
5683   // Vectors containing all zeros can be matched by pxor and xorps later
5684   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5685     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5686     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5687     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5688       return Op;
5689
5690     return getZeroVector(VT, Subtarget, DAG, dl);
5691   }
5692
5693   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5694   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5695   // vpcmpeqd on 256-bit vectors.
5696   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5697     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5698       return Op;
5699
5700     if (!VT.is512BitVector())
5701       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5702   }
5703
5704   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5705   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5706     return AddSub;
5707   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5708     return HorizontalOp;
5709   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5710     return Broadcast;
5711
5712   unsigned EVTBits = ExtVT.getSizeInBits();
5713
5714   unsigned NumZero  = 0;
5715   unsigned NumNonZero = 0;
5716   unsigned NonZeros = 0;
5717   bool IsAllConstants = true;
5718   SmallSet<SDValue, 8> Values;
5719   for (unsigned i = 0; i < NumElems; ++i) {
5720     SDValue Elt = Op.getOperand(i);
5721     if (Elt.getOpcode() == ISD::UNDEF)
5722       continue;
5723     Values.insert(Elt);
5724     if (Elt.getOpcode() != ISD::Constant &&
5725         Elt.getOpcode() != ISD::ConstantFP)
5726       IsAllConstants = false;
5727     if (X86::isZeroNode(Elt))
5728       NumZero++;
5729     else {
5730       NonZeros |= (1 << i);
5731       NumNonZero++;
5732     }
5733   }
5734
5735   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5736   if (NumNonZero == 0)
5737     return DAG.getUNDEF(VT);
5738
5739   // Special case for single non-zero, non-undef, element.
5740   if (NumNonZero == 1) {
5741     unsigned Idx = countTrailingZeros(NonZeros);
5742     SDValue Item = Op.getOperand(Idx);
5743
5744     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5745     // the value are obviously zero, truncate the value to i32 and do the
5746     // insertion that way.  Only do this if the value is non-constant or if the
5747     // value is a constant being inserted into element 0.  It is cheaper to do
5748     // a constant pool load than it is to do a movd + shuffle.
5749     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5750         (!IsAllConstants || Idx == 0)) {
5751       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5752         // Handle SSE only.
5753         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5754         EVT VecVT = MVT::v4i32;
5755
5756         // Truncate the value (which may itself be a constant) to i32, and
5757         // convert it to a vector with movd (S2V+shuffle to zero extend).
5758         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5759         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5760         return DAG.getNode(
5761             ISD::BITCAST, dl, VT,
5762             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5763       }
5764     }
5765
5766     // If we have a constant or non-constant insertion into the low element of
5767     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5768     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5769     // depending on what the source datatype is.
5770     if (Idx == 0) {
5771       if (NumZero == 0)
5772         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5773
5774       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5775           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5776         if (VT.is512BitVector()) {
5777           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5778           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5779                              Item, DAG.getIntPtrConstant(0, dl));
5780         }
5781         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5782                "Expected an SSE value type!");
5783         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5784         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5785         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5786       }
5787
5788       // We can't directly insert an i8 or i16 into a vector, so zero extend
5789       // it to i32 first.
5790       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5791         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5792         if (VT.is256BitVector()) {
5793           if (Subtarget->hasAVX()) {
5794             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5795             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5796           } else {
5797             // Without AVX, we need to extend to a 128-bit vector and then
5798             // insert into the 256-bit vector.
5799             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5800             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5801             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5802           }
5803         } else {
5804           assert(VT.is128BitVector() && "Expected an SSE value type!");
5805           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5806           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5807         }
5808         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5809       }
5810     }
5811
5812     // Is it a vector logical left shift?
5813     if (NumElems == 2 && Idx == 1 &&
5814         X86::isZeroNode(Op.getOperand(0)) &&
5815         !X86::isZeroNode(Op.getOperand(1))) {
5816       unsigned NumBits = VT.getSizeInBits();
5817       return getVShift(true, VT,
5818                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5819                                    VT, Op.getOperand(1)),
5820                        NumBits/2, DAG, *this, dl);
5821     }
5822
5823     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5824       return SDValue();
5825
5826     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5827     // is a non-constant being inserted into an element other than the low one,
5828     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5829     // movd/movss) to move this into the low element, then shuffle it into
5830     // place.
5831     if (EVTBits == 32) {
5832       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5833       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5834     }
5835   }
5836
5837   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5838   if (Values.size() == 1) {
5839     if (EVTBits == 32) {
5840       // Instead of a shuffle like this:
5841       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5842       // Check if it's possible to issue this instead.
5843       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5844       unsigned Idx = countTrailingZeros(NonZeros);
5845       SDValue Item = Op.getOperand(Idx);
5846       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5847         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5848     }
5849     return SDValue();
5850   }
5851
5852   // A vector full of immediates; various special cases are already
5853   // handled, so this is best done with a single constant-pool load.
5854   if (IsAllConstants)
5855     return SDValue();
5856
5857   // For AVX-length vectors, see if we can use a vector load to get all of the
5858   // elements, otherwise build the individual 128-bit pieces and use
5859   // shuffles to put them in place.
5860   if (VT.is256BitVector() || VT.is512BitVector()) {
5861     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5862
5863     // Check for a build vector of consecutive loads.
5864     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5865       return LD;
5866
5867     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5868
5869     // Build both the lower and upper subvector.
5870     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5871                                 makeArrayRef(&V[0], NumElems/2));
5872     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5873                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5874
5875     // Recreate the wider vector with the lower and upper part.
5876     if (VT.is256BitVector())
5877       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5878     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5879   }
5880
5881   // Let legalizer expand 2-wide build_vectors.
5882   if (EVTBits == 64) {
5883     if (NumNonZero == 1) {
5884       // One half is zero or undef.
5885       unsigned Idx = countTrailingZeros(NonZeros);
5886       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5887                                  Op.getOperand(Idx));
5888       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5889     }
5890     return SDValue();
5891   }
5892
5893   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5894   if (EVTBits == 8 && NumElems == 16)
5895     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5896                                         Subtarget, *this))
5897       return V;
5898
5899   if (EVTBits == 16 && NumElems == 8)
5900     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5901                                       Subtarget, *this))
5902       return V;
5903
5904   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5905   if (EVTBits == 32 && NumElems == 4)
5906     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5907       return V;
5908
5909   // If element VT is == 32 bits, turn it into a number of shuffles.
5910   SmallVector<SDValue, 8> V(NumElems);
5911   if (NumElems == 4 && NumZero > 0) {
5912     for (unsigned i = 0; i < 4; ++i) {
5913       bool isZero = !(NonZeros & (1 << i));
5914       if (isZero)
5915         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5916       else
5917         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5918     }
5919
5920     for (unsigned i = 0; i < 2; ++i) {
5921       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5922         default: break;
5923         case 0:
5924           V[i] = V[i*2];  // Must be a zero vector.
5925           break;
5926         case 1:
5927           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5928           break;
5929         case 2:
5930           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5931           break;
5932         case 3:
5933           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5934           break;
5935       }
5936     }
5937
5938     bool Reverse1 = (NonZeros & 0x3) == 2;
5939     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5940     int MaskVec[] = {
5941       Reverse1 ? 1 : 0,
5942       Reverse1 ? 0 : 1,
5943       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5944       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5945     };
5946     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5947   }
5948
5949   if (Values.size() > 1 && VT.is128BitVector()) {
5950     // Check for a build vector of consecutive loads.
5951     for (unsigned i = 0; i < NumElems; ++i)
5952       V[i] = Op.getOperand(i);
5953
5954     // Check for elements which are consecutive loads.
5955     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5956       return LD;
5957
5958     // Check for a build vector from mostly shuffle plus few inserting.
5959     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5960       return Sh;
5961
5962     // For SSE 4.1, use insertps to put the high elements into the low element.
5963     if (Subtarget->hasSSE41()) {
5964       SDValue Result;
5965       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5966         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5967       else
5968         Result = DAG.getUNDEF(VT);
5969
5970       for (unsigned i = 1; i < NumElems; ++i) {
5971         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5972         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5973                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
5974       }
5975       return Result;
5976     }
5977
5978     // Otherwise, expand into a number of unpckl*, start by extending each of
5979     // our (non-undef) elements to the full vector width with the element in the
5980     // bottom slot of the vector (which generates no code for SSE).
5981     for (unsigned i = 0; i < NumElems; ++i) {
5982       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5983         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5984       else
5985         V[i] = DAG.getUNDEF(VT);
5986     }
5987
5988     // Next, we iteratively mix elements, e.g. for v4f32:
5989     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5990     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5991     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5992     unsigned EltStride = NumElems >> 1;
5993     while (EltStride != 0) {
5994       for (unsigned i = 0; i < EltStride; ++i) {
5995         // If V[i+EltStride] is undef and this is the first round of mixing,
5996         // then it is safe to just drop this shuffle: V[i] is already in the
5997         // right place, the one element (since it's the first round) being
5998         // inserted as undef can be dropped.  This isn't safe for successive
5999         // rounds because they will permute elements within both vectors.
6000         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6001             EltStride == NumElems/2)
6002           continue;
6003
6004         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6005       }
6006       EltStride >>= 1;
6007     }
6008     return V[0];
6009   }
6010   return SDValue();
6011 }
6012
6013 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6014 // to create 256-bit vectors from two other 128-bit ones.
6015 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6016   SDLoc dl(Op);
6017   MVT ResVT = Op.getSimpleValueType();
6018
6019   assert((ResVT.is256BitVector() ||
6020           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6021
6022   SDValue V1 = Op.getOperand(0);
6023   SDValue V2 = Op.getOperand(1);
6024   unsigned NumElems = ResVT.getVectorNumElements();
6025   if (ResVT.is256BitVector())
6026     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6027
6028   if (Op.getNumOperands() == 4) {
6029     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6030                                 ResVT.getVectorNumElements()/2);
6031     SDValue V3 = Op.getOperand(2);
6032     SDValue V4 = Op.getOperand(3);
6033     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6034       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6035   }
6036   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6037 }
6038
6039 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6040                                        const X86Subtarget *Subtarget,
6041                                        SelectionDAG & DAG) {
6042   SDLoc dl(Op);
6043   MVT ResVT = Op.getSimpleValueType();
6044   unsigned NumOfOperands = Op.getNumOperands();
6045
6046   assert(isPowerOf2_32(NumOfOperands) &&
6047          "Unexpected number of operands in CONCAT_VECTORS");
6048
6049   if (NumOfOperands > 2) {
6050     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6051                                   ResVT.getVectorNumElements()/2);
6052     SmallVector<SDValue, 2> Ops;
6053     for (unsigned i = 0; i < NumOfOperands/2; i++)
6054       Ops.push_back(Op.getOperand(i));
6055     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6056     Ops.clear();
6057     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6058       Ops.push_back(Op.getOperand(i));
6059     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6060     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6061   }
6062
6063   SDValue V1 = Op.getOperand(0);
6064   SDValue V2 = Op.getOperand(1);
6065   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6066   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6067
6068   if (IsZeroV1 && IsZeroV2)
6069     return getZeroVector(ResVT, Subtarget, DAG, dl);
6070
6071   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6072   SDValue Undef = DAG.getUNDEF(ResVT);
6073   unsigned NumElems = ResVT.getVectorNumElements();
6074   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6075
6076   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6077   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6078   if (IsZeroV1)
6079     return V2;
6080
6081   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6082   // Zero the upper bits of V1
6083   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6084   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6085   if (IsZeroV2)
6086     return V1;
6087   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6088 }
6089
6090 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6091                                    const X86Subtarget *Subtarget,
6092                                    SelectionDAG &DAG) {
6093   MVT VT = Op.getSimpleValueType();
6094   if (VT.getVectorElementType() == MVT::i1)
6095     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6096
6097   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6098          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6099           Op.getNumOperands() == 4)));
6100
6101   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6102   // from two other 128-bit ones.
6103
6104   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6105   return LowerAVXCONCAT_VECTORS(Op, DAG);
6106 }
6107
6108
6109 //===----------------------------------------------------------------------===//
6110 // Vector shuffle lowering
6111 //
6112 // This is an experimental code path for lowering vector shuffles on x86. It is
6113 // designed to handle arbitrary vector shuffles and blends, gracefully
6114 // degrading performance as necessary. It works hard to recognize idiomatic
6115 // shuffles and lower them to optimal instruction patterns without leaving
6116 // a framework that allows reasonably efficient handling of all vector shuffle
6117 // patterns.
6118 //===----------------------------------------------------------------------===//
6119
6120 /// \brief Tiny helper function to identify a no-op mask.
6121 ///
6122 /// This is a somewhat boring predicate function. It checks whether the mask
6123 /// array input, which is assumed to be a single-input shuffle mask of the kind
6124 /// used by the X86 shuffle instructions (not a fully general
6125 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6126 /// in-place shuffle are 'no-op's.
6127 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6128   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6129     if (Mask[i] != -1 && Mask[i] != i)
6130       return false;
6131   return true;
6132 }
6133
6134 /// \brief Helper function to classify a mask as a single-input mask.
6135 ///
6136 /// This isn't a generic single-input test because in the vector shuffle
6137 /// lowering we canonicalize single inputs to be the first input operand. This
6138 /// means we can more quickly test for a single input by only checking whether
6139 /// an input from the second operand exists. We also assume that the size of
6140 /// mask corresponds to the size of the input vectors which isn't true in the
6141 /// fully general case.
6142 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6143   for (int M : Mask)
6144     if (M >= (int)Mask.size())
6145       return false;
6146   return true;
6147 }
6148
6149 /// \brief Test whether there are elements crossing 128-bit lanes in this
6150 /// shuffle mask.
6151 ///
6152 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6153 /// and we routinely test for these.
6154 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6155   int LaneSize = 128 / VT.getScalarSizeInBits();
6156   int Size = Mask.size();
6157   for (int i = 0; i < Size; ++i)
6158     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6159       return true;
6160   return false;
6161 }
6162
6163 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6164 ///
6165 /// This checks a shuffle mask to see if it is performing the same
6166 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6167 /// that it is also not lane-crossing. It may however involve a blend from the
6168 /// same lane of a second vector.
6169 ///
6170 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6171 /// non-trivial to compute in the face of undef lanes. The representation is
6172 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6173 /// entries from both V1 and V2 inputs to the wider mask.
6174 static bool
6175 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6176                                 SmallVectorImpl<int> &RepeatedMask) {
6177   int LaneSize = 128 / VT.getScalarSizeInBits();
6178   RepeatedMask.resize(LaneSize, -1);
6179   int Size = Mask.size();
6180   for (int i = 0; i < Size; ++i) {
6181     if (Mask[i] < 0)
6182       continue;
6183     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6184       // This entry crosses lanes, so there is no way to model this shuffle.
6185       return false;
6186
6187     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6188     if (RepeatedMask[i % LaneSize] == -1)
6189       // This is the first non-undef entry in this slot of a 128-bit lane.
6190       RepeatedMask[i % LaneSize] =
6191           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6192     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6193       // Found a mismatch with the repeated mask.
6194       return false;
6195   }
6196   return true;
6197 }
6198
6199 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6200 /// arguments.
6201 ///
6202 /// This is a fast way to test a shuffle mask against a fixed pattern:
6203 ///
6204 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6205 ///
6206 /// It returns true if the mask is exactly as wide as the argument list, and
6207 /// each element of the mask is either -1 (signifying undef) or the value given
6208 /// in the argument.
6209 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6210                                 ArrayRef<int> ExpectedMask) {
6211   if (Mask.size() != ExpectedMask.size())
6212     return false;
6213
6214   int Size = Mask.size();
6215
6216   // If the values are build vectors, we can look through them to find
6217   // equivalent inputs that make the shuffles equivalent.
6218   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6219   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6220
6221   for (int i = 0; i < Size; ++i)
6222     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6223       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6224       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6225       if (!MaskBV || !ExpectedBV ||
6226           MaskBV->getOperand(Mask[i] % Size) !=
6227               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6228         return false;
6229     }
6230
6231   return true;
6232 }
6233
6234 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6235 ///
6236 /// This helper function produces an 8-bit shuffle immediate corresponding to
6237 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6238 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6239 /// example.
6240 ///
6241 /// NB: We rely heavily on "undef" masks preserving the input lane.
6242 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6243                                           SelectionDAG &DAG) {
6244   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6245   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6246   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6247   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6248   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6249
6250   unsigned Imm = 0;
6251   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6252   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6253   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6254   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6255   return DAG.getConstant(Imm, DL, MVT::i8);
6256 }
6257
6258 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6259 ///
6260 /// This is used as a fallback approach when first class blend instructions are
6261 /// unavailable. Currently it is only suitable for integer vectors, but could
6262 /// be generalized for floating point vectors if desirable.
6263 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6264                                             SDValue V2, ArrayRef<int> Mask,
6265                                             SelectionDAG &DAG) {
6266   assert(VT.isInteger() && "Only supports integer vector types!");
6267   MVT EltVT = VT.getScalarType();
6268   int NumEltBits = EltVT.getSizeInBits();
6269   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6270   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6271                                     EltVT);
6272   SmallVector<SDValue, 16> MaskOps;
6273   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6274     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6275       return SDValue(); // Shuffled input!
6276     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6277   }
6278
6279   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6280   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6281   // We have to cast V2 around.
6282   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6283   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6284                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6285                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6286                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6287   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6288 }
6289
6290 /// \brief Try to emit a blend instruction for a shuffle.
6291 ///
6292 /// This doesn't do any checks for the availability of instructions for blending
6293 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6294 /// be matched in the backend with the type given. What it does check for is
6295 /// that the shuffle mask is in fact a blend.
6296 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6297                                          SDValue V2, ArrayRef<int> Mask,
6298                                          const X86Subtarget *Subtarget,
6299                                          SelectionDAG &DAG) {
6300   unsigned BlendMask = 0;
6301   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6302     if (Mask[i] >= Size) {
6303       if (Mask[i] != i + Size)
6304         return SDValue(); // Shuffled V2 input!
6305       BlendMask |= 1u << i;
6306       continue;
6307     }
6308     if (Mask[i] >= 0 && Mask[i] != i)
6309       return SDValue(); // Shuffled V1 input!
6310   }
6311   switch (VT.SimpleTy) {
6312   case MVT::v2f64:
6313   case MVT::v4f32:
6314   case MVT::v4f64:
6315   case MVT::v8f32:
6316     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6317                        DAG.getConstant(BlendMask, DL, MVT::i8));
6318
6319   case MVT::v4i64:
6320   case MVT::v8i32:
6321     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6322     // FALLTHROUGH
6323   case MVT::v2i64:
6324   case MVT::v4i32:
6325     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6326     // that instruction.
6327     if (Subtarget->hasAVX2()) {
6328       // Scale the blend by the number of 32-bit dwords per element.
6329       int Scale =  VT.getScalarSizeInBits() / 32;
6330       BlendMask = 0;
6331       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6332         if (Mask[i] >= Size)
6333           for (int j = 0; j < Scale; ++j)
6334             BlendMask |= 1u << (i * Scale + j);
6335
6336       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6337       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6338       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6339       return DAG.getNode(ISD::BITCAST, DL, VT,
6340                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6341                                      DAG.getConstant(BlendMask, DL, MVT::i8)));
6342     }
6343     // FALLTHROUGH
6344   case MVT::v8i16: {
6345     // For integer shuffles we need to expand the mask and cast the inputs to
6346     // v8i16s prior to blending.
6347     int Scale = 8 / VT.getVectorNumElements();
6348     BlendMask = 0;
6349     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6350       if (Mask[i] >= Size)
6351         for (int j = 0; j < Scale; ++j)
6352           BlendMask |= 1u << (i * Scale + j);
6353
6354     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6355     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6356     return DAG.getNode(ISD::BITCAST, DL, VT,
6357                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6358                                    DAG.getConstant(BlendMask, DL, MVT::i8)));
6359   }
6360
6361   case MVT::v16i16: {
6362     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6363     SmallVector<int, 8> RepeatedMask;
6364     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6365       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6366       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6367       BlendMask = 0;
6368       for (int i = 0; i < 8; ++i)
6369         if (RepeatedMask[i] >= 16)
6370           BlendMask |= 1u << i;
6371       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6372                          DAG.getConstant(BlendMask, DL, MVT::i8));
6373     }
6374   }
6375     // FALLTHROUGH
6376   case MVT::v16i8:
6377   case MVT::v32i8: {
6378     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6379            "256-bit byte-blends require AVX2 support!");
6380
6381     // Scale the blend by the number of bytes per element.
6382     int Scale = VT.getScalarSizeInBits() / 8;
6383
6384     // This form of blend is always done on bytes. Compute the byte vector
6385     // type.
6386     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6387
6388     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6389     // mix of LLVM's code generator and the x86 backend. We tell the code
6390     // generator that boolean values in the elements of an x86 vector register
6391     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6392     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6393     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6394     // of the element (the remaining are ignored) and 0 in that high bit would
6395     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6396     // the LLVM model for boolean values in vector elements gets the relevant
6397     // bit set, it is set backwards and over constrained relative to x86's
6398     // actual model.
6399     SmallVector<SDValue, 32> VSELECTMask;
6400     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6401       for (int j = 0; j < Scale; ++j)
6402         VSELECTMask.push_back(
6403             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6404                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6405                                           MVT::i8));
6406
6407     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6408     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6409     return DAG.getNode(
6410         ISD::BITCAST, DL, VT,
6411         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6412                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6413                     V1, V2));
6414   }
6415
6416   default:
6417     llvm_unreachable("Not a supported integer vector type!");
6418   }
6419 }
6420
6421 /// \brief Try to lower as a blend of elements from two inputs followed by
6422 /// a single-input permutation.
6423 ///
6424 /// This matches the pattern where we can blend elements from two inputs and
6425 /// then reduce the shuffle to a single-input permutation.
6426 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6427                                                    SDValue V2,
6428                                                    ArrayRef<int> Mask,
6429                                                    SelectionDAG &DAG) {
6430   // We build up the blend mask while checking whether a blend is a viable way
6431   // to reduce the shuffle.
6432   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6433   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6434
6435   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6436     if (Mask[i] < 0)
6437       continue;
6438
6439     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6440
6441     if (BlendMask[Mask[i] % Size] == -1)
6442       BlendMask[Mask[i] % Size] = Mask[i];
6443     else if (BlendMask[Mask[i] % Size] != Mask[i])
6444       return SDValue(); // Can't blend in the needed input!
6445
6446     PermuteMask[i] = Mask[i] % Size;
6447   }
6448
6449   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6450   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6451 }
6452
6453 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6454 /// blends and permutes.
6455 ///
6456 /// This matches the extremely common pattern for handling combined
6457 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6458 /// operations. It will try to pick the best arrangement of shuffles and
6459 /// blends.
6460 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6461                                                           SDValue V1,
6462                                                           SDValue V2,
6463                                                           ArrayRef<int> Mask,
6464                                                           SelectionDAG &DAG) {
6465   // Shuffle the input elements into the desired positions in V1 and V2 and
6466   // blend them together.
6467   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6468   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6469   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6470   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6471     if (Mask[i] >= 0 && Mask[i] < Size) {
6472       V1Mask[i] = Mask[i];
6473       BlendMask[i] = i;
6474     } else if (Mask[i] >= Size) {
6475       V2Mask[i] = Mask[i] - Size;
6476       BlendMask[i] = i + Size;
6477     }
6478
6479   // Try to lower with the simpler initial blend strategy unless one of the
6480   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6481   // shuffle may be able to fold with a load or other benefit. However, when
6482   // we'll have to do 2x as many shuffles in order to achieve this, blending
6483   // first is a better strategy.
6484   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6485     if (SDValue BlendPerm =
6486             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6487       return BlendPerm;
6488
6489   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6490   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6491   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6492 }
6493
6494 /// \brief Try to lower a vector shuffle as a byte rotation.
6495 ///
6496 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6497 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6498 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6499 /// try to generically lower a vector shuffle through such an pattern. It
6500 /// does not check for the profitability of lowering either as PALIGNR or
6501 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6502 /// This matches shuffle vectors that look like:
6503 ///
6504 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6505 ///
6506 /// Essentially it concatenates V1 and V2, shifts right by some number of
6507 /// elements, and takes the low elements as the result. Note that while this is
6508 /// specified as a *right shift* because x86 is little-endian, it is a *left
6509 /// rotate* of the vector lanes.
6510 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6511                                               SDValue V2,
6512                                               ArrayRef<int> Mask,
6513                                               const X86Subtarget *Subtarget,
6514                                               SelectionDAG &DAG) {
6515   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6516
6517   int NumElts = Mask.size();
6518   int NumLanes = VT.getSizeInBits() / 128;
6519   int NumLaneElts = NumElts / NumLanes;
6520
6521   // We need to detect various ways of spelling a rotation:
6522   //   [11, 12, 13, 14, 15,  0,  1,  2]
6523   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6524   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6525   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6526   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6527   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6528   int Rotation = 0;
6529   SDValue Lo, Hi;
6530   for (int l = 0; l < NumElts; l += NumLaneElts) {
6531     for (int i = 0; i < NumLaneElts; ++i) {
6532       if (Mask[l + i] == -1)
6533         continue;
6534       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6535
6536       // Get the mod-Size index and lane correct it.
6537       int LaneIdx = (Mask[l + i] % NumElts) - l;
6538       // Make sure it was in this lane.
6539       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6540         return SDValue();
6541
6542       // Determine where a rotated vector would have started.
6543       int StartIdx = i - LaneIdx;
6544       if (StartIdx == 0)
6545         // The identity rotation isn't interesting, stop.
6546         return SDValue();
6547
6548       // If we found the tail of a vector the rotation must be the missing
6549       // front. If we found the head of a vector, it must be how much of the
6550       // head.
6551       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6552
6553       if (Rotation == 0)
6554         Rotation = CandidateRotation;
6555       else if (Rotation != CandidateRotation)
6556         // The rotations don't match, so we can't match this mask.
6557         return SDValue();
6558
6559       // Compute which value this mask is pointing at.
6560       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6561
6562       // Compute which of the two target values this index should be assigned
6563       // to. This reflects whether the high elements are remaining or the low
6564       // elements are remaining.
6565       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6566
6567       // Either set up this value if we've not encountered it before, or check
6568       // that it remains consistent.
6569       if (!TargetV)
6570         TargetV = MaskV;
6571       else if (TargetV != MaskV)
6572         // This may be a rotation, but it pulls from the inputs in some
6573         // unsupported interleaving.
6574         return SDValue();
6575     }
6576   }
6577
6578   // Check that we successfully analyzed the mask, and normalize the results.
6579   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6580   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6581   if (!Lo)
6582     Lo = Hi;
6583   else if (!Hi)
6584     Hi = Lo;
6585
6586   // The actual rotate instruction rotates bytes, so we need to scale the
6587   // rotation based on how many bytes are in the vector lane.
6588   int Scale = 16 / NumLaneElts;
6589
6590   // SSSE3 targets can use the palignr instruction.
6591   if (Subtarget->hasSSSE3()) {
6592     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6593     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6594     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6595     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6596
6597     return DAG.getNode(ISD::BITCAST, DL, VT,
6598                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6599                                    DAG.getConstant(Rotation * Scale, DL,
6600                                                    MVT::i8)));
6601   }
6602
6603   assert(VT.getSizeInBits() == 128 &&
6604          "Rotate-based lowering only supports 128-bit lowering!");
6605   assert(Mask.size() <= 16 &&
6606          "Can shuffle at most 16 bytes in a 128-bit vector!");
6607
6608   // Default SSE2 implementation
6609   int LoByteShift = 16 - Rotation * Scale;
6610   int HiByteShift = Rotation * Scale;
6611
6612   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6613   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6614   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6615
6616   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6617                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6618   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6619                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6620   return DAG.getNode(ISD::BITCAST, DL, VT,
6621                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6622 }
6623
6624 /// \brief Compute whether each element of a shuffle is zeroable.
6625 ///
6626 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6627 /// Either it is an undef element in the shuffle mask, the element of the input
6628 /// referenced is undef, or the element of the input referenced is known to be
6629 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6630 /// as many lanes with this technique as possible to simplify the remaining
6631 /// shuffle.
6632 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6633                                                      SDValue V1, SDValue V2) {
6634   SmallBitVector Zeroable(Mask.size(), false);
6635
6636   while (V1.getOpcode() == ISD::BITCAST)
6637     V1 = V1->getOperand(0);
6638   while (V2.getOpcode() == ISD::BITCAST)
6639     V2 = V2->getOperand(0);
6640
6641   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6642   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6643
6644   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6645     int M = Mask[i];
6646     // Handle the easy cases.
6647     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6648       Zeroable[i] = true;
6649       continue;
6650     }
6651
6652     // If this is an index into a build_vector node (which has the same number
6653     // of elements), dig out the input value and use it.
6654     SDValue V = M < Size ? V1 : V2;
6655     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6656       continue;
6657
6658     SDValue Input = V.getOperand(M % Size);
6659     // The UNDEF opcode check really should be dead code here, but not quite
6660     // worth asserting on (it isn't invalid, just unexpected).
6661     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6662       Zeroable[i] = true;
6663   }
6664
6665   return Zeroable;
6666 }
6667
6668 /// \brief Try to emit a bitmask instruction for a shuffle.
6669 ///
6670 /// This handles cases where we can model a blend exactly as a bitmask due to
6671 /// one of the inputs being zeroable.
6672 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6673                                            SDValue V2, ArrayRef<int> Mask,
6674                                            SelectionDAG &DAG) {
6675   MVT EltVT = VT.getScalarType();
6676   int NumEltBits = EltVT.getSizeInBits();
6677   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6678   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6679   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6680                                     IntEltVT);
6681   if (EltVT.isFloatingPoint()) {
6682     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6683     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6684   }
6685   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6686   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6687   SDValue V;
6688   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6689     if (Zeroable[i])
6690       continue;
6691     if (Mask[i] % Size != i)
6692       return SDValue(); // Not a blend.
6693     if (!V)
6694       V = Mask[i] < Size ? V1 : V2;
6695     else if (V != (Mask[i] < Size ? V1 : V2))
6696       return SDValue(); // Can only let one input through the mask.
6697
6698     VMaskOps[i] = AllOnes;
6699   }
6700   if (!V)
6701     return SDValue(); // No non-zeroable elements!
6702
6703   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6704   V = DAG.getNode(VT.isFloatingPoint()
6705                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6706                   DL, VT, V, VMask);
6707   return V;
6708 }
6709
6710 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6711 ///
6712 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6713 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6714 /// matches elements from one of the input vectors shuffled to the left or
6715 /// right with zeroable elements 'shifted in'. It handles both the strictly
6716 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6717 /// quad word lane.
6718 ///
6719 /// PSHL : (little-endian) left bit shift.
6720 /// [ zz, 0, zz,  2 ]
6721 /// [ -1, 4, zz, -1 ]
6722 /// PSRL : (little-endian) right bit shift.
6723 /// [  1, zz,  3, zz]
6724 /// [ -1, -1,  7, zz]
6725 /// PSLLDQ : (little-endian) left byte shift
6726 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6727 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6728 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6729 /// PSRLDQ : (little-endian) right byte shift
6730 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6731 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6732 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6733 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6734                                          SDValue V2, ArrayRef<int> Mask,
6735                                          SelectionDAG &DAG) {
6736   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6737
6738   int Size = Mask.size();
6739   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6740
6741   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6742     for (int i = 0; i < Size; i += Scale)
6743       for (int j = 0; j < Shift; ++j)
6744         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6745           return false;
6746
6747     return true;
6748   };
6749
6750   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6751     for (int i = 0; i != Size; i += Scale) {
6752       unsigned Pos = Left ? i + Shift : i;
6753       unsigned Low = Left ? i : i + Shift;
6754       unsigned Len = Scale - Shift;
6755       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6756                                       Low + (V == V1 ? 0 : Size)))
6757         return SDValue();
6758     }
6759
6760     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6761     bool ByteShift = ShiftEltBits > 64;
6762     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6763                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6764     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6765
6766     // Normalize the scale for byte shifts to still produce an i64 element
6767     // type.
6768     Scale = ByteShift ? Scale / 2 : Scale;
6769
6770     // We need to round trip through the appropriate type for the shift.
6771     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6772     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6773     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6774            "Illegal integer vector type");
6775     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6776
6777     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6778                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6779     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6780   };
6781
6782   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6783   // keep doubling the size of the integer elements up to that. We can
6784   // then shift the elements of the integer vector by whole multiples of
6785   // their width within the elements of the larger integer vector. Test each
6786   // multiple to see if we can find a match with the moved element indices
6787   // and that the shifted in elements are all zeroable.
6788   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6789     for (int Shift = 1; Shift != Scale; ++Shift)
6790       for (bool Left : {true, false})
6791         if (CheckZeros(Shift, Scale, Left))
6792           for (SDValue V : {V1, V2})
6793             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6794               return Match;
6795
6796   // no match
6797   return SDValue();
6798 }
6799
6800 /// \brief Lower a vector shuffle as a zero or any extension.
6801 ///
6802 /// Given a specific number of elements, element bit width, and extension
6803 /// stride, produce either a zero or any extension based on the available
6804 /// features of the subtarget.
6805 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6806     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6807     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6808   assert(Scale > 1 && "Need a scale to extend.");
6809   int NumElements = VT.getVectorNumElements();
6810   int EltBits = VT.getScalarSizeInBits();
6811   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6812          "Only 8, 16, and 32 bit elements can be extended.");
6813   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6814
6815   // Found a valid zext mask! Try various lowering strategies based on the
6816   // input type and available ISA extensions.
6817   if (Subtarget->hasSSE41()) {
6818     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6819                                  NumElements / Scale);
6820     return DAG.getNode(ISD::BITCAST, DL, VT,
6821                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6822   }
6823
6824   // For any extends we can cheat for larger element sizes and use shuffle
6825   // instructions that can fold with a load and/or copy.
6826   if (AnyExt && EltBits == 32) {
6827     int PSHUFDMask[4] = {0, -1, 1, -1};
6828     return DAG.getNode(
6829         ISD::BITCAST, DL, VT,
6830         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6831                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6832                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6833   }
6834   if (AnyExt && EltBits == 16 && Scale > 2) {
6835     int PSHUFDMask[4] = {0, -1, 0, -1};
6836     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6837                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6838                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6839     int PSHUFHWMask[4] = {1, -1, -1, -1};
6840     return DAG.getNode(
6841         ISD::BITCAST, DL, VT,
6842         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6843                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6844                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6845   }
6846
6847   // If this would require more than 2 unpack instructions to expand, use
6848   // pshufb when available. We can only use more than 2 unpack instructions
6849   // when zero extending i8 elements which also makes it easier to use pshufb.
6850   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6851     assert(NumElements == 16 && "Unexpected byte vector width!");
6852     SDValue PSHUFBMask[16];
6853     for (int i = 0; i < 16; ++i)
6854       PSHUFBMask[i] =
6855           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6856     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6857     return DAG.getNode(ISD::BITCAST, DL, VT,
6858                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6859                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6860                                                MVT::v16i8, PSHUFBMask)));
6861   }
6862
6863   // Otherwise emit a sequence of unpacks.
6864   do {
6865     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6866     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6867                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6868     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6869     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6870     Scale /= 2;
6871     EltBits *= 2;
6872     NumElements /= 2;
6873   } while (Scale > 1);
6874   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6875 }
6876
6877 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6878 ///
6879 /// This routine will try to do everything in its power to cleverly lower
6880 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6881 /// check for the profitability of this lowering,  it tries to aggressively
6882 /// match this pattern. It will use all of the micro-architectural details it
6883 /// can to emit an efficient lowering. It handles both blends with all-zero
6884 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6885 /// masking out later).
6886 ///
6887 /// The reason we have dedicated lowering for zext-style shuffles is that they
6888 /// are both incredibly common and often quite performance sensitive.
6889 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6890     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6891     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6892   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6893
6894   int Bits = VT.getSizeInBits();
6895   int NumElements = VT.getVectorNumElements();
6896   assert(VT.getScalarSizeInBits() <= 32 &&
6897          "Exceeds 32-bit integer zero extension limit");
6898   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6899
6900   // Define a helper function to check a particular ext-scale and lower to it if
6901   // valid.
6902   auto Lower = [&](int Scale) -> SDValue {
6903     SDValue InputV;
6904     bool AnyExt = true;
6905     for (int i = 0; i < NumElements; ++i) {
6906       if (Mask[i] == -1)
6907         continue; // Valid anywhere but doesn't tell us anything.
6908       if (i % Scale != 0) {
6909         // Each of the extended elements need to be zeroable.
6910         if (!Zeroable[i])
6911           return SDValue();
6912
6913         // We no longer are in the anyext case.
6914         AnyExt = false;
6915         continue;
6916       }
6917
6918       // Each of the base elements needs to be consecutive indices into the
6919       // same input vector.
6920       SDValue V = Mask[i] < NumElements ? V1 : V2;
6921       if (!InputV)
6922         InputV = V;
6923       else if (InputV != V)
6924         return SDValue(); // Flip-flopping inputs.
6925
6926       if (Mask[i] % NumElements != i / Scale)
6927         return SDValue(); // Non-consecutive strided elements.
6928     }
6929
6930     // If we fail to find an input, we have a zero-shuffle which should always
6931     // have already been handled.
6932     // FIXME: Maybe handle this here in case during blending we end up with one?
6933     if (!InputV)
6934       return SDValue();
6935
6936     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6937         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6938   };
6939
6940   // The widest scale possible for extending is to a 64-bit integer.
6941   assert(Bits % 64 == 0 &&
6942          "The number of bits in a vector must be divisible by 64 on x86!");
6943   int NumExtElements = Bits / 64;
6944
6945   // Each iteration, try extending the elements half as much, but into twice as
6946   // many elements.
6947   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6948     assert(NumElements % NumExtElements == 0 &&
6949            "The input vector size must be divisible by the extended size.");
6950     if (SDValue V = Lower(NumElements / NumExtElements))
6951       return V;
6952   }
6953
6954   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6955   if (Bits != 128)
6956     return SDValue();
6957
6958   // Returns one of the source operands if the shuffle can be reduced to a
6959   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6960   auto CanZExtLowHalf = [&]() {
6961     for (int i = NumElements / 2; i != NumElements; ++i)
6962       if (!Zeroable[i])
6963         return SDValue();
6964     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6965       return V1;
6966     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6967       return V2;
6968     return SDValue();
6969   };
6970
6971   if (SDValue V = CanZExtLowHalf()) {
6972     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6973     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6974     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6975   }
6976
6977   // No viable ext lowering found.
6978   return SDValue();
6979 }
6980
6981 /// \brief Try to get a scalar value for a specific element of a vector.
6982 ///
6983 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6984 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6985                                               SelectionDAG &DAG) {
6986   MVT VT = V.getSimpleValueType();
6987   MVT EltVT = VT.getVectorElementType();
6988   while (V.getOpcode() == ISD::BITCAST)
6989     V = V.getOperand(0);
6990   // If the bitcasts shift the element size, we can't extract an equivalent
6991   // element from it.
6992   MVT NewVT = V.getSimpleValueType();
6993   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6994     return SDValue();
6995
6996   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6997       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
6998     // Ensure the scalar operand is the same size as the destination.
6999     // FIXME: Add support for scalar truncation where possible.
7000     SDValue S = V.getOperand(Idx);
7001     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7002       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7003   }
7004
7005   return SDValue();
7006 }
7007
7008 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7009 ///
7010 /// This is particularly important because the set of instructions varies
7011 /// significantly based on whether the operand is a load or not.
7012 static bool isShuffleFoldableLoad(SDValue V) {
7013   while (V.getOpcode() == ISD::BITCAST)
7014     V = V.getOperand(0);
7015
7016   return ISD::isNON_EXTLoad(V.getNode());
7017 }
7018
7019 /// \brief Try to lower insertion of a single element into a zero vector.
7020 ///
7021 /// This is a common pattern that we have especially efficient patterns to lower
7022 /// across all subtarget feature sets.
7023 static SDValue lowerVectorShuffleAsElementInsertion(
7024     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7025     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7026   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7027   MVT ExtVT = VT;
7028   MVT EltVT = VT.getVectorElementType();
7029
7030   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7031                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7032                 Mask.begin();
7033   bool IsV1Zeroable = true;
7034   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7035     if (i != V2Index && !Zeroable[i]) {
7036       IsV1Zeroable = false;
7037       break;
7038     }
7039
7040   // Check for a single input from a SCALAR_TO_VECTOR node.
7041   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7042   // all the smarts here sunk into that routine. However, the current
7043   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7044   // vector shuffle lowering is dead.
7045   if (SDValue V2S = getScalarValueForVectorElement(
7046           V2, Mask[V2Index] - Mask.size(), DAG)) {
7047     // We need to zext the scalar if it is smaller than an i32.
7048     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7049     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7050       // Using zext to expand a narrow element won't work for non-zero
7051       // insertions.
7052       if (!IsV1Zeroable)
7053         return SDValue();
7054
7055       // Zero-extend directly to i32.
7056       ExtVT = MVT::v4i32;
7057       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7058     }
7059     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7060   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7061              EltVT == MVT::i16) {
7062     // Either not inserting from the low element of the input or the input
7063     // element size is too small to use VZEXT_MOVL to clear the high bits.
7064     return SDValue();
7065   }
7066
7067   if (!IsV1Zeroable) {
7068     // If V1 can't be treated as a zero vector we have fewer options to lower
7069     // this. We can't support integer vectors or non-zero targets cheaply, and
7070     // the V1 elements can't be permuted in any way.
7071     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7072     if (!VT.isFloatingPoint() || V2Index != 0)
7073       return SDValue();
7074     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7075     V1Mask[V2Index] = -1;
7076     if (!isNoopShuffleMask(V1Mask))
7077       return SDValue();
7078     // This is essentially a special case blend operation, but if we have
7079     // general purpose blend operations, they are always faster. Bail and let
7080     // the rest of the lowering handle these as blends.
7081     if (Subtarget->hasSSE41())
7082       return SDValue();
7083
7084     // Otherwise, use MOVSD or MOVSS.
7085     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7086            "Only two types of floating point element types to handle!");
7087     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7088                        ExtVT, V1, V2);
7089   }
7090
7091   // This lowering only works for the low element with floating point vectors.
7092   if (VT.isFloatingPoint() && V2Index != 0)
7093     return SDValue();
7094
7095   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7096   if (ExtVT != VT)
7097     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7098
7099   if (V2Index != 0) {
7100     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7101     // the desired position. Otherwise it is more efficient to do a vector
7102     // shift left. We know that we can do a vector shift left because all
7103     // the inputs are zero.
7104     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7105       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7106       V2Shuffle[V2Index] = 0;
7107       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7108     } else {
7109       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7110       V2 = DAG.getNode(
7111           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7112           DAG.getConstant(
7113               V2Index * EltVT.getSizeInBits()/8, DL,
7114               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7115       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7116     }
7117   }
7118   return V2;
7119 }
7120
7121 /// \brief Try to lower broadcast of a single element.
7122 ///
7123 /// For convenience, this code also bundles all of the subtarget feature set
7124 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7125 /// a convenient way to factor it out.
7126 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7127                                              ArrayRef<int> Mask,
7128                                              const X86Subtarget *Subtarget,
7129                                              SelectionDAG &DAG) {
7130   if (!Subtarget->hasAVX())
7131     return SDValue();
7132   if (VT.isInteger() && !Subtarget->hasAVX2())
7133     return SDValue();
7134
7135   // Check that the mask is a broadcast.
7136   int BroadcastIdx = -1;
7137   for (int M : Mask)
7138     if (M >= 0 && BroadcastIdx == -1)
7139       BroadcastIdx = M;
7140     else if (M >= 0 && M != BroadcastIdx)
7141       return SDValue();
7142
7143   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7144                                             "a sorted mask where the broadcast "
7145                                             "comes from V1.");
7146
7147   // Go up the chain of (vector) values to find a scalar load that we can
7148   // combine with the broadcast.
7149   for (;;) {
7150     switch (V.getOpcode()) {
7151     case ISD::CONCAT_VECTORS: {
7152       int OperandSize = Mask.size() / V.getNumOperands();
7153       V = V.getOperand(BroadcastIdx / OperandSize);
7154       BroadcastIdx %= OperandSize;
7155       continue;
7156     }
7157
7158     case ISD::INSERT_SUBVECTOR: {
7159       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7160       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7161       if (!ConstantIdx)
7162         break;
7163
7164       int BeginIdx = (int)ConstantIdx->getZExtValue();
7165       int EndIdx =
7166           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7167       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7168         BroadcastIdx -= BeginIdx;
7169         V = VInner;
7170       } else {
7171         V = VOuter;
7172       }
7173       continue;
7174     }
7175     }
7176     break;
7177   }
7178
7179   // Check if this is a broadcast of a scalar. We special case lowering
7180   // for scalars so that we can more effectively fold with loads.
7181   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7182       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7183     V = V.getOperand(BroadcastIdx);
7184
7185     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7186     // Only AVX2 has register broadcasts.
7187     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7188       return SDValue();
7189   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7190     // We can't broadcast from a vector register without AVX2, and we can only
7191     // broadcast from the zero-element of a vector register.
7192     return SDValue();
7193   }
7194
7195   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7196 }
7197
7198 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7199 // INSERTPS when the V1 elements are already in the correct locations
7200 // because otherwise we can just always use two SHUFPS instructions which
7201 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7202 // perform INSERTPS if a single V1 element is out of place and all V2
7203 // elements are zeroable.
7204 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7205                                             ArrayRef<int> Mask,
7206                                             SelectionDAG &DAG) {
7207   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7208   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7209   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7210   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7211
7212   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7213
7214   unsigned ZMask = 0;
7215   int V1DstIndex = -1;
7216   int V2DstIndex = -1;
7217   bool V1UsedInPlace = false;
7218
7219   for (int i = 0; i < 4; ++i) {
7220     // Synthesize a zero mask from the zeroable elements (includes undefs).
7221     if (Zeroable[i]) {
7222       ZMask |= 1 << i;
7223       continue;
7224     }
7225
7226     // Flag if we use any V1 inputs in place.
7227     if (i == Mask[i]) {
7228       V1UsedInPlace = true;
7229       continue;
7230     }
7231
7232     // We can only insert a single non-zeroable element.
7233     if (V1DstIndex != -1 || V2DstIndex != -1)
7234       return SDValue();
7235
7236     if (Mask[i] < 4) {
7237       // V1 input out of place for insertion.
7238       V1DstIndex = i;
7239     } else {
7240       // V2 input for insertion.
7241       V2DstIndex = i;
7242     }
7243   }
7244
7245   // Don't bother if we have no (non-zeroable) element for insertion.
7246   if (V1DstIndex == -1 && V2DstIndex == -1)
7247     return SDValue();
7248
7249   // Determine element insertion src/dst indices. The src index is from the
7250   // start of the inserted vector, not the start of the concatenated vector.
7251   unsigned V2SrcIndex = 0;
7252   if (V1DstIndex != -1) {
7253     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7254     // and don't use the original V2 at all.
7255     V2SrcIndex = Mask[V1DstIndex];
7256     V2DstIndex = V1DstIndex;
7257     V2 = V1;
7258   } else {
7259     V2SrcIndex = Mask[V2DstIndex] - 4;
7260   }
7261
7262   // If no V1 inputs are used in place, then the result is created only from
7263   // the zero mask and the V2 insertion - so remove V1 dependency.
7264   if (!V1UsedInPlace)
7265     V1 = DAG.getUNDEF(MVT::v4f32);
7266
7267   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7268   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7269
7270   // Insert the V2 element into the desired position.
7271   SDLoc DL(Op);
7272   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7273                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7274 }
7275
7276 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7277 /// UNPCK instruction.
7278 ///
7279 /// This specifically targets cases where we end up with alternating between
7280 /// the two inputs, and so can permute them into something that feeds a single
7281 /// UNPCK instruction. Note that this routine only targets integer vectors
7282 /// because for floating point vectors we have a generalized SHUFPS lowering
7283 /// strategy that handles everything that doesn't *exactly* match an unpack,
7284 /// making this clever lowering unnecessary.
7285 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7286                                           SDValue V2, ArrayRef<int> Mask,
7287                                           SelectionDAG &DAG) {
7288   assert(!VT.isFloatingPoint() &&
7289          "This routine only supports integer vectors.");
7290   assert(!isSingleInputShuffleMask(Mask) &&
7291          "This routine should only be used when blending two inputs.");
7292   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7293
7294   int Size = Mask.size();
7295
7296   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7297     return M >= 0 && M % Size < Size / 2;
7298   });
7299   int NumHiInputs = std::count_if(
7300       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7301
7302   bool UnpackLo = NumLoInputs >= NumHiInputs;
7303
7304   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7305     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7306     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7307
7308     for (int i = 0; i < Size; ++i) {
7309       if (Mask[i] < 0)
7310         continue;
7311
7312       // Each element of the unpack contains Scale elements from this mask.
7313       int UnpackIdx = i / Scale;
7314
7315       // We only handle the case where V1 feeds the first slots of the unpack.
7316       // We rely on canonicalization to ensure this is the case.
7317       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7318         return SDValue();
7319
7320       // Setup the mask for this input. The indexing is tricky as we have to
7321       // handle the unpack stride.
7322       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7323       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7324           Mask[i] % Size;
7325     }
7326
7327     // If we will have to shuffle both inputs to use the unpack, check whether
7328     // we can just unpack first and shuffle the result. If so, skip this unpack.
7329     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7330         !isNoopShuffleMask(V2Mask))
7331       return SDValue();
7332
7333     // Shuffle the inputs into place.
7334     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7335     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7336
7337     // Cast the inputs to the type we will use to unpack them.
7338     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7339     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7340
7341     // Unpack the inputs and cast the result back to the desired type.
7342     return DAG.getNode(ISD::BITCAST, DL, VT,
7343                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7344                                    DL, UnpackVT, V1, V2));
7345   };
7346
7347   // We try each unpack from the largest to the smallest to try and find one
7348   // that fits this mask.
7349   int OrigNumElements = VT.getVectorNumElements();
7350   int OrigScalarSize = VT.getScalarSizeInBits();
7351   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7352     int Scale = ScalarSize / OrigScalarSize;
7353     int NumElements = OrigNumElements / Scale;
7354     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7355     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7356       return Unpack;
7357   }
7358
7359   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7360   // initial unpack.
7361   if (NumLoInputs == 0 || NumHiInputs == 0) {
7362     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7363            "We have to have *some* inputs!");
7364     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7365
7366     // FIXME: We could consider the total complexity of the permute of each
7367     // possible unpacking. Or at the least we should consider how many
7368     // half-crossings are created.
7369     // FIXME: We could consider commuting the unpacks.
7370
7371     SmallVector<int, 32> PermMask;
7372     PermMask.assign(Size, -1);
7373     for (int i = 0; i < Size; ++i) {
7374       if (Mask[i] < 0)
7375         continue;
7376
7377       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7378
7379       PermMask[i] =
7380           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7381     }
7382     return DAG.getVectorShuffle(
7383         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7384                             DL, VT, V1, V2),
7385         DAG.getUNDEF(VT), PermMask);
7386   }
7387
7388   return SDValue();
7389 }
7390
7391 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7392 ///
7393 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7394 /// support for floating point shuffles but not integer shuffles. These
7395 /// instructions will incur a domain crossing penalty on some chips though so
7396 /// it is better to avoid lowering through this for integer vectors where
7397 /// possible.
7398 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7399                                        const X86Subtarget *Subtarget,
7400                                        SelectionDAG &DAG) {
7401   SDLoc DL(Op);
7402   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7403   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7404   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7405   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7406   ArrayRef<int> Mask = SVOp->getMask();
7407   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7408
7409   if (isSingleInputShuffleMask(Mask)) {
7410     // Use low duplicate instructions for masks that match their pattern.
7411     if (Subtarget->hasSSE3())
7412       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7413         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7414
7415     // Straight shuffle of a single input vector. Simulate this by using the
7416     // single input as both of the "inputs" to this instruction..
7417     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7418
7419     if (Subtarget->hasAVX()) {
7420       // If we have AVX, we can use VPERMILPS which will allow folding a load
7421       // into the shuffle.
7422       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7423                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7424     }
7425
7426     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7427                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7428   }
7429   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7430   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7431
7432   // If we have a single input, insert that into V1 if we can do so cheaply.
7433   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7434     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7435             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7436       return Insertion;
7437     // Try inverting the insertion since for v2 masks it is easy to do and we
7438     // can't reliably sort the mask one way or the other.
7439     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7440                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7441     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7442             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7443       return Insertion;
7444   }
7445
7446   // Try to use one of the special instruction patterns to handle two common
7447   // blend patterns if a zero-blend above didn't work.
7448   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7449       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7450     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7451       // We can either use a special instruction to load over the low double or
7452       // to move just the low double.
7453       return DAG.getNode(
7454           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7455           DL, MVT::v2f64, V2,
7456           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7457
7458   if (Subtarget->hasSSE41())
7459     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7460                                                   Subtarget, DAG))
7461       return Blend;
7462
7463   // Use dedicated unpack instructions for masks that match their pattern.
7464   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7465     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7466   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7467     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7468
7469   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7470   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7471                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7472 }
7473
7474 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7475 ///
7476 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7477 /// the integer unit to minimize domain crossing penalties. However, for blends
7478 /// it falls back to the floating point shuffle operation with appropriate bit
7479 /// casting.
7480 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7481                                        const X86Subtarget *Subtarget,
7482                                        SelectionDAG &DAG) {
7483   SDLoc DL(Op);
7484   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7485   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7486   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7487   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7488   ArrayRef<int> Mask = SVOp->getMask();
7489   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7490
7491   if (isSingleInputShuffleMask(Mask)) {
7492     // Check for being able to broadcast a single element.
7493     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7494                                                           Mask, Subtarget, DAG))
7495       return Broadcast;
7496
7497     // Straight shuffle of a single input vector. For everything from SSE2
7498     // onward this has a single fast instruction with no scary immediates.
7499     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7500     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7501     int WidenedMask[4] = {
7502         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7503         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7504     return DAG.getNode(
7505         ISD::BITCAST, DL, MVT::v2i64,
7506         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7507                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7508   }
7509   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7510   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7511   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7512   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7513
7514   // If we have a blend of two PACKUS operations an the blend aligns with the
7515   // low and half halves, we can just merge the PACKUS operations. This is
7516   // particularly important as it lets us merge shuffles that this routine itself
7517   // creates.
7518   auto GetPackNode = [](SDValue V) {
7519     while (V.getOpcode() == ISD::BITCAST)
7520       V = V.getOperand(0);
7521
7522     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7523   };
7524   if (SDValue V1Pack = GetPackNode(V1))
7525     if (SDValue V2Pack = GetPackNode(V2))
7526       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7527                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7528                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7529                                                   : V1Pack.getOperand(1),
7530                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7531                                                   : V2Pack.getOperand(1)));
7532
7533   // Try to use shift instructions.
7534   if (SDValue Shift =
7535           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7536     return Shift;
7537
7538   // When loading a scalar and then shuffling it into a vector we can often do
7539   // the insertion cheaply.
7540   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7541           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7542     return Insertion;
7543   // Try inverting the insertion since for v2 masks it is easy to do and we
7544   // can't reliably sort the mask one way or the other.
7545   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7546   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7547           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7548     return Insertion;
7549
7550   // We have different paths for blend lowering, but they all must use the
7551   // *exact* same predicate.
7552   bool IsBlendSupported = Subtarget->hasSSE41();
7553   if (IsBlendSupported)
7554     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7555                                                   Subtarget, DAG))
7556       return Blend;
7557
7558   // Use dedicated unpack instructions for masks that match their pattern.
7559   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7560     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7561   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7562     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7563
7564   // Try to use byte rotation instructions.
7565   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7566   if (Subtarget->hasSSSE3())
7567     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7568             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7569       return Rotate;
7570
7571   // If we have direct support for blends, we should lower by decomposing into
7572   // a permute. That will be faster than the domain cross.
7573   if (IsBlendSupported)
7574     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7575                                                       Mask, DAG);
7576
7577   // We implement this with SHUFPD which is pretty lame because it will likely
7578   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7579   // However, all the alternatives are still more cycles and newer chips don't
7580   // have this problem. It would be really nice if x86 had better shuffles here.
7581   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7582   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7583   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7584                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7585 }
7586
7587 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7588 ///
7589 /// This is used to disable more specialized lowerings when the shufps lowering
7590 /// will happen to be efficient.
7591 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7592   // This routine only handles 128-bit shufps.
7593   assert(Mask.size() == 4 && "Unsupported mask size!");
7594
7595   // To lower with a single SHUFPS we need to have the low half and high half
7596   // each requiring a single input.
7597   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7598     return false;
7599   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7600     return false;
7601
7602   return true;
7603 }
7604
7605 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7606 ///
7607 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7608 /// It makes no assumptions about whether this is the *best* lowering, it simply
7609 /// uses it.
7610 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7611                                             ArrayRef<int> Mask, SDValue V1,
7612                                             SDValue V2, SelectionDAG &DAG) {
7613   SDValue LowV = V1, HighV = V2;
7614   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7615
7616   int NumV2Elements =
7617       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7618
7619   if (NumV2Elements == 1) {
7620     int V2Index =
7621         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7622         Mask.begin();
7623
7624     // Compute the index adjacent to V2Index and in the same half by toggling
7625     // the low bit.
7626     int V2AdjIndex = V2Index ^ 1;
7627
7628     if (Mask[V2AdjIndex] == -1) {
7629       // Handles all the cases where we have a single V2 element and an undef.
7630       // This will only ever happen in the high lanes because we commute the
7631       // vector otherwise.
7632       if (V2Index < 2)
7633         std::swap(LowV, HighV);
7634       NewMask[V2Index] -= 4;
7635     } else {
7636       // Handle the case where the V2 element ends up adjacent to a V1 element.
7637       // To make this work, blend them together as the first step.
7638       int V1Index = V2AdjIndex;
7639       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7640       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7641                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7642
7643       // Now proceed to reconstruct the final blend as we have the necessary
7644       // high or low half formed.
7645       if (V2Index < 2) {
7646         LowV = V2;
7647         HighV = V1;
7648       } else {
7649         HighV = V2;
7650       }
7651       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7652       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7653     }
7654   } else if (NumV2Elements == 2) {
7655     if (Mask[0] < 4 && Mask[1] < 4) {
7656       // Handle the easy case where we have V1 in the low lanes and V2 in the
7657       // high lanes.
7658       NewMask[2] -= 4;
7659       NewMask[3] -= 4;
7660     } else if (Mask[2] < 4 && Mask[3] < 4) {
7661       // We also handle the reversed case because this utility may get called
7662       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7663       // arrange things in the right direction.
7664       NewMask[0] -= 4;
7665       NewMask[1] -= 4;
7666       HighV = V1;
7667       LowV = V2;
7668     } else {
7669       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7670       // trying to place elements directly, just blend them and set up the final
7671       // shuffle to place them.
7672
7673       // The first two blend mask elements are for V1, the second two are for
7674       // V2.
7675       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7676                           Mask[2] < 4 ? Mask[2] : Mask[3],
7677                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7678                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7679       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7680                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7681
7682       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7683       // a blend.
7684       LowV = HighV = V1;
7685       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7686       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7687       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7688       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7689     }
7690   }
7691   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7692                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7693 }
7694
7695 /// \brief Lower 4-lane 32-bit floating point shuffles.
7696 ///
7697 /// Uses instructions exclusively from the floating point unit to minimize
7698 /// domain crossing penalties, as these are sufficient to implement all v4f32
7699 /// shuffles.
7700 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7701                                        const X86Subtarget *Subtarget,
7702                                        SelectionDAG &DAG) {
7703   SDLoc DL(Op);
7704   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7705   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7706   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7707   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7708   ArrayRef<int> Mask = SVOp->getMask();
7709   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7710
7711   int NumV2Elements =
7712       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7713
7714   if (NumV2Elements == 0) {
7715     // Check for being able to broadcast a single element.
7716     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7717                                                           Mask, Subtarget, DAG))
7718       return Broadcast;
7719
7720     // Use even/odd duplicate instructions for masks that match their pattern.
7721     if (Subtarget->hasSSE3()) {
7722       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7723         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7724       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7725         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7726     }
7727
7728     if (Subtarget->hasAVX()) {
7729       // If we have AVX, we can use VPERMILPS which will allow folding a load
7730       // into the shuffle.
7731       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7732                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7733     }
7734
7735     // Otherwise, use a straight shuffle of a single input vector. We pass the
7736     // input vector to both operands to simulate this with a SHUFPS.
7737     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7738                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7739   }
7740
7741   // There are special ways we can lower some single-element blends. However, we
7742   // have custom ways we can lower more complex single-element blends below that
7743   // we defer to if both this and BLENDPS fail to match, so restrict this to
7744   // when the V2 input is targeting element 0 of the mask -- that is the fast
7745   // case here.
7746   if (NumV2Elements == 1 && Mask[0] >= 4)
7747     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7748                                                          Mask, Subtarget, DAG))
7749       return V;
7750
7751   if (Subtarget->hasSSE41()) {
7752     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7753                                                   Subtarget, DAG))
7754       return Blend;
7755
7756     // Use INSERTPS if we can complete the shuffle efficiently.
7757     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7758       return V;
7759
7760     if (!isSingleSHUFPSMask(Mask))
7761       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7762               DL, MVT::v4f32, V1, V2, Mask, DAG))
7763         return BlendPerm;
7764   }
7765
7766   // Use dedicated unpack instructions for masks that match their pattern.
7767   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7768     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7769   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7770     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7771   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7772     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7773   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7774     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7775
7776   // Otherwise fall back to a SHUFPS lowering strategy.
7777   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7778 }
7779
7780 /// \brief Lower 4-lane i32 vector shuffles.
7781 ///
7782 /// We try to handle these with integer-domain shuffles where we can, but for
7783 /// blends we use the floating point domain blend instructions.
7784 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7785                                        const X86Subtarget *Subtarget,
7786                                        SelectionDAG &DAG) {
7787   SDLoc DL(Op);
7788   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7789   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7790   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7791   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7792   ArrayRef<int> Mask = SVOp->getMask();
7793   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7794
7795   // Whenever we can lower this as a zext, that instruction is strictly faster
7796   // than any alternative. It also allows us to fold memory operands into the
7797   // shuffle in many cases.
7798   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7799                                                          Mask, Subtarget, DAG))
7800     return ZExt;
7801
7802   int NumV2Elements =
7803       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7804
7805   if (NumV2Elements == 0) {
7806     // Check for being able to broadcast a single element.
7807     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7808                                                           Mask, Subtarget, DAG))
7809       return Broadcast;
7810
7811     // Straight shuffle of a single input vector. For everything from SSE2
7812     // onward this has a single fast instruction with no scary immediates.
7813     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7814     // but we aren't actually going to use the UNPCK instruction because doing
7815     // so prevents folding a load into this instruction or making a copy.
7816     const int UnpackLoMask[] = {0, 0, 1, 1};
7817     const int UnpackHiMask[] = {2, 2, 3, 3};
7818     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7819       Mask = UnpackLoMask;
7820     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7821       Mask = UnpackHiMask;
7822
7823     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7824                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7825   }
7826
7827   // Try to use shift instructions.
7828   if (SDValue Shift =
7829           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7830     return Shift;
7831
7832   // There are special ways we can lower some single-element blends.
7833   if (NumV2Elements == 1)
7834     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7835                                                          Mask, Subtarget, DAG))
7836       return V;
7837
7838   // We have different paths for blend lowering, but they all must use the
7839   // *exact* same predicate.
7840   bool IsBlendSupported = Subtarget->hasSSE41();
7841   if (IsBlendSupported)
7842     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7843                                                   Subtarget, DAG))
7844       return Blend;
7845
7846   if (SDValue Masked =
7847           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7848     return Masked;
7849
7850   // Use dedicated unpack instructions for masks that match their pattern.
7851   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7852     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7853   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7854     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7855   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7856     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7857   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7858     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7859
7860   // Try to use byte rotation instructions.
7861   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7862   if (Subtarget->hasSSSE3())
7863     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7864             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7865       return Rotate;
7866
7867   // If we have direct support for blends, we should lower by decomposing into
7868   // a permute. That will be faster than the domain cross.
7869   if (IsBlendSupported)
7870     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7871                                                       Mask, DAG);
7872
7873   // Try to lower by permuting the inputs into an unpack instruction.
7874   if (SDValue Unpack =
7875           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7876     return Unpack;
7877
7878   // We implement this with SHUFPS because it can blend from two vectors.
7879   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7880   // up the inputs, bypassing domain shift penalties that we would encur if we
7881   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7882   // relevant.
7883   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7884                      DAG.getVectorShuffle(
7885                          MVT::v4f32, DL,
7886                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7887                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7888 }
7889
7890 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7891 /// shuffle lowering, and the most complex part.
7892 ///
7893 /// The lowering strategy is to try to form pairs of input lanes which are
7894 /// targeted at the same half of the final vector, and then use a dword shuffle
7895 /// to place them onto the right half, and finally unpack the paired lanes into
7896 /// their final position.
7897 ///
7898 /// The exact breakdown of how to form these dword pairs and align them on the
7899 /// correct sides is really tricky. See the comments within the function for
7900 /// more of the details.
7901 ///
7902 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7903 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7904 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7905 /// vector, form the analogous 128-bit 8-element Mask.
7906 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7907     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7908     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7909   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7910   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7911
7912   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7913   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7914   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7915
7916   SmallVector<int, 4> LoInputs;
7917   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7918                [](int M) { return M >= 0; });
7919   std::sort(LoInputs.begin(), LoInputs.end());
7920   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7921   SmallVector<int, 4> HiInputs;
7922   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7923                [](int M) { return M >= 0; });
7924   std::sort(HiInputs.begin(), HiInputs.end());
7925   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7926   int NumLToL =
7927       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7928   int NumHToL = LoInputs.size() - NumLToL;
7929   int NumLToH =
7930       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7931   int NumHToH = HiInputs.size() - NumLToH;
7932   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7933   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7934   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7935   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7936
7937   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7938   // such inputs we can swap two of the dwords across the half mark and end up
7939   // with <=2 inputs to each half in each half. Once there, we can fall through
7940   // to the generic code below. For example:
7941   //
7942   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7943   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7944   //
7945   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7946   // and an existing 2-into-2 on the other half. In this case we may have to
7947   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7948   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7949   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7950   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7951   // half than the one we target for fixing) will be fixed when we re-enter this
7952   // path. We will also combine away any sequence of PSHUFD instructions that
7953   // result into a single instruction. Here is an example of the tricky case:
7954   //
7955   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7956   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7957   //
7958   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7959   //
7960   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7961   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7962   //
7963   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7964   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7965   //
7966   // The result is fine to be handled by the generic logic.
7967   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7968                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7969                           int AOffset, int BOffset) {
7970     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7971            "Must call this with A having 3 or 1 inputs from the A half.");
7972     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7973            "Must call this with B having 1 or 3 inputs from the B half.");
7974     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7975            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7976
7977     // Compute the index of dword with only one word among the three inputs in
7978     // a half by taking the sum of the half with three inputs and subtracting
7979     // the sum of the actual three inputs. The difference is the remaining
7980     // slot.
7981     int ADWord, BDWord;
7982     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7983     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7984     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7985     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7986     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7987     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7988     int TripleNonInputIdx =
7989         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7990     TripleDWord = TripleNonInputIdx / 2;
7991
7992     // We use xor with one to compute the adjacent DWord to whichever one the
7993     // OneInput is in.
7994     OneInputDWord = (OneInput / 2) ^ 1;
7995
7996     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7997     // and BToA inputs. If there is also such a problem with the BToB and AToB
7998     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7999     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8000     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8001     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8002       // Compute how many inputs will be flipped by swapping these DWords. We
8003       // need
8004       // to balance this to ensure we don't form a 3-1 shuffle in the other
8005       // half.
8006       int NumFlippedAToBInputs =
8007           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8008           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8009       int NumFlippedBToBInputs =
8010           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8011           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8012       if ((NumFlippedAToBInputs == 1 &&
8013            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8014           (NumFlippedBToBInputs == 1 &&
8015            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8016         // We choose whether to fix the A half or B half based on whether that
8017         // half has zero flipped inputs. At zero, we may not be able to fix it
8018         // with that half. We also bias towards fixing the B half because that
8019         // will more commonly be the high half, and we have to bias one way.
8020         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8021                                                        ArrayRef<int> Inputs) {
8022           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8023           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8024                                          PinnedIdx ^ 1) != Inputs.end();
8025           // Determine whether the free index is in the flipped dword or the
8026           // unflipped dword based on where the pinned index is. We use this bit
8027           // in an xor to conditionally select the adjacent dword.
8028           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8029           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8030                                              FixFreeIdx) != Inputs.end();
8031           if (IsFixIdxInput == IsFixFreeIdxInput)
8032             FixFreeIdx += 1;
8033           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8034                                         FixFreeIdx) != Inputs.end();
8035           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8036                  "We need to be changing the number of flipped inputs!");
8037           int PSHUFHalfMask[] = {0, 1, 2, 3};
8038           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8039           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8040                           MVT::v8i16, V,
8041                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8042
8043           for (int &M : Mask)
8044             if (M != -1 && M == FixIdx)
8045               M = FixFreeIdx;
8046             else if (M != -1 && M == FixFreeIdx)
8047               M = FixIdx;
8048         };
8049         if (NumFlippedBToBInputs != 0) {
8050           int BPinnedIdx =
8051               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8052           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8053         } else {
8054           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8055           int APinnedIdx =
8056               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8057           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8058         }
8059       }
8060     }
8061
8062     int PSHUFDMask[] = {0, 1, 2, 3};
8063     PSHUFDMask[ADWord] = BDWord;
8064     PSHUFDMask[BDWord] = ADWord;
8065     V = DAG.getNode(ISD::BITCAST, DL, VT,
8066                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8067                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8068                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8069                                                            DAG)));
8070
8071     // Adjust the mask to match the new locations of A and B.
8072     for (int &M : Mask)
8073       if (M != -1 && M/2 == ADWord)
8074         M = 2 * BDWord + M % 2;
8075       else if (M != -1 && M/2 == BDWord)
8076         M = 2 * ADWord + M % 2;
8077
8078     // Recurse back into this routine to re-compute state now that this isn't
8079     // a 3 and 1 problem.
8080     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8081                                                      DAG);
8082   };
8083   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8084     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8085   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8086     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8087
8088   // At this point there are at most two inputs to the low and high halves from
8089   // each half. That means the inputs can always be grouped into dwords and
8090   // those dwords can then be moved to the correct half with a dword shuffle.
8091   // We use at most one low and one high word shuffle to collect these paired
8092   // inputs into dwords, and finally a dword shuffle to place them.
8093   int PSHUFLMask[4] = {-1, -1, -1, -1};
8094   int PSHUFHMask[4] = {-1, -1, -1, -1};
8095   int PSHUFDMask[4] = {-1, -1, -1, -1};
8096
8097   // First fix the masks for all the inputs that are staying in their
8098   // original halves. This will then dictate the targets of the cross-half
8099   // shuffles.
8100   auto fixInPlaceInputs =
8101       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8102                     MutableArrayRef<int> SourceHalfMask,
8103                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8104     if (InPlaceInputs.empty())
8105       return;
8106     if (InPlaceInputs.size() == 1) {
8107       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8108           InPlaceInputs[0] - HalfOffset;
8109       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8110       return;
8111     }
8112     if (IncomingInputs.empty()) {
8113       // Just fix all of the in place inputs.
8114       for (int Input : InPlaceInputs) {
8115         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8116         PSHUFDMask[Input / 2] = Input / 2;
8117       }
8118       return;
8119     }
8120
8121     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8122     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8123         InPlaceInputs[0] - HalfOffset;
8124     // Put the second input next to the first so that they are packed into
8125     // a dword. We find the adjacent index by toggling the low bit.
8126     int AdjIndex = InPlaceInputs[0] ^ 1;
8127     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8128     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8129     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8130   };
8131   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8132   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8133
8134   // Now gather the cross-half inputs and place them into a free dword of
8135   // their target half.
8136   // FIXME: This operation could almost certainly be simplified dramatically to
8137   // look more like the 3-1 fixing operation.
8138   auto moveInputsToRightHalf = [&PSHUFDMask](
8139       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8140       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8141       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8142       int DestOffset) {
8143     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8144       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8145     };
8146     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8147                                                int Word) {
8148       int LowWord = Word & ~1;
8149       int HighWord = Word | 1;
8150       return isWordClobbered(SourceHalfMask, LowWord) ||
8151              isWordClobbered(SourceHalfMask, HighWord);
8152     };
8153
8154     if (IncomingInputs.empty())
8155       return;
8156
8157     if (ExistingInputs.empty()) {
8158       // Map any dwords with inputs from them into the right half.
8159       for (int Input : IncomingInputs) {
8160         // If the source half mask maps over the inputs, turn those into
8161         // swaps and use the swapped lane.
8162         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8163           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8164             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8165                 Input - SourceOffset;
8166             // We have to swap the uses in our half mask in one sweep.
8167             for (int &M : HalfMask)
8168               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8169                 M = Input;
8170               else if (M == Input)
8171                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8172           } else {
8173             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8174                        Input - SourceOffset &&
8175                    "Previous placement doesn't match!");
8176           }
8177           // Note that this correctly re-maps both when we do a swap and when
8178           // we observe the other side of the swap above. We rely on that to
8179           // avoid swapping the members of the input list directly.
8180           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8181         }
8182
8183         // Map the input's dword into the correct half.
8184         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8185           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8186         else
8187           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8188                      Input / 2 &&
8189                  "Previous placement doesn't match!");
8190       }
8191
8192       // And just directly shift any other-half mask elements to be same-half
8193       // as we will have mirrored the dword containing the element into the
8194       // same position within that half.
8195       for (int &M : HalfMask)
8196         if (M >= SourceOffset && M < SourceOffset + 4) {
8197           M = M - SourceOffset + DestOffset;
8198           assert(M >= 0 && "This should never wrap below zero!");
8199         }
8200       return;
8201     }
8202
8203     // Ensure we have the input in a viable dword of its current half. This
8204     // is particularly tricky because the original position may be clobbered
8205     // by inputs being moved and *staying* in that half.
8206     if (IncomingInputs.size() == 1) {
8207       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8208         int InputFixed = std::find(std::begin(SourceHalfMask),
8209                                    std::end(SourceHalfMask), -1) -
8210                          std::begin(SourceHalfMask) + SourceOffset;
8211         SourceHalfMask[InputFixed - SourceOffset] =
8212             IncomingInputs[0] - SourceOffset;
8213         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8214                      InputFixed);
8215         IncomingInputs[0] = InputFixed;
8216       }
8217     } else if (IncomingInputs.size() == 2) {
8218       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8219           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8220         // We have two non-adjacent or clobbered inputs we need to extract from
8221         // the source half. To do this, we need to map them into some adjacent
8222         // dword slot in the source mask.
8223         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8224                               IncomingInputs[1] - SourceOffset};
8225
8226         // If there is a free slot in the source half mask adjacent to one of
8227         // the inputs, place the other input in it. We use (Index XOR 1) to
8228         // compute an adjacent index.
8229         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8230             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8231           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8232           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8233           InputsFixed[1] = InputsFixed[0] ^ 1;
8234         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8235                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8236           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8237           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8238           InputsFixed[0] = InputsFixed[1] ^ 1;
8239         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8240                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8241           // The two inputs are in the same DWord but it is clobbered and the
8242           // adjacent DWord isn't used at all. Move both inputs to the free
8243           // slot.
8244           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8245           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8246           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8247           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8248         } else {
8249           // The only way we hit this point is if there is no clobbering
8250           // (because there are no off-half inputs to this half) and there is no
8251           // free slot adjacent to one of the inputs. In this case, we have to
8252           // swap an input with a non-input.
8253           for (int i = 0; i < 4; ++i)
8254             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8255                    "We can't handle any clobbers here!");
8256           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8257                  "Cannot have adjacent inputs here!");
8258
8259           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8260           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8261
8262           // We also have to update the final source mask in this case because
8263           // it may need to undo the above swap.
8264           for (int &M : FinalSourceHalfMask)
8265             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8266               M = InputsFixed[1] + SourceOffset;
8267             else if (M == InputsFixed[1] + SourceOffset)
8268               M = (InputsFixed[0] ^ 1) + SourceOffset;
8269
8270           InputsFixed[1] = InputsFixed[0] ^ 1;
8271         }
8272
8273         // Point everything at the fixed inputs.
8274         for (int &M : HalfMask)
8275           if (M == IncomingInputs[0])
8276             M = InputsFixed[0] + SourceOffset;
8277           else if (M == IncomingInputs[1])
8278             M = InputsFixed[1] + SourceOffset;
8279
8280         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8281         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8282       }
8283     } else {
8284       llvm_unreachable("Unhandled input size!");
8285     }
8286
8287     // Now hoist the DWord down to the right half.
8288     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8289     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8290     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8291     for (int &M : HalfMask)
8292       for (int Input : IncomingInputs)
8293         if (M == Input)
8294           M = FreeDWord * 2 + Input % 2;
8295   };
8296   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8297                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8298   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8299                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8300
8301   // Now enact all the shuffles we've computed to move the inputs into their
8302   // target half.
8303   if (!isNoopShuffleMask(PSHUFLMask))
8304     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8305                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8306   if (!isNoopShuffleMask(PSHUFHMask))
8307     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8308                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8309   if (!isNoopShuffleMask(PSHUFDMask))
8310     V = DAG.getNode(ISD::BITCAST, DL, VT,
8311                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8312                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8313                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8314                                                            DAG)));
8315
8316   // At this point, each half should contain all its inputs, and we can then
8317   // just shuffle them into their final position.
8318   assert(std::count_if(LoMask.begin(), LoMask.end(),
8319                        [](int M) { return M >= 4; }) == 0 &&
8320          "Failed to lift all the high half inputs to the low mask!");
8321   assert(std::count_if(HiMask.begin(), HiMask.end(),
8322                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8323          "Failed to lift all the low half inputs to the high mask!");
8324
8325   // Do a half shuffle for the low mask.
8326   if (!isNoopShuffleMask(LoMask))
8327     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8328                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8329
8330   // Do a half shuffle with the high mask after shifting its values down.
8331   for (int &M : HiMask)
8332     if (M >= 0)
8333       M -= 4;
8334   if (!isNoopShuffleMask(HiMask))
8335     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8336                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8337
8338   return V;
8339 }
8340
8341 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8342 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8343                                           SDValue V2, ArrayRef<int> Mask,
8344                                           SelectionDAG &DAG, bool &V1InUse,
8345                                           bool &V2InUse) {
8346   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8347   SDValue V1Mask[16];
8348   SDValue V2Mask[16];
8349   V1InUse = false;
8350   V2InUse = false;
8351
8352   int Size = Mask.size();
8353   int Scale = 16 / Size;
8354   for (int i = 0; i < 16; ++i) {
8355     if (Mask[i / Scale] == -1) {
8356       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8357     } else {
8358       const int ZeroMask = 0x80;
8359       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8360                                           : ZeroMask;
8361       int V2Idx = Mask[i / Scale] < Size
8362                       ? ZeroMask
8363                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8364       if (Zeroable[i / Scale])
8365         V1Idx = V2Idx = ZeroMask;
8366       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8367       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8368       V1InUse |= (ZeroMask != V1Idx);
8369       V2InUse |= (ZeroMask != V2Idx);
8370     }
8371   }
8372
8373   if (V1InUse)
8374     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8375                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8376                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8377   if (V2InUse)
8378     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8379                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8380                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8381
8382   // If we need shuffled inputs from both, blend the two.
8383   SDValue V;
8384   if (V1InUse && V2InUse)
8385     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8386   else
8387     V = V1InUse ? V1 : V2;
8388
8389   // Cast the result back to the correct type.
8390   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8391 }
8392
8393 /// \brief Generic lowering of 8-lane i16 shuffles.
8394 ///
8395 /// This handles both single-input shuffles and combined shuffle/blends with
8396 /// two inputs. The single input shuffles are immediately delegated to
8397 /// a dedicated lowering routine.
8398 ///
8399 /// The blends are lowered in one of three fundamental ways. If there are few
8400 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8401 /// of the input is significantly cheaper when lowered as an interleaving of
8402 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8403 /// halves of the inputs separately (making them have relatively few inputs)
8404 /// and then concatenate them.
8405 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8406                                        const X86Subtarget *Subtarget,
8407                                        SelectionDAG &DAG) {
8408   SDLoc DL(Op);
8409   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8410   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8411   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8412   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8413   ArrayRef<int> OrigMask = SVOp->getMask();
8414   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8415                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8416   MutableArrayRef<int> Mask(MaskStorage);
8417
8418   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8419
8420   // Whenever we can lower this as a zext, that instruction is strictly faster
8421   // than any alternative.
8422   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8423           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8424     return ZExt;
8425
8426   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8427   (void)isV1;
8428   auto isV2 = [](int M) { return M >= 8; };
8429
8430   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8431
8432   if (NumV2Inputs == 0) {
8433     // Check for being able to broadcast a single element.
8434     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8435                                                           Mask, Subtarget, DAG))
8436       return Broadcast;
8437
8438     // Try to use shift instructions.
8439     if (SDValue Shift =
8440             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8441       return Shift;
8442
8443     // Use dedicated unpack instructions for masks that match their pattern.
8444     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8445       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8446     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8447       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8448
8449     // Try to use byte rotation instructions.
8450     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8451                                                         Mask, Subtarget, DAG))
8452       return Rotate;
8453
8454     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8455                                                      Subtarget, DAG);
8456   }
8457
8458   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8459          "All single-input shuffles should be canonicalized to be V1-input "
8460          "shuffles.");
8461
8462   // Try to use shift instructions.
8463   if (SDValue Shift =
8464           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8465     return Shift;
8466
8467   // There are special ways we can lower some single-element blends.
8468   if (NumV2Inputs == 1)
8469     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8470                                                          Mask, Subtarget, DAG))
8471       return V;
8472
8473   // We have different paths for blend lowering, but they all must use the
8474   // *exact* same predicate.
8475   bool IsBlendSupported = Subtarget->hasSSE41();
8476   if (IsBlendSupported)
8477     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8478                                                   Subtarget, DAG))
8479       return Blend;
8480
8481   if (SDValue Masked =
8482           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8483     return Masked;
8484
8485   // Use dedicated unpack instructions for masks that match their pattern.
8486   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8487     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8488   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8489     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8490
8491   // Try to use byte rotation instructions.
8492   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8493           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8494     return Rotate;
8495
8496   if (SDValue BitBlend =
8497           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8498     return BitBlend;
8499
8500   if (SDValue Unpack =
8501           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8502     return Unpack;
8503
8504   // If we can't directly blend but can use PSHUFB, that will be better as it
8505   // can both shuffle and set up the inefficient blend.
8506   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8507     bool V1InUse, V2InUse;
8508     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8509                                       V1InUse, V2InUse);
8510   }
8511
8512   // We can always bit-blend if we have to so the fallback strategy is to
8513   // decompose into single-input permutes and blends.
8514   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8515                                                       Mask, DAG);
8516 }
8517
8518 /// \brief Check whether a compaction lowering can be done by dropping even
8519 /// elements and compute how many times even elements must be dropped.
8520 ///
8521 /// This handles shuffles which take every Nth element where N is a power of
8522 /// two. Example shuffle masks:
8523 ///
8524 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8525 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8526 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8527 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8528 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8529 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8530 ///
8531 /// Any of these lanes can of course be undef.
8532 ///
8533 /// This routine only supports N <= 3.
8534 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8535 /// for larger N.
8536 ///
8537 /// \returns N above, or the number of times even elements must be dropped if
8538 /// there is such a number. Otherwise returns zero.
8539 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8540   // Figure out whether we're looping over two inputs or just one.
8541   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8542
8543   // The modulus for the shuffle vector entries is based on whether this is
8544   // a single input or not.
8545   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8546   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8547          "We should only be called with masks with a power-of-2 size!");
8548
8549   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8550
8551   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8552   // and 2^3 simultaneously. This is because we may have ambiguity with
8553   // partially undef inputs.
8554   bool ViableForN[3] = {true, true, true};
8555
8556   for (int i = 0, e = Mask.size(); i < e; ++i) {
8557     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8558     // want.
8559     if (Mask[i] == -1)
8560       continue;
8561
8562     bool IsAnyViable = false;
8563     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8564       if (ViableForN[j]) {
8565         uint64_t N = j + 1;
8566
8567         // The shuffle mask must be equal to (i * 2^N) % M.
8568         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8569           IsAnyViable = true;
8570         else
8571           ViableForN[j] = false;
8572       }
8573     // Early exit if we exhaust the possible powers of two.
8574     if (!IsAnyViable)
8575       break;
8576   }
8577
8578   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8579     if (ViableForN[j])
8580       return j + 1;
8581
8582   // Return 0 as there is no viable power of two.
8583   return 0;
8584 }
8585
8586 /// \brief Generic lowering of v16i8 shuffles.
8587 ///
8588 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8589 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8590 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8591 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8592 /// back together.
8593 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8594                                        const X86Subtarget *Subtarget,
8595                                        SelectionDAG &DAG) {
8596   SDLoc DL(Op);
8597   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8598   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8599   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8600   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8601   ArrayRef<int> Mask = SVOp->getMask();
8602   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8603
8604   // Try to use shift instructions.
8605   if (SDValue Shift =
8606           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8607     return Shift;
8608
8609   // Try to use byte rotation instructions.
8610   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8611           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8612     return Rotate;
8613
8614   // Try to use a zext lowering.
8615   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8616           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8617     return ZExt;
8618
8619   int NumV2Elements =
8620       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8621
8622   // For single-input shuffles, there are some nicer lowering tricks we can use.
8623   if (NumV2Elements == 0) {
8624     // Check for being able to broadcast a single element.
8625     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8626                                                           Mask, Subtarget, DAG))
8627       return Broadcast;
8628
8629     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8630     // Notably, this handles splat and partial-splat shuffles more efficiently.
8631     // However, it only makes sense if the pre-duplication shuffle simplifies
8632     // things significantly. Currently, this means we need to be able to
8633     // express the pre-duplication shuffle as an i16 shuffle.
8634     //
8635     // FIXME: We should check for other patterns which can be widened into an
8636     // i16 shuffle as well.
8637     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8638       for (int i = 0; i < 16; i += 2)
8639         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8640           return false;
8641
8642       return true;
8643     };
8644     auto tryToWidenViaDuplication = [&]() -> SDValue {
8645       if (!canWidenViaDuplication(Mask))
8646         return SDValue();
8647       SmallVector<int, 4> LoInputs;
8648       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8649                    [](int M) { return M >= 0 && M < 8; });
8650       std::sort(LoInputs.begin(), LoInputs.end());
8651       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8652                      LoInputs.end());
8653       SmallVector<int, 4> HiInputs;
8654       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8655                    [](int M) { return M >= 8; });
8656       std::sort(HiInputs.begin(), HiInputs.end());
8657       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8658                      HiInputs.end());
8659
8660       bool TargetLo = LoInputs.size() >= HiInputs.size();
8661       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8662       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8663
8664       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8665       SmallDenseMap<int, int, 8> LaneMap;
8666       for (int I : InPlaceInputs) {
8667         PreDupI16Shuffle[I/2] = I/2;
8668         LaneMap[I] = I;
8669       }
8670       int j = TargetLo ? 0 : 4, je = j + 4;
8671       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8672         // Check if j is already a shuffle of this input. This happens when
8673         // there are two adjacent bytes after we move the low one.
8674         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8675           // If we haven't yet mapped the input, search for a slot into which
8676           // we can map it.
8677           while (j < je && PreDupI16Shuffle[j] != -1)
8678             ++j;
8679
8680           if (j == je)
8681             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8682             return SDValue();
8683
8684           // Map this input with the i16 shuffle.
8685           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8686         }
8687
8688         // Update the lane map based on the mapping we ended up with.
8689         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8690       }
8691       V1 = DAG.getNode(
8692           ISD::BITCAST, DL, MVT::v16i8,
8693           DAG.getVectorShuffle(MVT::v8i16, DL,
8694                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8695                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8696
8697       // Unpack the bytes to form the i16s that will be shuffled into place.
8698       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8699                        MVT::v16i8, V1, V1);
8700
8701       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8702       for (int i = 0; i < 16; ++i)
8703         if (Mask[i] != -1) {
8704           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8705           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8706           if (PostDupI16Shuffle[i / 2] == -1)
8707             PostDupI16Shuffle[i / 2] = MappedMask;
8708           else
8709             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8710                    "Conflicting entrties in the original shuffle!");
8711         }
8712       return DAG.getNode(
8713           ISD::BITCAST, DL, MVT::v16i8,
8714           DAG.getVectorShuffle(MVT::v8i16, DL,
8715                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8716                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8717     };
8718     if (SDValue V = tryToWidenViaDuplication())
8719       return V;
8720   }
8721
8722   // Use dedicated unpack instructions for masks that match their pattern.
8723   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8724                                          0, 16, 1, 17, 2, 18, 3, 19,
8725                                          // High half.
8726                                          4, 20, 5, 21, 6, 22, 7, 23}))
8727     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8728   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8729                                          8, 24, 9, 25, 10, 26, 11, 27,
8730                                          // High half.
8731                                          12, 28, 13, 29, 14, 30, 15, 31}))
8732     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8733
8734   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8735   // with PSHUFB. It is important to do this before we attempt to generate any
8736   // blends but after all of the single-input lowerings. If the single input
8737   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8738   // want to preserve that and we can DAG combine any longer sequences into
8739   // a PSHUFB in the end. But once we start blending from multiple inputs,
8740   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8741   // and there are *very* few patterns that would actually be faster than the
8742   // PSHUFB approach because of its ability to zero lanes.
8743   //
8744   // FIXME: The only exceptions to the above are blends which are exact
8745   // interleavings with direct instructions supporting them. We currently don't
8746   // handle those well here.
8747   if (Subtarget->hasSSSE3()) {
8748     bool V1InUse = false;
8749     bool V2InUse = false;
8750
8751     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8752                                                 DAG, V1InUse, V2InUse);
8753
8754     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8755     // do so. This avoids using them to handle blends-with-zero which is
8756     // important as a single pshufb is significantly faster for that.
8757     if (V1InUse && V2InUse) {
8758       if (Subtarget->hasSSE41())
8759         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8760                                                       Mask, Subtarget, DAG))
8761           return Blend;
8762
8763       // We can use an unpack to do the blending rather than an or in some
8764       // cases. Even though the or may be (very minorly) more efficient, we
8765       // preference this lowering because there are common cases where part of
8766       // the complexity of the shuffles goes away when we do the final blend as
8767       // an unpack.
8768       // FIXME: It might be worth trying to detect if the unpack-feeding
8769       // shuffles will both be pshufb, in which case we shouldn't bother with
8770       // this.
8771       if (SDValue Unpack =
8772               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8773         return Unpack;
8774     }
8775
8776     return PSHUFB;
8777   }
8778
8779   // There are special ways we can lower some single-element blends.
8780   if (NumV2Elements == 1)
8781     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8782                                                          Mask, Subtarget, DAG))
8783       return V;
8784
8785   if (SDValue BitBlend =
8786           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8787     return BitBlend;
8788
8789   // Check whether a compaction lowering can be done. This handles shuffles
8790   // which take every Nth element for some even N. See the helper function for
8791   // details.
8792   //
8793   // We special case these as they can be particularly efficiently handled with
8794   // the PACKUSB instruction on x86 and they show up in common patterns of
8795   // rearranging bytes to truncate wide elements.
8796   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8797     // NumEvenDrops is the power of two stride of the elements. Another way of
8798     // thinking about it is that we need to drop the even elements this many
8799     // times to get the original input.
8800     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8801
8802     // First we need to zero all the dropped bytes.
8803     assert(NumEvenDrops <= 3 &&
8804            "No support for dropping even elements more than 3 times.");
8805     // We use the mask type to pick which bytes are preserved based on how many
8806     // elements are dropped.
8807     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8808     SDValue ByteClearMask =
8809         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8810                     DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8811     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8812     if (!IsSingleInput)
8813       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8814
8815     // Now pack things back together.
8816     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8817     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8818     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8819     for (int i = 1; i < NumEvenDrops; ++i) {
8820       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8821       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8822     }
8823
8824     return Result;
8825   }
8826
8827   // Handle multi-input cases by blending single-input shuffles.
8828   if (NumV2Elements > 0)
8829     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8830                                                       Mask, DAG);
8831
8832   // The fallback path for single-input shuffles widens this into two v8i16
8833   // vectors with unpacks, shuffles those, and then pulls them back together
8834   // with a pack.
8835   SDValue V = V1;
8836
8837   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8838   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8839   for (int i = 0; i < 16; ++i)
8840     if (Mask[i] >= 0)
8841       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8842
8843   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8844
8845   SDValue VLoHalf, VHiHalf;
8846   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8847   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8848   // i16s.
8849   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8850                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8851       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8852                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8853     // Use a mask to drop the high bytes.
8854     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8855     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8856                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8857
8858     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8859     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8860
8861     // Squash the masks to point directly into VLoHalf.
8862     for (int &M : LoBlendMask)
8863       if (M >= 0)
8864         M /= 2;
8865     for (int &M : HiBlendMask)
8866       if (M >= 0)
8867         M /= 2;
8868   } else {
8869     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8870     // VHiHalf so that we can blend them as i16s.
8871     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8872                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8873     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8874                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8875   }
8876
8877   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8878   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8879
8880   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8881 }
8882
8883 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8884 ///
8885 /// This routine breaks down the specific type of 128-bit shuffle and
8886 /// dispatches to the lowering routines accordingly.
8887 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8888                                         MVT VT, const X86Subtarget *Subtarget,
8889                                         SelectionDAG &DAG) {
8890   switch (VT.SimpleTy) {
8891   case MVT::v2i64:
8892     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8893   case MVT::v2f64:
8894     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8895   case MVT::v4i32:
8896     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8897   case MVT::v4f32:
8898     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8899   case MVT::v8i16:
8900     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8901   case MVT::v16i8:
8902     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8903
8904   default:
8905     llvm_unreachable("Unimplemented!");
8906   }
8907 }
8908
8909 /// \brief Helper function to test whether a shuffle mask could be
8910 /// simplified by widening the elements being shuffled.
8911 ///
8912 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8913 /// leaves it in an unspecified state.
8914 ///
8915 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8916 /// shuffle masks. The latter have the special property of a '-2' representing
8917 /// a zero-ed lane of a vector.
8918 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8919                                     SmallVectorImpl<int> &WidenedMask) {
8920   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8921     // If both elements are undef, its trivial.
8922     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8923       WidenedMask.push_back(SM_SentinelUndef);
8924       continue;
8925     }
8926
8927     // Check for an undef mask and a mask value properly aligned to fit with
8928     // a pair of values. If we find such a case, use the non-undef mask's value.
8929     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8930       WidenedMask.push_back(Mask[i + 1] / 2);
8931       continue;
8932     }
8933     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8934       WidenedMask.push_back(Mask[i] / 2);
8935       continue;
8936     }
8937
8938     // When zeroing, we need to spread the zeroing across both lanes to widen.
8939     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8940       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8941           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8942         WidenedMask.push_back(SM_SentinelZero);
8943         continue;
8944       }
8945       return false;
8946     }
8947
8948     // Finally check if the two mask values are adjacent and aligned with
8949     // a pair.
8950     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8951       WidenedMask.push_back(Mask[i] / 2);
8952       continue;
8953     }
8954
8955     // Otherwise we can't safely widen the elements used in this shuffle.
8956     return false;
8957   }
8958   assert(WidenedMask.size() == Mask.size() / 2 &&
8959          "Incorrect size of mask after widening the elements!");
8960
8961   return true;
8962 }
8963
8964 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8965 ///
8966 /// This routine just extracts two subvectors, shuffles them independently, and
8967 /// then concatenates them back together. This should work effectively with all
8968 /// AVX vector shuffle types.
8969 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8970                                           SDValue V2, ArrayRef<int> Mask,
8971                                           SelectionDAG &DAG) {
8972   assert(VT.getSizeInBits() >= 256 &&
8973          "Only for 256-bit or wider vector shuffles!");
8974   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8975   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8976
8977   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8978   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8979
8980   int NumElements = VT.getVectorNumElements();
8981   int SplitNumElements = NumElements / 2;
8982   MVT ScalarVT = VT.getScalarType();
8983   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8984
8985   // Rather than splitting build-vectors, just build two narrower build
8986   // vectors. This helps shuffling with splats and zeros.
8987   auto SplitVector = [&](SDValue V) {
8988     while (V.getOpcode() == ISD::BITCAST)
8989       V = V->getOperand(0);
8990
8991     MVT OrigVT = V.getSimpleValueType();
8992     int OrigNumElements = OrigVT.getVectorNumElements();
8993     int OrigSplitNumElements = OrigNumElements / 2;
8994     MVT OrigScalarVT = OrigVT.getScalarType();
8995     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8996
8997     SDValue LoV, HiV;
8998
8999     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9000     if (!BV) {
9001       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9002                         DAG.getIntPtrConstant(0, DL));
9003       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9004                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9005     } else {
9006
9007       SmallVector<SDValue, 16> LoOps, HiOps;
9008       for (int i = 0; i < OrigSplitNumElements; ++i) {
9009         LoOps.push_back(BV->getOperand(i));
9010         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9011       }
9012       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9013       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9014     }
9015     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9016                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9017   };
9018
9019   SDValue LoV1, HiV1, LoV2, HiV2;
9020   std::tie(LoV1, HiV1) = SplitVector(V1);
9021   std::tie(LoV2, HiV2) = SplitVector(V2);
9022
9023   // Now create two 4-way blends of these half-width vectors.
9024   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9025     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9026     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9027     for (int i = 0; i < SplitNumElements; ++i) {
9028       int M = HalfMask[i];
9029       if (M >= NumElements) {
9030         if (M >= NumElements + SplitNumElements)
9031           UseHiV2 = true;
9032         else
9033           UseLoV2 = true;
9034         V2BlendMask.push_back(M - NumElements);
9035         V1BlendMask.push_back(-1);
9036         BlendMask.push_back(SplitNumElements + i);
9037       } else if (M >= 0) {
9038         if (M >= SplitNumElements)
9039           UseHiV1 = true;
9040         else
9041           UseLoV1 = true;
9042         V2BlendMask.push_back(-1);
9043         V1BlendMask.push_back(M);
9044         BlendMask.push_back(i);
9045       } else {
9046         V2BlendMask.push_back(-1);
9047         V1BlendMask.push_back(-1);
9048         BlendMask.push_back(-1);
9049       }
9050     }
9051
9052     // Because the lowering happens after all combining takes place, we need to
9053     // manually combine these blend masks as much as possible so that we create
9054     // a minimal number of high-level vector shuffle nodes.
9055
9056     // First try just blending the halves of V1 or V2.
9057     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9058       return DAG.getUNDEF(SplitVT);
9059     if (!UseLoV2 && !UseHiV2)
9060       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9061     if (!UseLoV1 && !UseHiV1)
9062       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9063
9064     SDValue V1Blend, V2Blend;
9065     if (UseLoV1 && UseHiV1) {
9066       V1Blend =
9067         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9068     } else {
9069       // We only use half of V1 so map the usage down into the final blend mask.
9070       V1Blend = UseLoV1 ? LoV1 : HiV1;
9071       for (int i = 0; i < SplitNumElements; ++i)
9072         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9073           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9074     }
9075     if (UseLoV2 && UseHiV2) {
9076       V2Blend =
9077         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9078     } else {
9079       // We only use half of V2 so map the usage down into the final blend mask.
9080       V2Blend = UseLoV2 ? LoV2 : HiV2;
9081       for (int i = 0; i < SplitNumElements; ++i)
9082         if (BlendMask[i] >= SplitNumElements)
9083           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9084     }
9085     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9086   };
9087   SDValue Lo = HalfBlend(LoMask);
9088   SDValue Hi = HalfBlend(HiMask);
9089   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9090 }
9091
9092 /// \brief Either split a vector in halves or decompose the shuffles and the
9093 /// blend.
9094 ///
9095 /// This is provided as a good fallback for many lowerings of non-single-input
9096 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9097 /// between splitting the shuffle into 128-bit components and stitching those
9098 /// back together vs. extracting the single-input shuffles and blending those
9099 /// results.
9100 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9101                                                 SDValue V2, ArrayRef<int> Mask,
9102                                                 SelectionDAG &DAG) {
9103   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9104                                             "lower single-input shuffles as it "
9105                                             "could then recurse on itself.");
9106   int Size = Mask.size();
9107
9108   // If this can be modeled as a broadcast of two elements followed by a blend,
9109   // prefer that lowering. This is especially important because broadcasts can
9110   // often fold with memory operands.
9111   auto DoBothBroadcast = [&] {
9112     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9113     for (int M : Mask)
9114       if (M >= Size) {
9115         if (V2BroadcastIdx == -1)
9116           V2BroadcastIdx = M - Size;
9117         else if (M - Size != V2BroadcastIdx)
9118           return false;
9119       } else if (M >= 0) {
9120         if (V1BroadcastIdx == -1)
9121           V1BroadcastIdx = M;
9122         else if (M != V1BroadcastIdx)
9123           return false;
9124       }
9125     return true;
9126   };
9127   if (DoBothBroadcast())
9128     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9129                                                       DAG);
9130
9131   // If the inputs all stem from a single 128-bit lane of each input, then we
9132   // split them rather than blending because the split will decompose to
9133   // unusually few instructions.
9134   int LaneCount = VT.getSizeInBits() / 128;
9135   int LaneSize = Size / LaneCount;
9136   SmallBitVector LaneInputs[2];
9137   LaneInputs[0].resize(LaneCount, false);
9138   LaneInputs[1].resize(LaneCount, false);
9139   for (int i = 0; i < Size; ++i)
9140     if (Mask[i] >= 0)
9141       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9142   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9143     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9144
9145   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9146   // that the decomposed single-input shuffles don't end up here.
9147   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9148 }
9149
9150 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9151 /// a permutation and blend of those lanes.
9152 ///
9153 /// This essentially blends the out-of-lane inputs to each lane into the lane
9154 /// from a permuted copy of the vector. This lowering strategy results in four
9155 /// instructions in the worst case for a single-input cross lane shuffle which
9156 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9157 /// of. Special cases for each particular shuffle pattern should be handled
9158 /// prior to trying this lowering.
9159 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9160                                                        SDValue V1, SDValue V2,
9161                                                        ArrayRef<int> Mask,
9162                                                        SelectionDAG &DAG) {
9163   // FIXME: This should probably be generalized for 512-bit vectors as well.
9164   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9165   int LaneSize = Mask.size() / 2;
9166
9167   // If there are only inputs from one 128-bit lane, splitting will in fact be
9168   // less expensive. The flags track whether the given lane contains an element
9169   // that crosses to another lane.
9170   bool LaneCrossing[2] = {false, false};
9171   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9172     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9173       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9174   if (!LaneCrossing[0] || !LaneCrossing[1])
9175     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9176
9177   if (isSingleInputShuffleMask(Mask)) {
9178     SmallVector<int, 32> FlippedBlendMask;
9179     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9180       FlippedBlendMask.push_back(
9181           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9182                                   ? Mask[i]
9183                                   : Mask[i] % LaneSize +
9184                                         (i / LaneSize) * LaneSize + Size));
9185
9186     // Flip the vector, and blend the results which should now be in-lane. The
9187     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9188     // 5 for the high source. The value 3 selects the high half of source 2 and
9189     // the value 2 selects the low half of source 2. We only use source 2 to
9190     // allow folding it into a memory operand.
9191     unsigned PERMMask = 3 | 2 << 4;
9192     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9193                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9194     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9195   }
9196
9197   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9198   // will be handled by the above logic and a blend of the results, much like
9199   // other patterns in AVX.
9200   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9201 }
9202
9203 /// \brief Handle lowering 2-lane 128-bit shuffles.
9204 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9205                                         SDValue V2, ArrayRef<int> Mask,
9206                                         const X86Subtarget *Subtarget,
9207                                         SelectionDAG &DAG) {
9208   // TODO: If minimizing size and one of the inputs is a zero vector and the
9209   // the zero vector has only one use, we could use a VPERM2X128 to save the
9210   // instruction bytes needed to explicitly generate the zero vector.
9211
9212   // Blends are faster and handle all the non-lane-crossing cases.
9213   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9214                                                 Subtarget, DAG))
9215     return Blend;
9216
9217   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9218   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9219
9220   // If either input operand is a zero vector, use VPERM2X128 because its mask
9221   // allows us to replace the zero input with an implicit zero.
9222   if (!IsV1Zero && !IsV2Zero) {
9223     // Check for patterns which can be matched with a single insert of a 128-bit
9224     // subvector.
9225     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9226     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9227       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9228                                    VT.getVectorNumElements() / 2);
9229       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9230                                 DAG.getIntPtrConstant(0, DL));
9231       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9232                                 OnlyUsesV1 ? V1 : V2,
9233                                 DAG.getIntPtrConstant(0, DL));
9234       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9235     }
9236   }
9237
9238   // Otherwise form a 128-bit permutation. After accounting for undefs,
9239   // convert the 64-bit shuffle mask selection values into 128-bit
9240   // selection bits by dividing the indexes by 2 and shifting into positions
9241   // defined by a vperm2*128 instruction's immediate control byte.
9242
9243   // The immediate permute control byte looks like this:
9244   //    [1:0] - select 128 bits from sources for low half of destination
9245   //    [2]   - ignore
9246   //    [3]   - zero low half of destination
9247   //    [5:4] - select 128 bits from sources for high half of destination
9248   //    [6]   - ignore
9249   //    [7]   - zero high half of destination
9250
9251   int MaskLO = Mask[0];
9252   if (MaskLO == SM_SentinelUndef)
9253     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9254
9255   int MaskHI = Mask[2];
9256   if (MaskHI == SM_SentinelUndef)
9257     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9258
9259   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9260
9261   // If either input is a zero vector, replace it with an undef input.
9262   // Shuffle mask values <  4 are selecting elements of V1.
9263   // Shuffle mask values >= 4 are selecting elements of V2.
9264   // Adjust each half of the permute mask by clearing the half that was
9265   // selecting the zero vector and setting the zero mask bit.
9266   if (IsV1Zero) {
9267     V1 = DAG.getUNDEF(VT);
9268     if (MaskLO < 4)
9269       PermMask = (PermMask & 0xf0) | 0x08;
9270     if (MaskHI < 4)
9271       PermMask = (PermMask & 0x0f) | 0x80;
9272   }
9273   if (IsV2Zero) {
9274     V2 = DAG.getUNDEF(VT);
9275     if (MaskLO >= 4)
9276       PermMask = (PermMask & 0xf0) | 0x08;
9277     if (MaskHI >= 4)
9278       PermMask = (PermMask & 0x0f) | 0x80;
9279   }
9280
9281   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9282                      DAG.getConstant(PermMask, DL, MVT::i8));
9283 }
9284
9285 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9286 /// shuffling each lane.
9287 ///
9288 /// This will only succeed when the result of fixing the 128-bit lanes results
9289 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9290 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9291 /// the lane crosses early and then use simpler shuffles within each lane.
9292 ///
9293 /// FIXME: It might be worthwhile at some point to support this without
9294 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9295 /// in x86 only floating point has interesting non-repeating shuffles, and even
9296 /// those are still *marginally* more expensive.
9297 static SDValue lowerVectorShuffleByMerging128BitLanes(
9298     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9299     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9300   assert(!isSingleInputShuffleMask(Mask) &&
9301          "This is only useful with multiple inputs.");
9302
9303   int Size = Mask.size();
9304   int LaneSize = 128 / VT.getScalarSizeInBits();
9305   int NumLanes = Size / LaneSize;
9306   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9307
9308   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9309   // check whether the in-128-bit lane shuffles share a repeating pattern.
9310   SmallVector<int, 4> Lanes;
9311   Lanes.resize(NumLanes, -1);
9312   SmallVector<int, 4> InLaneMask;
9313   InLaneMask.resize(LaneSize, -1);
9314   for (int i = 0; i < Size; ++i) {
9315     if (Mask[i] < 0)
9316       continue;
9317
9318     int j = i / LaneSize;
9319
9320     if (Lanes[j] < 0) {
9321       // First entry we've seen for this lane.
9322       Lanes[j] = Mask[i] / LaneSize;
9323     } else if (Lanes[j] != Mask[i] / LaneSize) {
9324       // This doesn't match the lane selected previously!
9325       return SDValue();
9326     }
9327
9328     // Check that within each lane we have a consistent shuffle mask.
9329     int k = i % LaneSize;
9330     if (InLaneMask[k] < 0) {
9331       InLaneMask[k] = Mask[i] % LaneSize;
9332     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9333       // This doesn't fit a repeating in-lane mask.
9334       return SDValue();
9335     }
9336   }
9337
9338   // First shuffle the lanes into place.
9339   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9340                                 VT.getSizeInBits() / 64);
9341   SmallVector<int, 8> LaneMask;
9342   LaneMask.resize(NumLanes * 2, -1);
9343   for (int i = 0; i < NumLanes; ++i)
9344     if (Lanes[i] >= 0) {
9345       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9346       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9347     }
9348
9349   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9350   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9351   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9352
9353   // Cast it back to the type we actually want.
9354   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9355
9356   // Now do a simple shuffle that isn't lane crossing.
9357   SmallVector<int, 8> NewMask;
9358   NewMask.resize(Size, -1);
9359   for (int i = 0; i < Size; ++i)
9360     if (Mask[i] >= 0)
9361       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9362   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9363          "Must not introduce lane crosses at this point!");
9364
9365   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9366 }
9367
9368 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9369 /// given mask.
9370 ///
9371 /// This returns true if the elements from a particular input are already in the
9372 /// slot required by the given mask and require no permutation.
9373 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9374   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9375   int Size = Mask.size();
9376   for (int i = 0; i < Size; ++i)
9377     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9378       return false;
9379
9380   return true;
9381 }
9382
9383 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9384 ///
9385 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9386 /// isn't available.
9387 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9388                                        const X86Subtarget *Subtarget,
9389                                        SelectionDAG &DAG) {
9390   SDLoc DL(Op);
9391   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9392   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9393   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9394   ArrayRef<int> Mask = SVOp->getMask();
9395   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9396
9397   SmallVector<int, 4> WidenedMask;
9398   if (canWidenShuffleElements(Mask, WidenedMask))
9399     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9400                                     DAG);
9401
9402   if (isSingleInputShuffleMask(Mask)) {
9403     // Check for being able to broadcast a single element.
9404     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9405                                                           Mask, Subtarget, DAG))
9406       return Broadcast;
9407
9408     // Use low duplicate instructions for masks that match their pattern.
9409     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9410       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9411
9412     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9413       // Non-half-crossing single input shuffles can be lowerid with an
9414       // interleaved permutation.
9415       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9416                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9417       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9418                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9419     }
9420
9421     // With AVX2 we have direct support for this permutation.
9422     if (Subtarget->hasAVX2())
9423       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9424                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9425
9426     // Otherwise, fall back.
9427     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9428                                                    DAG);
9429   }
9430
9431   // X86 has dedicated unpack instructions that can handle specific blend
9432   // operations: UNPCKH and UNPCKL.
9433   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9434     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9435   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9436     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9437   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9438     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9439   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9440     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9441
9442   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9443                                                 Subtarget, DAG))
9444     return Blend;
9445
9446   // Check if the blend happens to exactly fit that of SHUFPD.
9447   if ((Mask[0] == -1 || Mask[0] < 2) &&
9448       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9449       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9450       (Mask[3] == -1 || Mask[3] >= 6)) {
9451     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9452                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9453     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9454                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9455   }
9456   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9457       (Mask[1] == -1 || Mask[1] < 2) &&
9458       (Mask[2] == -1 || Mask[2] >= 6) &&
9459       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9460     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9461                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9462     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9463                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9464   }
9465
9466   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9467   // shuffle. However, if we have AVX2 and either inputs are already in place,
9468   // we will be able to shuffle even across lanes the other input in a single
9469   // instruction so skip this pattern.
9470   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9471                                  isShuffleMaskInputInPlace(1, Mask))))
9472     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9473             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9474       return Result;
9475
9476   // If we have AVX2 then we always want to lower with a blend because an v4 we
9477   // can fully permute the elements.
9478   if (Subtarget->hasAVX2())
9479     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9480                                                       Mask, DAG);
9481
9482   // Otherwise fall back on generic lowering.
9483   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9484 }
9485
9486 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9487 ///
9488 /// This routine is only called when we have AVX2 and thus a reasonable
9489 /// instruction set for v4i64 shuffling..
9490 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9491                                        const X86Subtarget *Subtarget,
9492                                        SelectionDAG &DAG) {
9493   SDLoc DL(Op);
9494   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9495   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9496   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9497   ArrayRef<int> Mask = SVOp->getMask();
9498   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9499   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9500
9501   SmallVector<int, 4> WidenedMask;
9502   if (canWidenShuffleElements(Mask, WidenedMask))
9503     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9504                                     DAG);
9505
9506   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9507                                                 Subtarget, DAG))
9508     return Blend;
9509
9510   // Check for being able to broadcast a single element.
9511   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9512                                                         Mask, Subtarget, DAG))
9513     return Broadcast;
9514
9515   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9516   // use lower latency instructions that will operate on both 128-bit lanes.
9517   SmallVector<int, 2> RepeatedMask;
9518   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9519     if (isSingleInputShuffleMask(Mask)) {
9520       int PSHUFDMask[] = {-1, -1, -1, -1};
9521       for (int i = 0; i < 2; ++i)
9522         if (RepeatedMask[i] >= 0) {
9523           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9524           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9525         }
9526       return DAG.getNode(
9527           ISD::BITCAST, DL, MVT::v4i64,
9528           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9529                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9530                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9531     }
9532   }
9533
9534   // AVX2 provides a direct instruction for permuting a single input across
9535   // lanes.
9536   if (isSingleInputShuffleMask(Mask))
9537     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9538                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9539
9540   // Try to use shift instructions.
9541   if (SDValue Shift =
9542           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9543     return Shift;
9544
9545   // Use dedicated unpack instructions for masks that match their pattern.
9546   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9547     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9548   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9549     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9550   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9551     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9552   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9553     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9554
9555   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9556   // shuffle. However, if we have AVX2 and either inputs are already in place,
9557   // we will be able to shuffle even across lanes the other input in a single
9558   // instruction so skip this pattern.
9559   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9560                                  isShuffleMaskInputInPlace(1, Mask))))
9561     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9562             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9563       return Result;
9564
9565   // Otherwise fall back on generic blend lowering.
9566   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9567                                                     Mask, DAG);
9568 }
9569
9570 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9571 ///
9572 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9573 /// isn't available.
9574 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9575                                        const X86Subtarget *Subtarget,
9576                                        SelectionDAG &DAG) {
9577   SDLoc DL(Op);
9578   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9579   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9580   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9581   ArrayRef<int> Mask = SVOp->getMask();
9582   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9583
9584   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9585                                                 Subtarget, DAG))
9586     return Blend;
9587
9588   // Check for being able to broadcast a single element.
9589   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9590                                                         Mask, Subtarget, DAG))
9591     return Broadcast;
9592
9593   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9594   // options to efficiently lower the shuffle.
9595   SmallVector<int, 4> RepeatedMask;
9596   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9597     assert(RepeatedMask.size() == 4 &&
9598            "Repeated masks must be half the mask width!");
9599
9600     // Use even/odd duplicate instructions for masks that match their pattern.
9601     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9602       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9603     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9604       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9605
9606     if (isSingleInputShuffleMask(Mask))
9607       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9608                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9609
9610     // Use dedicated unpack instructions for masks that match their pattern.
9611     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9612       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9613     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9614       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9615     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9616       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9617     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9618       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9619
9620     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9621     // have already handled any direct blends. We also need to squash the
9622     // repeated mask into a simulated v4f32 mask.
9623     for (int i = 0; i < 4; ++i)
9624       if (RepeatedMask[i] >= 8)
9625         RepeatedMask[i] -= 4;
9626     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9627   }
9628
9629   // If we have a single input shuffle with different shuffle patterns in the
9630   // two 128-bit lanes use the variable mask to VPERMILPS.
9631   if (isSingleInputShuffleMask(Mask)) {
9632     SDValue VPermMask[8];
9633     for (int i = 0; i < 8; ++i)
9634       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9635                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9636     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9637       return DAG.getNode(
9638           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9639           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9640
9641     if (Subtarget->hasAVX2())
9642       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9643                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9644                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9645                                                  MVT::v8i32, VPermMask)),
9646                          V1);
9647
9648     // Otherwise, fall back.
9649     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9650                                                    DAG);
9651   }
9652
9653   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9654   // shuffle.
9655   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9656           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9657     return Result;
9658
9659   // If we have AVX2 then we always want to lower with a blend because at v8 we
9660   // can fully permute the elements.
9661   if (Subtarget->hasAVX2())
9662     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9663                                                       Mask, DAG);
9664
9665   // Otherwise fall back on generic lowering.
9666   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9667 }
9668
9669 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9670 ///
9671 /// This routine is only called when we have AVX2 and thus a reasonable
9672 /// instruction set for v8i32 shuffling..
9673 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9674                                        const X86Subtarget *Subtarget,
9675                                        SelectionDAG &DAG) {
9676   SDLoc DL(Op);
9677   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9678   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9679   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9680   ArrayRef<int> Mask = SVOp->getMask();
9681   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9682   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9683
9684   // Whenever we can lower this as a zext, that instruction is strictly faster
9685   // than any alternative. It also allows us to fold memory operands into the
9686   // shuffle in many cases.
9687   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9688                                                          Mask, Subtarget, DAG))
9689     return ZExt;
9690
9691   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9692                                                 Subtarget, DAG))
9693     return Blend;
9694
9695   // Check for being able to broadcast a single element.
9696   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9697                                                         Mask, Subtarget, DAG))
9698     return Broadcast;
9699
9700   // If the shuffle mask is repeated in each 128-bit lane we can use more
9701   // efficient instructions that mirror the shuffles across the two 128-bit
9702   // lanes.
9703   SmallVector<int, 4> RepeatedMask;
9704   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9705     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9706     if (isSingleInputShuffleMask(Mask))
9707       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9708                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9709
9710     // Use dedicated unpack instructions for masks that match their pattern.
9711     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9712       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9713     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9714       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9715     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9716       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9717     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9718       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9719   }
9720
9721   // Try to use shift instructions.
9722   if (SDValue Shift =
9723           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9724     return Shift;
9725
9726   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9727           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9728     return Rotate;
9729
9730   // If the shuffle patterns aren't repeated but it is a single input, directly
9731   // generate a cross-lane VPERMD instruction.
9732   if (isSingleInputShuffleMask(Mask)) {
9733     SDValue VPermMask[8];
9734     for (int i = 0; i < 8; ++i)
9735       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9736                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9737     return DAG.getNode(
9738         X86ISD::VPERMV, DL, MVT::v8i32,
9739         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9740   }
9741
9742   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9743   // shuffle.
9744   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9745           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9746     return Result;
9747
9748   // Otherwise fall back on generic blend lowering.
9749   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9750                                                     Mask, DAG);
9751 }
9752
9753 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9754 ///
9755 /// This routine is only called when we have AVX2 and thus a reasonable
9756 /// instruction set for v16i16 shuffling..
9757 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9758                                         const X86Subtarget *Subtarget,
9759                                         SelectionDAG &DAG) {
9760   SDLoc DL(Op);
9761   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9762   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9763   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9764   ArrayRef<int> Mask = SVOp->getMask();
9765   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9766   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9767
9768   // Whenever we can lower this as a zext, that instruction is strictly faster
9769   // than any alternative. It also allows us to fold memory operands into the
9770   // shuffle in many cases.
9771   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9772                                                          Mask, Subtarget, DAG))
9773     return ZExt;
9774
9775   // Check for being able to broadcast a single element.
9776   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9777                                                         Mask, Subtarget, DAG))
9778     return Broadcast;
9779
9780   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9781                                                 Subtarget, DAG))
9782     return Blend;
9783
9784   // Use dedicated unpack instructions for masks that match their pattern.
9785   if (isShuffleEquivalent(V1, V2, Mask,
9786                           {// First 128-bit lane:
9787                            0, 16, 1, 17, 2, 18, 3, 19,
9788                            // Second 128-bit lane:
9789                            8, 24, 9, 25, 10, 26, 11, 27}))
9790     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9791   if (isShuffleEquivalent(V1, V2, Mask,
9792                           {// First 128-bit lane:
9793                            4, 20, 5, 21, 6, 22, 7, 23,
9794                            // Second 128-bit lane:
9795                            12, 28, 13, 29, 14, 30, 15, 31}))
9796     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9797
9798   // Try to use shift instructions.
9799   if (SDValue Shift =
9800           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9801     return Shift;
9802
9803   // Try to use byte rotation instructions.
9804   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9805           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9806     return Rotate;
9807
9808   if (isSingleInputShuffleMask(Mask)) {
9809     // There are no generalized cross-lane shuffle operations available on i16
9810     // element types.
9811     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9812       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9813                                                      Mask, DAG);
9814
9815     SmallVector<int, 8> RepeatedMask;
9816     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9817       // As this is a single-input shuffle, the repeated mask should be
9818       // a strictly valid v8i16 mask that we can pass through to the v8i16
9819       // lowering to handle even the v16 case.
9820       return lowerV8I16GeneralSingleInputVectorShuffle(
9821           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9822     }
9823
9824     SDValue PSHUFBMask[32];
9825     for (int i = 0; i < 16; ++i) {
9826       if (Mask[i] == -1) {
9827         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9828         continue;
9829       }
9830
9831       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9832       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9833       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9834       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9835     }
9836     return DAG.getNode(
9837         ISD::BITCAST, DL, MVT::v16i16,
9838         DAG.getNode(
9839             X86ISD::PSHUFB, DL, MVT::v32i8,
9840             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9841             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9842   }
9843
9844   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9845   // shuffle.
9846   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9847           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9848     return Result;
9849
9850   // Otherwise fall back on generic lowering.
9851   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9852 }
9853
9854 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9855 ///
9856 /// This routine is only called when we have AVX2 and thus a reasonable
9857 /// instruction set for v32i8 shuffling..
9858 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9859                                        const X86Subtarget *Subtarget,
9860                                        SelectionDAG &DAG) {
9861   SDLoc DL(Op);
9862   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9863   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9864   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9865   ArrayRef<int> Mask = SVOp->getMask();
9866   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9867   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9868
9869   // Whenever we can lower this as a zext, that instruction is strictly faster
9870   // than any alternative. It also allows us to fold memory operands into the
9871   // shuffle in many cases.
9872   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9873                                                          Mask, Subtarget, DAG))
9874     return ZExt;
9875
9876   // Check for being able to broadcast a single element.
9877   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9878                                                         Mask, Subtarget, DAG))
9879     return Broadcast;
9880
9881   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9882                                                 Subtarget, DAG))
9883     return Blend;
9884
9885   // Use dedicated unpack instructions for masks that match their pattern.
9886   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9887   // 256-bit lanes.
9888   if (isShuffleEquivalent(
9889           V1, V2, Mask,
9890           {// First 128-bit lane:
9891            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9892            // Second 128-bit lane:
9893            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9894     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9895   if (isShuffleEquivalent(
9896           V1, V2, Mask,
9897           {// First 128-bit lane:
9898            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9899            // Second 128-bit lane:
9900            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9901     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9902
9903   // Try to use shift instructions.
9904   if (SDValue Shift =
9905           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9906     return Shift;
9907
9908   // Try to use byte rotation instructions.
9909   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9910           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9911     return Rotate;
9912
9913   if (isSingleInputShuffleMask(Mask)) {
9914     // There are no generalized cross-lane shuffle operations available on i8
9915     // element types.
9916     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9917       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9918                                                      Mask, DAG);
9919
9920     SDValue PSHUFBMask[32];
9921     for (int i = 0; i < 32; ++i)
9922       PSHUFBMask[i] =
9923           Mask[i] < 0
9924               ? DAG.getUNDEF(MVT::i8)
9925               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9926                                 MVT::i8);
9927
9928     return DAG.getNode(
9929         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9930         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9931   }
9932
9933   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9934   // shuffle.
9935   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9936           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9937     return Result;
9938
9939   // Otherwise fall back on generic lowering.
9940   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9941 }
9942
9943 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9944 ///
9945 /// This routine either breaks down the specific type of a 256-bit x86 vector
9946 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9947 /// together based on the available instructions.
9948 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9949                                         MVT VT, const X86Subtarget *Subtarget,
9950                                         SelectionDAG &DAG) {
9951   SDLoc DL(Op);
9952   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9953   ArrayRef<int> Mask = SVOp->getMask();
9954
9955   // If we have a single input to the zero element, insert that into V1 if we
9956   // can do so cheaply.
9957   int NumElts = VT.getVectorNumElements();
9958   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9959     return M >= NumElts;
9960   });
9961
9962   if (NumV2Elements == 1 && Mask[0] >= NumElts)
9963     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9964                               DL, VT, V1, V2, Mask, Subtarget, DAG))
9965       return Insertion;
9966
9967   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9968   // check for those subtargets here and avoid much of the subtarget querying in
9969   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9970   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9971   // floating point types there eventually, just immediately cast everything to
9972   // a float and operate entirely in that domain.
9973   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9974     int ElementBits = VT.getScalarSizeInBits();
9975     if (ElementBits < 32)
9976       // No floating point type available, decompose into 128-bit vectors.
9977       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9978
9979     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9980                                 VT.getVectorNumElements());
9981     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9982     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9983     return DAG.getNode(ISD::BITCAST, DL, VT,
9984                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9985   }
9986
9987   switch (VT.SimpleTy) {
9988   case MVT::v4f64:
9989     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9990   case MVT::v4i64:
9991     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9992   case MVT::v8f32:
9993     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9994   case MVT::v8i32:
9995     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9996   case MVT::v16i16:
9997     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9998   case MVT::v32i8:
9999     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10000
10001   default:
10002     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10003   }
10004 }
10005
10006 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10007 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10008                                        const X86Subtarget *Subtarget,
10009                                        SelectionDAG &DAG) {
10010   SDLoc DL(Op);
10011   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10012   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10013   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10014   ArrayRef<int> Mask = SVOp->getMask();
10015   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10016
10017   // X86 has dedicated unpack instructions that can handle specific blend
10018   // operations: UNPCKH and UNPCKL.
10019   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10020     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10021   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10022     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10023
10024   // FIXME: Implement direct support for this type!
10025   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10026 }
10027
10028 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10029 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10030                                        const X86Subtarget *Subtarget,
10031                                        SelectionDAG &DAG) {
10032   SDLoc DL(Op);
10033   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10034   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10035   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10036   ArrayRef<int> Mask = SVOp->getMask();
10037   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10038
10039   // Use dedicated unpack instructions for masks that match their pattern.
10040   if (isShuffleEquivalent(V1, V2, Mask,
10041                           {// First 128-bit lane.
10042                            0, 16, 1, 17, 4, 20, 5, 21,
10043                            // Second 128-bit lane.
10044                            8, 24, 9, 25, 12, 28, 13, 29}))
10045     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10046   if (isShuffleEquivalent(V1, V2, Mask,
10047                           {// First 128-bit lane.
10048                            2, 18, 3, 19, 6, 22, 7, 23,
10049                            // Second 128-bit lane.
10050                            10, 26, 11, 27, 14, 30, 15, 31}))
10051     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10052
10053   // FIXME: Implement direct support for this type!
10054   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10055 }
10056
10057 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10058 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10059                                        const X86Subtarget *Subtarget,
10060                                        SelectionDAG &DAG) {
10061   SDLoc DL(Op);
10062   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10063   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10064   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10065   ArrayRef<int> Mask = SVOp->getMask();
10066   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10067
10068   // X86 has dedicated unpack instructions that can handle specific blend
10069   // operations: UNPCKH and UNPCKL.
10070   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10071     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10072   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10073     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10074
10075   // FIXME: Implement direct support for this type!
10076   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10077 }
10078
10079 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10080 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10081                                        const X86Subtarget *Subtarget,
10082                                        SelectionDAG &DAG) {
10083   SDLoc DL(Op);
10084   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10085   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10086   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10087   ArrayRef<int> Mask = SVOp->getMask();
10088   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10089
10090   // Use dedicated unpack instructions for masks that match their pattern.
10091   if (isShuffleEquivalent(V1, V2, Mask,
10092                           {// First 128-bit lane.
10093                            0, 16, 1, 17, 4, 20, 5, 21,
10094                            // Second 128-bit lane.
10095                            8, 24, 9, 25, 12, 28, 13, 29}))
10096     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10097   if (isShuffleEquivalent(V1, V2, Mask,
10098                           {// First 128-bit lane.
10099                            2, 18, 3, 19, 6, 22, 7, 23,
10100                            // Second 128-bit lane.
10101                            10, 26, 11, 27, 14, 30, 15, 31}))
10102     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10103
10104   // FIXME: Implement direct support for this type!
10105   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10106 }
10107
10108 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10109 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10110                                         const X86Subtarget *Subtarget,
10111                                         SelectionDAG &DAG) {
10112   SDLoc DL(Op);
10113   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10114   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10115   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10116   ArrayRef<int> Mask = SVOp->getMask();
10117   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10118   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10119
10120   // FIXME: Implement direct support for this type!
10121   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10122 }
10123
10124 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10125 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10126                                        const X86Subtarget *Subtarget,
10127                                        SelectionDAG &DAG) {
10128   SDLoc DL(Op);
10129   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10130   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10131   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10132   ArrayRef<int> Mask = SVOp->getMask();
10133   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10134   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10135
10136   // FIXME: Implement direct support for this type!
10137   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10138 }
10139
10140 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10141 ///
10142 /// This routine either breaks down the specific type of a 512-bit x86 vector
10143 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10144 /// together based on the available instructions.
10145 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10146                                         MVT VT, const X86Subtarget *Subtarget,
10147                                         SelectionDAG &DAG) {
10148   SDLoc DL(Op);
10149   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10150   ArrayRef<int> Mask = SVOp->getMask();
10151   assert(Subtarget->hasAVX512() &&
10152          "Cannot lower 512-bit vectors w/ basic ISA!");
10153
10154   // Check for being able to broadcast a single element.
10155   if (SDValue Broadcast =
10156           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10157     return Broadcast;
10158
10159   // Dispatch to each element type for lowering. If we don't have supprot for
10160   // specific element type shuffles at 512 bits, immediately split them and
10161   // lower them. Each lowering routine of a given type is allowed to assume that
10162   // the requisite ISA extensions for that element type are available.
10163   switch (VT.SimpleTy) {
10164   case MVT::v8f64:
10165     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10166   case MVT::v16f32:
10167     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10168   case MVT::v8i64:
10169     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10170   case MVT::v16i32:
10171     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10172   case MVT::v32i16:
10173     if (Subtarget->hasBWI())
10174       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10175     break;
10176   case MVT::v64i8:
10177     if (Subtarget->hasBWI())
10178       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10179     break;
10180
10181   default:
10182     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10183   }
10184
10185   // Otherwise fall back on splitting.
10186   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10187 }
10188
10189 /// \brief Top-level lowering for x86 vector shuffles.
10190 ///
10191 /// This handles decomposition, canonicalization, and lowering of all x86
10192 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10193 /// above in helper routines. The canonicalization attempts to widen shuffles
10194 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10195 /// s.t. only one of the two inputs needs to be tested, etc.
10196 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10197                                   SelectionDAG &DAG) {
10198   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10199   ArrayRef<int> Mask = SVOp->getMask();
10200   SDValue V1 = Op.getOperand(0);
10201   SDValue V2 = Op.getOperand(1);
10202   MVT VT = Op.getSimpleValueType();
10203   int NumElements = VT.getVectorNumElements();
10204   SDLoc dl(Op);
10205
10206   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10207
10208   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10209   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10210   if (V1IsUndef && V2IsUndef)
10211     return DAG.getUNDEF(VT);
10212
10213   // When we create a shuffle node we put the UNDEF node to second operand,
10214   // but in some cases the first operand may be transformed to UNDEF.
10215   // In this case we should just commute the node.
10216   if (V1IsUndef)
10217     return DAG.getCommutedVectorShuffle(*SVOp);
10218
10219   // Check for non-undef masks pointing at an undef vector and make the masks
10220   // undef as well. This makes it easier to match the shuffle based solely on
10221   // the mask.
10222   if (V2IsUndef)
10223     for (int M : Mask)
10224       if (M >= NumElements) {
10225         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10226         for (int &M : NewMask)
10227           if (M >= NumElements)
10228             M = -1;
10229         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10230       }
10231
10232   // We actually see shuffles that are entirely re-arrangements of a set of
10233   // zero inputs. This mostly happens while decomposing complex shuffles into
10234   // simple ones. Directly lower these as a buildvector of zeros.
10235   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10236   if (Zeroable.all())
10237     return getZeroVector(VT, Subtarget, DAG, dl);
10238
10239   // Try to collapse shuffles into using a vector type with fewer elements but
10240   // wider element types. We cap this to not form integers or floating point
10241   // elements wider than 64 bits, but it might be interesting to form i128
10242   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10243   SmallVector<int, 16> WidenedMask;
10244   if (VT.getScalarSizeInBits() < 64 &&
10245       canWidenShuffleElements(Mask, WidenedMask)) {
10246     MVT NewEltVT = VT.isFloatingPoint()
10247                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10248                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10249     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10250     // Make sure that the new vector type is legal. For example, v2f64 isn't
10251     // legal on SSE1.
10252     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10253       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10254       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10255       return DAG.getNode(ISD::BITCAST, dl, VT,
10256                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10257     }
10258   }
10259
10260   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10261   for (int M : SVOp->getMask())
10262     if (M < 0)
10263       ++NumUndefElements;
10264     else if (M < NumElements)
10265       ++NumV1Elements;
10266     else
10267       ++NumV2Elements;
10268
10269   // Commute the shuffle as needed such that more elements come from V1 than
10270   // V2. This allows us to match the shuffle pattern strictly on how many
10271   // elements come from V1 without handling the symmetric cases.
10272   if (NumV2Elements > NumV1Elements)
10273     return DAG.getCommutedVectorShuffle(*SVOp);
10274
10275   // When the number of V1 and V2 elements are the same, try to minimize the
10276   // number of uses of V2 in the low half of the vector. When that is tied,
10277   // ensure that the sum of indices for V1 is equal to or lower than the sum
10278   // indices for V2. When those are equal, try to ensure that the number of odd
10279   // indices for V1 is lower than the number of odd indices for V2.
10280   if (NumV1Elements == NumV2Elements) {
10281     int LowV1Elements = 0, LowV2Elements = 0;
10282     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10283       if (M >= NumElements)
10284         ++LowV2Elements;
10285       else if (M >= 0)
10286         ++LowV1Elements;
10287     if (LowV2Elements > LowV1Elements) {
10288       return DAG.getCommutedVectorShuffle(*SVOp);
10289     } else if (LowV2Elements == LowV1Elements) {
10290       int SumV1Indices = 0, SumV2Indices = 0;
10291       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10292         if (SVOp->getMask()[i] >= NumElements)
10293           SumV2Indices += i;
10294         else if (SVOp->getMask()[i] >= 0)
10295           SumV1Indices += i;
10296       if (SumV2Indices < SumV1Indices) {
10297         return DAG.getCommutedVectorShuffle(*SVOp);
10298       } else if (SumV2Indices == SumV1Indices) {
10299         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10300         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10301           if (SVOp->getMask()[i] >= NumElements)
10302             NumV2OddIndices += i % 2;
10303           else if (SVOp->getMask()[i] >= 0)
10304             NumV1OddIndices += i % 2;
10305         if (NumV2OddIndices < NumV1OddIndices)
10306           return DAG.getCommutedVectorShuffle(*SVOp);
10307       }
10308     }
10309   }
10310
10311   // For each vector width, delegate to a specialized lowering routine.
10312   if (VT.getSizeInBits() == 128)
10313     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10314
10315   if (VT.getSizeInBits() == 256)
10316     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10317
10318   // Force AVX-512 vectors to be scalarized for now.
10319   // FIXME: Implement AVX-512 support!
10320   if (VT.getSizeInBits() == 512)
10321     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10322
10323   llvm_unreachable("Unimplemented!");
10324 }
10325
10326 // This function assumes its argument is a BUILD_VECTOR of constants or
10327 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10328 // true.
10329 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10330                                     unsigned &MaskValue) {
10331   MaskValue = 0;
10332   unsigned NumElems = BuildVector->getNumOperands();
10333   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10334   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10335   unsigned NumElemsInLane = NumElems / NumLanes;
10336
10337   // Blend for v16i16 should be symetric for the both lanes.
10338   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10339     SDValue EltCond = BuildVector->getOperand(i);
10340     SDValue SndLaneEltCond =
10341         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10342
10343     int Lane1Cond = -1, Lane2Cond = -1;
10344     if (isa<ConstantSDNode>(EltCond))
10345       Lane1Cond = !isZero(EltCond);
10346     if (isa<ConstantSDNode>(SndLaneEltCond))
10347       Lane2Cond = !isZero(SndLaneEltCond);
10348
10349     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10350       // Lane1Cond != 0, means we want the first argument.
10351       // Lane1Cond == 0, means we want the second argument.
10352       // The encoding of this argument is 0 for the first argument, 1
10353       // for the second. Therefore, invert the condition.
10354       MaskValue |= !Lane1Cond << i;
10355     else if (Lane1Cond < 0)
10356       MaskValue |= !Lane2Cond << i;
10357     else
10358       return false;
10359   }
10360   return true;
10361 }
10362
10363 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10364 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10365                                            const X86Subtarget *Subtarget,
10366                                            SelectionDAG &DAG) {
10367   SDValue Cond = Op.getOperand(0);
10368   SDValue LHS = Op.getOperand(1);
10369   SDValue RHS = Op.getOperand(2);
10370   SDLoc dl(Op);
10371   MVT VT = Op.getSimpleValueType();
10372
10373   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10374     return SDValue();
10375   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10376
10377   // Only non-legal VSELECTs reach this lowering, convert those into generic
10378   // shuffles and re-use the shuffle lowering path for blends.
10379   SmallVector<int, 32> Mask;
10380   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10381     SDValue CondElt = CondBV->getOperand(i);
10382     Mask.push_back(
10383         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10384   }
10385   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10386 }
10387
10388 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10389   // A vselect where all conditions and data are constants can be optimized into
10390   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10391   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10392       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10393       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10394     return SDValue();
10395
10396   // Try to lower this to a blend-style vector shuffle. This can handle all
10397   // constant condition cases.
10398   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10399     return BlendOp;
10400
10401   // Variable blends are only legal from SSE4.1 onward.
10402   if (!Subtarget->hasSSE41())
10403     return SDValue();
10404
10405   // Only some types will be legal on some subtargets. If we can emit a legal
10406   // VSELECT-matching blend, return Op, and but if we need to expand, return
10407   // a null value.
10408   switch (Op.getSimpleValueType().SimpleTy) {
10409   default:
10410     // Most of the vector types have blends past SSE4.1.
10411     return Op;
10412
10413   case MVT::v32i8:
10414     // The byte blends for AVX vectors were introduced only in AVX2.
10415     if (Subtarget->hasAVX2())
10416       return Op;
10417
10418     return SDValue();
10419
10420   case MVT::v8i16:
10421   case MVT::v16i16:
10422     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10423     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10424       return Op;
10425
10426     // FIXME: We should custom lower this by fixing the condition and using i8
10427     // blends.
10428     return SDValue();
10429   }
10430 }
10431
10432 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10433   MVT VT = Op.getSimpleValueType();
10434   SDLoc dl(Op);
10435
10436   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10437     return SDValue();
10438
10439   if (VT.getSizeInBits() == 8) {
10440     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10441                                   Op.getOperand(0), Op.getOperand(1));
10442     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10443                                   DAG.getValueType(VT));
10444     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10445   }
10446
10447   if (VT.getSizeInBits() == 16) {
10448     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10449     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10450     if (Idx == 0)
10451       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10452                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10453                                      DAG.getNode(ISD::BITCAST, dl,
10454                                                  MVT::v4i32,
10455                                                  Op.getOperand(0)),
10456                                      Op.getOperand(1)));
10457     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10458                                   Op.getOperand(0), Op.getOperand(1));
10459     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10460                                   DAG.getValueType(VT));
10461     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10462   }
10463
10464   if (VT == MVT::f32) {
10465     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10466     // the result back to FR32 register. It's only worth matching if the
10467     // result has a single use which is a store or a bitcast to i32.  And in
10468     // the case of a store, it's not worth it if the index is a constant 0,
10469     // because a MOVSSmr can be used instead, which is smaller and faster.
10470     if (!Op.hasOneUse())
10471       return SDValue();
10472     SDNode *User = *Op.getNode()->use_begin();
10473     if ((User->getOpcode() != ISD::STORE ||
10474          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10475           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10476         (User->getOpcode() != ISD::BITCAST ||
10477          User->getValueType(0) != MVT::i32))
10478       return SDValue();
10479     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10480                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10481                                               Op.getOperand(0)),
10482                                               Op.getOperand(1));
10483     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10484   }
10485
10486   if (VT == MVT::i32 || VT == MVT::i64) {
10487     // ExtractPS/pextrq works with constant index.
10488     if (isa<ConstantSDNode>(Op.getOperand(1)))
10489       return Op;
10490   }
10491   return SDValue();
10492 }
10493
10494 /// Extract one bit from mask vector, like v16i1 or v8i1.
10495 /// AVX-512 feature.
10496 SDValue
10497 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10498   SDValue Vec = Op.getOperand(0);
10499   SDLoc dl(Vec);
10500   MVT VecVT = Vec.getSimpleValueType();
10501   SDValue Idx = Op.getOperand(1);
10502   MVT EltVT = Op.getSimpleValueType();
10503
10504   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10505   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10506          "Unexpected vector type in ExtractBitFromMaskVector");
10507
10508   // variable index can't be handled in mask registers,
10509   // extend vector to VR512
10510   if (!isa<ConstantSDNode>(Idx)) {
10511     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10512     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10513     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10514                               ExtVT.getVectorElementType(), Ext, Idx);
10515     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10516   }
10517
10518   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10519   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10520   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10521     rc = getRegClassFor(MVT::v16i1);
10522   unsigned MaxSift = rc->getSize()*8 - 1;
10523   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10524                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10525   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10526                     DAG.getConstant(MaxSift, dl, MVT::i8));
10527   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10528                        DAG.getIntPtrConstant(0, dl));
10529 }
10530
10531 SDValue
10532 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10533                                            SelectionDAG &DAG) const {
10534   SDLoc dl(Op);
10535   SDValue Vec = Op.getOperand(0);
10536   MVT VecVT = Vec.getSimpleValueType();
10537   SDValue Idx = Op.getOperand(1);
10538
10539   if (Op.getSimpleValueType() == MVT::i1)
10540     return ExtractBitFromMaskVector(Op, DAG);
10541
10542   if (!isa<ConstantSDNode>(Idx)) {
10543     if (VecVT.is512BitVector() ||
10544         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10545          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10546
10547       MVT MaskEltVT =
10548         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10549       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10550                                     MaskEltVT.getSizeInBits());
10551
10552       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10553       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10554                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10555                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10556       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10557       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10558                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10559     }
10560     return SDValue();
10561   }
10562
10563   // If this is a 256-bit vector result, first extract the 128-bit vector and
10564   // then extract the element from the 128-bit vector.
10565   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10566
10567     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10568     // Get the 128-bit vector.
10569     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10570     MVT EltVT = VecVT.getVectorElementType();
10571
10572     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10573
10574     //if (IdxVal >= NumElems/2)
10575     //  IdxVal -= NumElems/2;
10576     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10577     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10578                        DAG.getConstant(IdxVal, dl, MVT::i32));
10579   }
10580
10581   assert(VecVT.is128BitVector() && "Unexpected vector length");
10582
10583   if (Subtarget->hasSSE41()) {
10584     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10585     if (Res.getNode())
10586       return Res;
10587   }
10588
10589   MVT VT = Op.getSimpleValueType();
10590   // TODO: handle v16i8.
10591   if (VT.getSizeInBits() == 16) {
10592     SDValue Vec = Op.getOperand(0);
10593     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10594     if (Idx == 0)
10595       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10596                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10597                                      DAG.getNode(ISD::BITCAST, dl,
10598                                                  MVT::v4i32, Vec),
10599                                      Op.getOperand(1)));
10600     // Transform it so it match pextrw which produces a 32-bit result.
10601     MVT EltVT = MVT::i32;
10602     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10603                                   Op.getOperand(0), Op.getOperand(1));
10604     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10605                                   DAG.getValueType(VT));
10606     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10607   }
10608
10609   if (VT.getSizeInBits() == 32) {
10610     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10611     if (Idx == 0)
10612       return Op;
10613
10614     // SHUFPS the element to the lowest double word, then movss.
10615     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10616     MVT VVT = Op.getOperand(0).getSimpleValueType();
10617     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10618                                        DAG.getUNDEF(VVT), Mask);
10619     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10620                        DAG.getIntPtrConstant(0, dl));
10621   }
10622
10623   if (VT.getSizeInBits() == 64) {
10624     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10625     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10626     //        to match extract_elt for f64.
10627     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10628     if (Idx == 0)
10629       return Op;
10630
10631     // UNPCKHPD the element to the lowest double word, then movsd.
10632     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10633     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10634     int Mask[2] = { 1, -1 };
10635     MVT VVT = Op.getOperand(0).getSimpleValueType();
10636     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10637                                        DAG.getUNDEF(VVT), Mask);
10638     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10639                        DAG.getIntPtrConstant(0, dl));
10640   }
10641
10642   return SDValue();
10643 }
10644
10645 /// Insert one bit to mask vector, like v16i1 or v8i1.
10646 /// AVX-512 feature.
10647 SDValue
10648 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10649   SDLoc dl(Op);
10650   SDValue Vec = Op.getOperand(0);
10651   SDValue Elt = Op.getOperand(1);
10652   SDValue Idx = Op.getOperand(2);
10653   MVT VecVT = Vec.getSimpleValueType();
10654
10655   if (!isa<ConstantSDNode>(Idx)) {
10656     // Non constant index. Extend source and destination,
10657     // insert element and then truncate the result.
10658     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10659     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10660     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10661       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10662       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10663     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10664   }
10665
10666   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10667   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10668   if (Vec.getOpcode() == ISD::UNDEF)
10669     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10670                        DAG.getConstant(IdxVal, dl, MVT::i8));
10671   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10672   unsigned MaxSift = rc->getSize()*8 - 1;
10673   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10674                     DAG.getConstant(MaxSift, dl, MVT::i8));
10675   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10676                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10677   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10678 }
10679
10680 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10681                                                   SelectionDAG &DAG) const {
10682   MVT VT = Op.getSimpleValueType();
10683   MVT EltVT = VT.getVectorElementType();
10684
10685   if (EltVT == MVT::i1)
10686     return InsertBitToMaskVector(Op, DAG);
10687
10688   SDLoc dl(Op);
10689   SDValue N0 = Op.getOperand(0);
10690   SDValue N1 = Op.getOperand(1);
10691   SDValue N2 = Op.getOperand(2);
10692   if (!isa<ConstantSDNode>(N2))
10693     return SDValue();
10694   auto *N2C = cast<ConstantSDNode>(N2);
10695   unsigned IdxVal = N2C->getZExtValue();
10696
10697   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10698   // into that, and then insert the subvector back into the result.
10699   if (VT.is256BitVector() || VT.is512BitVector()) {
10700     // With a 256-bit vector, we can insert into the zero element efficiently
10701     // using a blend if we have AVX or AVX2 and the right data type.
10702     if (VT.is256BitVector() && IdxVal == 0) {
10703       // TODO: It is worthwhile to cast integer to floating point and back
10704       // and incur a domain crossing penalty if that's what we'll end up
10705       // doing anyway after extracting to a 128-bit vector.
10706       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10707           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10708         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10709         N2 = DAG.getIntPtrConstant(1, dl);
10710         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10711       }
10712     }
10713
10714     // Get the desired 128-bit vector chunk.
10715     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10716
10717     // Insert the element into the desired chunk.
10718     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10719     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10720
10721     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10722                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10723
10724     // Insert the changed part back into the bigger vector
10725     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10726   }
10727   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10728
10729   if (Subtarget->hasSSE41()) {
10730     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10731       unsigned Opc;
10732       if (VT == MVT::v8i16) {
10733         Opc = X86ISD::PINSRW;
10734       } else {
10735         assert(VT == MVT::v16i8);
10736         Opc = X86ISD::PINSRB;
10737       }
10738
10739       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10740       // argument.
10741       if (N1.getValueType() != MVT::i32)
10742         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10743       if (N2.getValueType() != MVT::i32)
10744         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10745       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10746     }
10747
10748     if (EltVT == MVT::f32) {
10749       // Bits [7:6] of the constant are the source select. This will always be
10750       //   zero here. The DAG Combiner may combine an extract_elt index into
10751       //   these bits. For example (insert (extract, 3), 2) could be matched by
10752       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10753       // Bits [5:4] of the constant are the destination select. This is the
10754       //   value of the incoming immediate.
10755       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10756       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10757
10758       const Function *F = DAG.getMachineFunction().getFunction();
10759       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10760       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10761         // If this is an insertion of 32-bits into the low 32-bits of
10762         // a vector, we prefer to generate a blend with immediate rather
10763         // than an insertps. Blends are simpler operations in hardware and so
10764         // will always have equal or better performance than insertps.
10765         // But if optimizing for size and there's a load folding opportunity,
10766         // generate insertps because blendps does not have a 32-bit memory
10767         // operand form.
10768         N2 = DAG.getIntPtrConstant(1, dl);
10769         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10770         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10771       }
10772       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10773       // Create this as a scalar to vector..
10774       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10775       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10776     }
10777
10778     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10779       // PINSR* works with constant index.
10780       return Op;
10781     }
10782   }
10783
10784   if (EltVT == MVT::i8)
10785     return SDValue();
10786
10787   if (EltVT.getSizeInBits() == 16) {
10788     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10789     // as its second argument.
10790     if (N1.getValueType() != MVT::i32)
10791       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10792     if (N2.getValueType() != MVT::i32)
10793       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10794     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10795   }
10796   return SDValue();
10797 }
10798
10799 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10800   SDLoc dl(Op);
10801   MVT OpVT = Op.getSimpleValueType();
10802
10803   // If this is a 256-bit vector result, first insert into a 128-bit
10804   // vector and then insert into the 256-bit vector.
10805   if (!OpVT.is128BitVector()) {
10806     // Insert into a 128-bit vector.
10807     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10808     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10809                                  OpVT.getVectorNumElements() / SizeFactor);
10810
10811     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10812
10813     // Insert the 128-bit vector.
10814     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10815   }
10816
10817   if (OpVT == MVT::v1i64 &&
10818       Op.getOperand(0).getValueType() == MVT::i64)
10819     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10820
10821   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10822   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10823   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10824                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10825 }
10826
10827 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10828 // a simple subregister reference or explicit instructions to grab
10829 // upper bits of a vector.
10830 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10831                                       SelectionDAG &DAG) {
10832   SDLoc dl(Op);
10833   SDValue In =  Op.getOperand(0);
10834   SDValue Idx = Op.getOperand(1);
10835   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10836   MVT ResVT   = Op.getSimpleValueType();
10837   MVT InVT    = In.getSimpleValueType();
10838
10839   if (Subtarget->hasFp256()) {
10840     if (ResVT.is128BitVector() &&
10841         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10842         isa<ConstantSDNode>(Idx)) {
10843       return Extract128BitVector(In, IdxVal, DAG, dl);
10844     }
10845     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10846         isa<ConstantSDNode>(Idx)) {
10847       return Extract256BitVector(In, IdxVal, DAG, dl);
10848     }
10849   }
10850   return SDValue();
10851 }
10852
10853 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10854 // simple superregister reference or explicit instructions to insert
10855 // the upper bits of a vector.
10856 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10857                                      SelectionDAG &DAG) {
10858   if (!Subtarget->hasAVX())
10859     return SDValue();
10860
10861   SDLoc dl(Op);
10862   SDValue Vec = Op.getOperand(0);
10863   SDValue SubVec = Op.getOperand(1);
10864   SDValue Idx = Op.getOperand(2);
10865
10866   if (!isa<ConstantSDNode>(Idx))
10867     return SDValue();
10868
10869   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10870   MVT OpVT = Op.getSimpleValueType();
10871   MVT SubVecVT = SubVec.getSimpleValueType();
10872
10873   // Fold two 16-byte subvector loads into one 32-byte load:
10874   // (insert_subvector (insert_subvector undef, (load addr), 0),
10875   //                   (load addr + 16), Elts/2)
10876   // --> load32 addr
10877   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10878       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10879       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10880       !Subtarget->isUnalignedMem32Slow()) {
10881     SDValue SubVec2 = Vec.getOperand(1);
10882     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10883       if (Idx2->getZExtValue() == 0) {
10884         SDValue Ops[] = { SubVec2, SubVec };
10885         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10886         if (LD.getNode())
10887           return LD;
10888       }
10889     }
10890   }
10891
10892   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10893       SubVecVT.is128BitVector())
10894     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10895
10896   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10897     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10898
10899   if (OpVT.getVectorElementType() == MVT::i1) {
10900     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10901       return Op;
10902     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10903     SDValue Undef = DAG.getUNDEF(OpVT);
10904     unsigned NumElems = OpVT.getVectorNumElements();
10905     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10906
10907     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10908       // Zero upper bits of the Vec
10909       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10910       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10911
10912       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10913                                  SubVec, ZeroIdx);
10914       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10915       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10916     }
10917     if (IdxVal == 0) {
10918       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10919                                  SubVec, ZeroIdx);
10920       // Zero upper bits of the Vec2
10921       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10922       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10923       // Zero lower bits of the Vec
10924       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10925       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10926       // Merge them together
10927       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10928     }
10929   }
10930   return SDValue();
10931 }
10932
10933 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10934 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10935 // one of the above mentioned nodes. It has to be wrapped because otherwise
10936 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10937 // be used to form addressing mode. These wrapped nodes will be selected
10938 // into MOV32ri.
10939 SDValue
10940 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10941   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10942
10943   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10944   // global base reg.
10945   unsigned char OpFlag = 0;
10946   unsigned WrapperKind = X86ISD::Wrapper;
10947   CodeModel::Model M = DAG.getTarget().getCodeModel();
10948
10949   if (Subtarget->isPICStyleRIPRel() &&
10950       (M == CodeModel::Small || M == CodeModel::Kernel))
10951     WrapperKind = X86ISD::WrapperRIP;
10952   else if (Subtarget->isPICStyleGOT())
10953     OpFlag = X86II::MO_GOTOFF;
10954   else if (Subtarget->isPICStyleStubPIC())
10955     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10956
10957   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10958                                              CP->getAlignment(),
10959                                              CP->getOffset(), OpFlag);
10960   SDLoc DL(CP);
10961   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10962   // With PIC, the address is actually $g + Offset.
10963   if (OpFlag) {
10964     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10965                          DAG.getNode(X86ISD::GlobalBaseReg,
10966                                      SDLoc(), getPointerTy()),
10967                          Result);
10968   }
10969
10970   return Result;
10971 }
10972
10973 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10974   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10975
10976   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10977   // global base reg.
10978   unsigned char OpFlag = 0;
10979   unsigned WrapperKind = X86ISD::Wrapper;
10980   CodeModel::Model M = DAG.getTarget().getCodeModel();
10981
10982   if (Subtarget->isPICStyleRIPRel() &&
10983       (M == CodeModel::Small || M == CodeModel::Kernel))
10984     WrapperKind = X86ISD::WrapperRIP;
10985   else if (Subtarget->isPICStyleGOT())
10986     OpFlag = X86II::MO_GOTOFF;
10987   else if (Subtarget->isPICStyleStubPIC())
10988     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10989
10990   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10991                                           OpFlag);
10992   SDLoc DL(JT);
10993   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10994
10995   // With PIC, the address is actually $g + Offset.
10996   if (OpFlag)
10997     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10998                          DAG.getNode(X86ISD::GlobalBaseReg,
10999                                      SDLoc(), getPointerTy()),
11000                          Result);
11001
11002   return Result;
11003 }
11004
11005 SDValue
11006 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11007   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11008
11009   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11010   // global base reg.
11011   unsigned char OpFlag = 0;
11012   unsigned WrapperKind = X86ISD::Wrapper;
11013   CodeModel::Model M = DAG.getTarget().getCodeModel();
11014
11015   if (Subtarget->isPICStyleRIPRel() &&
11016       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11017     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11018       OpFlag = X86II::MO_GOTPCREL;
11019     WrapperKind = X86ISD::WrapperRIP;
11020   } else if (Subtarget->isPICStyleGOT()) {
11021     OpFlag = X86II::MO_GOT;
11022   } else if (Subtarget->isPICStyleStubPIC()) {
11023     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11024   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11025     OpFlag = X86II::MO_DARWIN_NONLAZY;
11026   }
11027
11028   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11029
11030   SDLoc DL(Op);
11031   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11032
11033   // With PIC, the address is actually $g + Offset.
11034   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11035       !Subtarget->is64Bit()) {
11036     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11037                          DAG.getNode(X86ISD::GlobalBaseReg,
11038                                      SDLoc(), getPointerTy()),
11039                          Result);
11040   }
11041
11042   // For symbols that require a load from a stub to get the address, emit the
11043   // load.
11044   if (isGlobalStubReference(OpFlag))
11045     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11046                          MachinePointerInfo::getGOT(), false, false, false, 0);
11047
11048   return Result;
11049 }
11050
11051 SDValue
11052 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11053   // Create the TargetBlockAddressAddress node.
11054   unsigned char OpFlags =
11055     Subtarget->ClassifyBlockAddressReference();
11056   CodeModel::Model M = DAG.getTarget().getCodeModel();
11057   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11058   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11059   SDLoc dl(Op);
11060   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11061                                              OpFlags);
11062
11063   if (Subtarget->isPICStyleRIPRel() &&
11064       (M == CodeModel::Small || M == CodeModel::Kernel))
11065     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11066   else
11067     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11068
11069   // With PIC, the address is actually $g + Offset.
11070   if (isGlobalRelativeToPICBase(OpFlags)) {
11071     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11072                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11073                          Result);
11074   }
11075
11076   return Result;
11077 }
11078
11079 SDValue
11080 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11081                                       int64_t Offset, SelectionDAG &DAG) const {
11082   // Create the TargetGlobalAddress node, folding in the constant
11083   // offset if it is legal.
11084   unsigned char OpFlags =
11085       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11086   CodeModel::Model M = DAG.getTarget().getCodeModel();
11087   SDValue Result;
11088   if (OpFlags == X86II::MO_NO_FLAG &&
11089       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11090     // A direct static reference to a global.
11091     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11092     Offset = 0;
11093   } else {
11094     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11095   }
11096
11097   if (Subtarget->isPICStyleRIPRel() &&
11098       (M == CodeModel::Small || M == CodeModel::Kernel))
11099     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11100   else
11101     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11102
11103   // With PIC, the address is actually $g + Offset.
11104   if (isGlobalRelativeToPICBase(OpFlags)) {
11105     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11106                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11107                          Result);
11108   }
11109
11110   // For globals that require a load from a stub to get the address, emit the
11111   // load.
11112   if (isGlobalStubReference(OpFlags))
11113     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11114                          MachinePointerInfo::getGOT(), false, false, false, 0);
11115
11116   // If there was a non-zero offset that we didn't fold, create an explicit
11117   // addition for it.
11118   if (Offset != 0)
11119     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11120                          DAG.getConstant(Offset, dl, getPointerTy()));
11121
11122   return Result;
11123 }
11124
11125 SDValue
11126 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11127   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11128   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11129   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11130 }
11131
11132 static SDValue
11133 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11134            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11135            unsigned char OperandFlags, bool LocalDynamic = false) {
11136   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11137   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11138   SDLoc dl(GA);
11139   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11140                                            GA->getValueType(0),
11141                                            GA->getOffset(),
11142                                            OperandFlags);
11143
11144   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11145                                            : X86ISD::TLSADDR;
11146
11147   if (InFlag) {
11148     SDValue Ops[] = { Chain,  TGA, *InFlag };
11149     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11150   } else {
11151     SDValue Ops[]  = { Chain, TGA };
11152     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11153   }
11154
11155   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11156   MFI->setAdjustsStack(true);
11157   MFI->setHasCalls(true);
11158
11159   SDValue Flag = Chain.getValue(1);
11160   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11161 }
11162
11163 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11164 static SDValue
11165 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11166                                 const EVT PtrVT) {
11167   SDValue InFlag;
11168   SDLoc dl(GA);  // ? function entry point might be better
11169   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11170                                    DAG.getNode(X86ISD::GlobalBaseReg,
11171                                                SDLoc(), PtrVT), InFlag);
11172   InFlag = Chain.getValue(1);
11173
11174   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11175 }
11176
11177 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11178 static SDValue
11179 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11180                                 const EVT PtrVT) {
11181   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11182                     X86::RAX, X86II::MO_TLSGD);
11183 }
11184
11185 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11186                                            SelectionDAG &DAG,
11187                                            const EVT PtrVT,
11188                                            bool is64Bit) {
11189   SDLoc dl(GA);
11190
11191   // Get the start address of the TLS block for this module.
11192   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11193       .getInfo<X86MachineFunctionInfo>();
11194   MFI->incNumLocalDynamicTLSAccesses();
11195
11196   SDValue Base;
11197   if (is64Bit) {
11198     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11199                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11200   } else {
11201     SDValue InFlag;
11202     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11203         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11204     InFlag = Chain.getValue(1);
11205     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11206                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11207   }
11208
11209   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11210   // of Base.
11211
11212   // Build x@dtpoff.
11213   unsigned char OperandFlags = X86II::MO_DTPOFF;
11214   unsigned WrapperKind = X86ISD::Wrapper;
11215   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11216                                            GA->getValueType(0),
11217                                            GA->getOffset(), OperandFlags);
11218   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11219
11220   // Add x@dtpoff with the base.
11221   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11222 }
11223
11224 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11225 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11226                                    const EVT PtrVT, TLSModel::Model model,
11227                                    bool is64Bit, bool isPIC) {
11228   SDLoc dl(GA);
11229
11230   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11231   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11232                                                          is64Bit ? 257 : 256));
11233
11234   SDValue ThreadPointer =
11235       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11236                   MachinePointerInfo(Ptr), false, false, false, 0);
11237
11238   unsigned char OperandFlags = 0;
11239   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11240   // initialexec.
11241   unsigned WrapperKind = X86ISD::Wrapper;
11242   if (model == TLSModel::LocalExec) {
11243     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11244   } else if (model == TLSModel::InitialExec) {
11245     if (is64Bit) {
11246       OperandFlags = X86II::MO_GOTTPOFF;
11247       WrapperKind = X86ISD::WrapperRIP;
11248     } else {
11249       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11250     }
11251   } else {
11252     llvm_unreachable("Unexpected model");
11253   }
11254
11255   // emit "addl x@ntpoff,%eax" (local exec)
11256   // or "addl x@indntpoff,%eax" (initial exec)
11257   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11258   SDValue TGA =
11259       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11260                                  GA->getOffset(), OperandFlags);
11261   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11262
11263   if (model == TLSModel::InitialExec) {
11264     if (isPIC && !is64Bit) {
11265       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11266                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11267                            Offset);
11268     }
11269
11270     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11271                          MachinePointerInfo::getGOT(), false, false, false, 0);
11272   }
11273
11274   // The address of the thread local variable is the add of the thread
11275   // pointer with the offset of the variable.
11276   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11277 }
11278
11279 SDValue
11280 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11281
11282   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11283   const GlobalValue *GV = GA->getGlobal();
11284
11285   if (Subtarget->isTargetELF()) {
11286     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11287
11288     switch (model) {
11289       case TLSModel::GeneralDynamic:
11290         if (Subtarget->is64Bit())
11291           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11292         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11293       case TLSModel::LocalDynamic:
11294         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11295                                            Subtarget->is64Bit());
11296       case TLSModel::InitialExec:
11297       case TLSModel::LocalExec:
11298         return LowerToTLSExecModel(
11299             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11300             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11301     }
11302     llvm_unreachable("Unknown TLS model.");
11303   }
11304
11305   if (Subtarget->isTargetDarwin()) {
11306     // Darwin only has one model of TLS.  Lower to that.
11307     unsigned char OpFlag = 0;
11308     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11309                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11310
11311     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11312     // global base reg.
11313     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11314                  !Subtarget->is64Bit();
11315     if (PIC32)
11316       OpFlag = X86II::MO_TLVP_PIC_BASE;
11317     else
11318       OpFlag = X86II::MO_TLVP;
11319     SDLoc DL(Op);
11320     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11321                                                 GA->getValueType(0),
11322                                                 GA->getOffset(), OpFlag);
11323     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11324
11325     // With PIC32, the address is actually $g + Offset.
11326     if (PIC32)
11327       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11328                            DAG.getNode(X86ISD::GlobalBaseReg,
11329                                        SDLoc(), getPointerTy()),
11330                            Offset);
11331
11332     // Lowering the machine isd will make sure everything is in the right
11333     // location.
11334     SDValue Chain = DAG.getEntryNode();
11335     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11336     SDValue Args[] = { Chain, Offset };
11337     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11338
11339     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11340     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11341     MFI->setAdjustsStack(true);
11342
11343     // And our return value (tls address) is in the standard call return value
11344     // location.
11345     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11346     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11347                               Chain.getValue(1));
11348   }
11349
11350   if (Subtarget->isTargetKnownWindowsMSVC() ||
11351       Subtarget->isTargetWindowsGNU()) {
11352     // Just use the implicit TLS architecture
11353     // Need to generate someting similar to:
11354     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11355     //                                  ; from TEB
11356     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11357     //   mov     rcx, qword [rdx+rcx*8]
11358     //   mov     eax, .tls$:tlsvar
11359     //   [rax+rcx] contains the address
11360     // Windows 64bit: gs:0x58
11361     // Windows 32bit: fs:__tls_array
11362
11363     SDLoc dl(GA);
11364     SDValue Chain = DAG.getEntryNode();
11365
11366     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11367     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11368     // use its literal value of 0x2C.
11369     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11370                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11371                                                              256)
11372                                         : Type::getInt32PtrTy(*DAG.getContext(),
11373                                                               257));
11374
11375     SDValue TlsArray =
11376         Subtarget->is64Bit()
11377             ? DAG.getIntPtrConstant(0x58, dl)
11378             : (Subtarget->isTargetWindowsGNU()
11379                    ? DAG.getIntPtrConstant(0x2C, dl)
11380                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11381
11382     SDValue ThreadPointer =
11383         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11384                     MachinePointerInfo(Ptr), false, false, false, 0);
11385
11386     // Load the _tls_index variable
11387     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11388     if (Subtarget->is64Bit())
11389       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11390                            IDX, MachinePointerInfo(), MVT::i32,
11391                            false, false, false, 0);
11392     else
11393       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11394                         false, false, false, 0);
11395
11396     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11397                                     getPointerTy());
11398     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11399
11400     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11401     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11402                       false, false, false, 0);
11403
11404     // Get the offset of start of .tls section
11405     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11406                                              GA->getValueType(0),
11407                                              GA->getOffset(), X86II::MO_SECREL);
11408     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11409
11410     // The address of the thread local variable is the add of the thread
11411     // pointer with the offset of the variable.
11412     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11413   }
11414
11415   llvm_unreachable("TLS not implemented for this target.");
11416 }
11417
11418 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11419 /// and take a 2 x i32 value to shift plus a shift amount.
11420 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11421   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11422   MVT VT = Op.getSimpleValueType();
11423   unsigned VTBits = VT.getSizeInBits();
11424   SDLoc dl(Op);
11425   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11426   SDValue ShOpLo = Op.getOperand(0);
11427   SDValue ShOpHi = Op.getOperand(1);
11428   SDValue ShAmt  = Op.getOperand(2);
11429   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11430   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11431   // during isel.
11432   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11433                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11434   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11435                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11436                        : DAG.getConstant(0, dl, VT);
11437
11438   SDValue Tmp2, Tmp3;
11439   if (Op.getOpcode() == ISD::SHL_PARTS) {
11440     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11441     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11442   } else {
11443     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11444     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11445   }
11446
11447   // If the shift amount is larger or equal than the width of a part we can't
11448   // rely on the results of shld/shrd. Insert a test and select the appropriate
11449   // values for large shift amounts.
11450   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11451                                 DAG.getConstant(VTBits, dl, MVT::i8));
11452   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11453                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11454
11455   SDValue Hi, Lo;
11456   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11457   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11458   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11459
11460   if (Op.getOpcode() == ISD::SHL_PARTS) {
11461     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11462     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11463   } else {
11464     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11465     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11466   }
11467
11468   SDValue Ops[2] = { Lo, Hi };
11469   return DAG.getMergeValues(Ops, dl);
11470 }
11471
11472 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11473                                            SelectionDAG &DAG) const {
11474   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11475   SDLoc dl(Op);
11476
11477   if (SrcVT.isVector()) {
11478     if (SrcVT.getVectorElementType() == MVT::i1) {
11479       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11480       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11481                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11482                                      Op.getOperand(0)));
11483     }
11484     return SDValue();
11485   }
11486
11487   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11488          "Unknown SINT_TO_FP to lower!");
11489
11490   // These are really Legal; return the operand so the caller accepts it as
11491   // Legal.
11492   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11493     return Op;
11494   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11495       Subtarget->is64Bit()) {
11496     return Op;
11497   }
11498
11499   unsigned Size = SrcVT.getSizeInBits()/8;
11500   MachineFunction &MF = DAG.getMachineFunction();
11501   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11502   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11503   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11504                                StackSlot,
11505                                MachinePointerInfo::getFixedStack(SSFI),
11506                                false, false, 0);
11507   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11508 }
11509
11510 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11511                                      SDValue StackSlot,
11512                                      SelectionDAG &DAG) const {
11513   // Build the FILD
11514   SDLoc DL(Op);
11515   SDVTList Tys;
11516   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11517   if (useSSE)
11518     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11519   else
11520     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11521
11522   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11523
11524   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11525   MachineMemOperand *MMO;
11526   if (FI) {
11527     int SSFI = FI->getIndex();
11528     MMO =
11529       DAG.getMachineFunction()
11530       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11531                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11532   } else {
11533     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11534     StackSlot = StackSlot.getOperand(1);
11535   }
11536   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11537   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11538                                            X86ISD::FILD, DL,
11539                                            Tys, Ops, SrcVT, MMO);
11540
11541   if (useSSE) {
11542     Chain = Result.getValue(1);
11543     SDValue InFlag = Result.getValue(2);
11544
11545     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11546     // shouldn't be necessary except that RFP cannot be live across
11547     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11548     MachineFunction &MF = DAG.getMachineFunction();
11549     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11550     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11551     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11552     Tys = DAG.getVTList(MVT::Other);
11553     SDValue Ops[] = {
11554       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11555     };
11556     MachineMemOperand *MMO =
11557       DAG.getMachineFunction()
11558       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11559                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11560
11561     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11562                                     Ops, Op.getValueType(), MMO);
11563     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11564                          MachinePointerInfo::getFixedStack(SSFI),
11565                          false, false, false, 0);
11566   }
11567
11568   return Result;
11569 }
11570
11571 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11572 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11573                                                SelectionDAG &DAG) const {
11574   // This algorithm is not obvious. Here it is what we're trying to output:
11575   /*
11576      movq       %rax,  %xmm0
11577      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11578      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11579      #ifdef __SSE3__
11580        haddpd   %xmm0, %xmm0
11581      #else
11582        pshufd   $0x4e, %xmm0, %xmm1
11583        addpd    %xmm1, %xmm0
11584      #endif
11585   */
11586
11587   SDLoc dl(Op);
11588   LLVMContext *Context = DAG.getContext();
11589
11590   // Build some magic constants.
11591   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11592   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11593   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11594
11595   SmallVector<Constant*,2> CV1;
11596   CV1.push_back(
11597     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11598                                       APInt(64, 0x4330000000000000ULL))));
11599   CV1.push_back(
11600     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11601                                       APInt(64, 0x4530000000000000ULL))));
11602   Constant *C1 = ConstantVector::get(CV1);
11603   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11604
11605   // Load the 64-bit value into an XMM register.
11606   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11607                             Op.getOperand(0));
11608   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11609                               MachinePointerInfo::getConstantPool(),
11610                               false, false, false, 16);
11611   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11612                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11613                               CLod0);
11614
11615   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11616                               MachinePointerInfo::getConstantPool(),
11617                               false, false, false, 16);
11618   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11619   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11620   SDValue Result;
11621
11622   if (Subtarget->hasSSE3()) {
11623     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11624     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11625   } else {
11626     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11627     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11628                                            S2F, 0x4E, DAG);
11629     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11630                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11631                          Sub);
11632   }
11633
11634   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11635                      DAG.getIntPtrConstant(0, dl));
11636 }
11637
11638 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11639 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11640                                                SelectionDAG &DAG) const {
11641   SDLoc dl(Op);
11642   // FP constant to bias correct the final result.
11643   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11644                                    MVT::f64);
11645
11646   // Load the 32-bit value into an XMM register.
11647   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11648                              Op.getOperand(0));
11649
11650   // Zero out the upper parts of the register.
11651   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11652
11653   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11654                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11655                      DAG.getIntPtrConstant(0, dl));
11656
11657   // Or the load with the bias.
11658   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11659                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11660                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11661                                                    MVT::v2f64, Load)),
11662                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11663                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11664                                                    MVT::v2f64, Bias)));
11665   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11666                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11667                    DAG.getIntPtrConstant(0, dl));
11668
11669   // Subtract the bias.
11670   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11671
11672   // Handle final rounding.
11673   EVT DestVT = Op.getValueType();
11674
11675   if (DestVT.bitsLT(MVT::f64))
11676     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11677                        DAG.getIntPtrConstant(0, dl));
11678   if (DestVT.bitsGT(MVT::f64))
11679     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11680
11681   // Handle final rounding.
11682   return Sub;
11683 }
11684
11685 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11686                                      const X86Subtarget &Subtarget) {
11687   // The algorithm is the following:
11688   // #ifdef __SSE4_1__
11689   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11690   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11691   //                                 (uint4) 0x53000000, 0xaa);
11692   // #else
11693   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11694   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11695   // #endif
11696   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11697   //     return (float4) lo + fhi;
11698
11699   SDLoc DL(Op);
11700   SDValue V = Op->getOperand(0);
11701   EVT VecIntVT = V.getValueType();
11702   bool Is128 = VecIntVT == MVT::v4i32;
11703   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11704   // If we convert to something else than the supported type, e.g., to v4f64,
11705   // abort early.
11706   if (VecFloatVT != Op->getValueType(0))
11707     return SDValue();
11708
11709   unsigned NumElts = VecIntVT.getVectorNumElements();
11710   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11711          "Unsupported custom type");
11712   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11713
11714   // In the #idef/#else code, we have in common:
11715   // - The vector of constants:
11716   // -- 0x4b000000
11717   // -- 0x53000000
11718   // - A shift:
11719   // -- v >> 16
11720
11721   // Create the splat vector for 0x4b000000.
11722   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11723   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11724                            CstLow, CstLow, CstLow, CstLow};
11725   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11726                                   makeArrayRef(&CstLowArray[0], NumElts));
11727   // Create the splat vector for 0x53000000.
11728   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11729   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11730                             CstHigh, CstHigh, CstHigh, CstHigh};
11731   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11732                                    makeArrayRef(&CstHighArray[0], NumElts));
11733
11734   // Create the right shift.
11735   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11736   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11737                              CstShift, CstShift, CstShift, CstShift};
11738   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11739                                     makeArrayRef(&CstShiftArray[0], NumElts));
11740   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11741
11742   SDValue Low, High;
11743   if (Subtarget.hasSSE41()) {
11744     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11745     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11746     SDValue VecCstLowBitcast =
11747         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11748     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11749     // Low will be bitcasted right away, so do not bother bitcasting back to its
11750     // original type.
11751     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11752                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11753     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11754     //                                 (uint4) 0x53000000, 0xaa);
11755     SDValue VecCstHighBitcast =
11756         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11757     SDValue VecShiftBitcast =
11758         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11759     // High will be bitcasted right away, so do not bother bitcasting back to
11760     // its original type.
11761     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11762                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11763   } else {
11764     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11765     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11766                                      CstMask, CstMask, CstMask);
11767     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11768     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11769     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11770
11771     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11772     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11773   }
11774
11775   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11776   SDValue CstFAdd = DAG.getConstantFP(
11777       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11778   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11779                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11780   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11781                                    makeArrayRef(&CstFAddArray[0], NumElts));
11782
11783   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11784   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11785   SDValue FHigh =
11786       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11787   //     return (float4) lo + fhi;
11788   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11789   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11790 }
11791
11792 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11793                                                SelectionDAG &DAG) const {
11794   SDValue N0 = Op.getOperand(0);
11795   MVT SVT = N0.getSimpleValueType();
11796   SDLoc dl(Op);
11797
11798   switch (SVT.SimpleTy) {
11799   default:
11800     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11801   case MVT::v4i8:
11802   case MVT::v4i16:
11803   case MVT::v8i8:
11804   case MVT::v8i16: {
11805     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11806     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11807                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11808   }
11809   case MVT::v4i32:
11810   case MVT::v8i32:
11811     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11812   case MVT::v16i8:
11813   case MVT::v16i16:
11814     if (Subtarget->hasAVX512())
11815       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11816                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11817   }
11818   llvm_unreachable(nullptr);
11819 }
11820
11821 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11822                                            SelectionDAG &DAG) const {
11823   SDValue N0 = Op.getOperand(0);
11824   SDLoc dl(Op);
11825
11826   if (Op.getValueType().isVector())
11827     return lowerUINT_TO_FP_vec(Op, DAG);
11828
11829   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11830   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11831   // the optimization here.
11832   if (DAG.SignBitIsZero(N0))
11833     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11834
11835   MVT SrcVT = N0.getSimpleValueType();
11836   MVT DstVT = Op.getSimpleValueType();
11837   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11838     return LowerUINT_TO_FP_i64(Op, DAG);
11839   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11840     return LowerUINT_TO_FP_i32(Op, DAG);
11841   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11842     return SDValue();
11843
11844   // Make a 64-bit buffer, and use it to build an FILD.
11845   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11846   if (SrcVT == MVT::i32) {
11847     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11848     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11849                                      getPointerTy(), StackSlot, WordOff);
11850     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11851                                   StackSlot, MachinePointerInfo(),
11852                                   false, false, 0);
11853     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11854                                   OffsetSlot, MachinePointerInfo(),
11855                                   false, false, 0);
11856     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11857     return Fild;
11858   }
11859
11860   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11861   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11862                                StackSlot, MachinePointerInfo(),
11863                                false, false, 0);
11864   // For i64 source, we need to add the appropriate power of 2 if the input
11865   // was negative.  This is the same as the optimization in
11866   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11867   // we must be careful to do the computation in x87 extended precision, not
11868   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11869   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11870   MachineMemOperand *MMO =
11871     DAG.getMachineFunction()
11872     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11873                           MachineMemOperand::MOLoad, 8, 8);
11874
11875   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11876   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11877   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11878                                          MVT::i64, MMO);
11879
11880   APInt FF(32, 0x5F800000ULL);
11881
11882   // Check whether the sign bit is set.
11883   SDValue SignSet = DAG.getSetCC(dl,
11884                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11885                                  Op.getOperand(0),
11886                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11887
11888   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11889   SDValue FudgePtr = DAG.getConstantPool(
11890                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11891                                          getPointerTy());
11892
11893   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11894   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11895   SDValue Four = DAG.getIntPtrConstant(4, dl);
11896   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11897                                Zero, Four);
11898   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11899
11900   // Load the value out, extending it from f32 to f80.
11901   // FIXME: Avoid the extend by constructing the right constant pool?
11902   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11903                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11904                                  MVT::f32, false, false, false, 4);
11905   // Extend everything to 80 bits to force it to be done on x87.
11906   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11907   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11908                      DAG.getIntPtrConstant(0, dl));
11909 }
11910
11911 std::pair<SDValue,SDValue>
11912 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11913                                     bool IsSigned, bool IsReplace) const {
11914   SDLoc DL(Op);
11915
11916   EVT DstTy = Op.getValueType();
11917
11918   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11919     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11920     DstTy = MVT::i64;
11921   }
11922
11923   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11924          DstTy.getSimpleVT() >= MVT::i16 &&
11925          "Unknown FP_TO_INT to lower!");
11926
11927   // These are really Legal.
11928   if (DstTy == MVT::i32 &&
11929       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11930     return std::make_pair(SDValue(), SDValue());
11931   if (Subtarget->is64Bit() &&
11932       DstTy == MVT::i64 &&
11933       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11934     return std::make_pair(SDValue(), SDValue());
11935
11936   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11937   // stack slot, or into the FTOL runtime function.
11938   MachineFunction &MF = DAG.getMachineFunction();
11939   unsigned MemSize = DstTy.getSizeInBits()/8;
11940   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11941   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11942
11943   unsigned Opc;
11944   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11945     Opc = X86ISD::WIN_FTOL;
11946   else
11947     switch (DstTy.getSimpleVT().SimpleTy) {
11948     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11949     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11950     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11951     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11952     }
11953
11954   SDValue Chain = DAG.getEntryNode();
11955   SDValue Value = Op.getOperand(0);
11956   EVT TheVT = Op.getOperand(0).getValueType();
11957   // FIXME This causes a redundant load/store if the SSE-class value is already
11958   // in memory, such as if it is on the callstack.
11959   if (isScalarFPTypeInSSEReg(TheVT)) {
11960     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11961     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11962                          MachinePointerInfo::getFixedStack(SSFI),
11963                          false, false, 0);
11964     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11965     SDValue Ops[] = {
11966       Chain, StackSlot, DAG.getValueType(TheVT)
11967     };
11968
11969     MachineMemOperand *MMO =
11970       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11971                               MachineMemOperand::MOLoad, MemSize, MemSize);
11972     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11973     Chain = Value.getValue(1);
11974     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11975     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11976   }
11977
11978   MachineMemOperand *MMO =
11979     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11980                             MachineMemOperand::MOStore, MemSize, MemSize);
11981
11982   if (Opc != X86ISD::WIN_FTOL) {
11983     // Build the FP_TO_INT*_IN_MEM
11984     SDValue Ops[] = { Chain, Value, StackSlot };
11985     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11986                                            Ops, DstTy, MMO);
11987     return std::make_pair(FIST, StackSlot);
11988   } else {
11989     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11990       DAG.getVTList(MVT::Other, MVT::Glue),
11991       Chain, Value);
11992     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11993       MVT::i32, ftol.getValue(1));
11994     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11995       MVT::i32, eax.getValue(2));
11996     SDValue Ops[] = { eax, edx };
11997     SDValue pair = IsReplace
11998       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11999       : DAG.getMergeValues(Ops, DL);
12000     return std::make_pair(pair, SDValue());
12001   }
12002 }
12003
12004 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12005                               const X86Subtarget *Subtarget) {
12006   MVT VT = Op->getSimpleValueType(0);
12007   SDValue In = Op->getOperand(0);
12008   MVT InVT = In.getSimpleValueType();
12009   SDLoc dl(Op);
12010
12011   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12012     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12013
12014   // Optimize vectors in AVX mode:
12015   //
12016   //   v8i16 -> v8i32
12017   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12018   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12019   //   Concat upper and lower parts.
12020   //
12021   //   v4i32 -> v4i64
12022   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12023   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12024   //   Concat upper and lower parts.
12025   //
12026
12027   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12028       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12029       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12030     return SDValue();
12031
12032   if (Subtarget->hasInt256())
12033     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12034
12035   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12036   SDValue Undef = DAG.getUNDEF(InVT);
12037   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12038   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12039   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12040
12041   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12042                              VT.getVectorNumElements()/2);
12043
12044   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12045   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12046
12047   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12048 }
12049
12050 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12051                                         SelectionDAG &DAG) {
12052   MVT VT = Op->getSimpleValueType(0);
12053   SDValue In = Op->getOperand(0);
12054   MVT InVT = In.getSimpleValueType();
12055   SDLoc DL(Op);
12056   unsigned int NumElts = VT.getVectorNumElements();
12057   if (NumElts != 8 && NumElts != 16)
12058     return SDValue();
12059
12060   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12061     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12062
12063   assert(InVT.getVectorElementType() == MVT::i1);
12064   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12065   SDValue One =
12066    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12067   SDValue Zero =
12068    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12069
12070   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12071   if (VT.is512BitVector())
12072     return V;
12073   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12074 }
12075
12076 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12077                                SelectionDAG &DAG) {
12078   if (Subtarget->hasFp256()) {
12079     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12080     if (Res.getNode())
12081       return Res;
12082   }
12083
12084   return SDValue();
12085 }
12086
12087 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12088                                 SelectionDAG &DAG) {
12089   SDLoc DL(Op);
12090   MVT VT = Op.getSimpleValueType();
12091   SDValue In = Op.getOperand(0);
12092   MVT SVT = In.getSimpleValueType();
12093
12094   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12095     return LowerZERO_EXTEND_AVX512(Op, DAG);
12096
12097   if (Subtarget->hasFp256()) {
12098     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12099     if (Res.getNode())
12100       return Res;
12101   }
12102
12103   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12104          VT.getVectorNumElements() != SVT.getVectorNumElements());
12105   return SDValue();
12106 }
12107
12108 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12109   SDLoc DL(Op);
12110   MVT VT = Op.getSimpleValueType();
12111   SDValue In = Op.getOperand(0);
12112   MVT InVT = In.getSimpleValueType();
12113
12114   if (VT == MVT::i1) {
12115     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12116            "Invalid scalar TRUNCATE operation");
12117     if (InVT.getSizeInBits() >= 32)
12118       return SDValue();
12119     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12120     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12121   }
12122   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12123          "Invalid TRUNCATE operation");
12124
12125   // move vector to mask - truncate solution for SKX
12126   if (VT.getVectorElementType() == MVT::i1) {
12127     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12128         Subtarget->hasBWI())
12129       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12130     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12131         && InVT.getScalarSizeInBits() <= 16 &&
12132         Subtarget->hasBWI() && Subtarget->hasVLX())
12133       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12134     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12135         Subtarget->hasDQI())
12136       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12137     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12138         && InVT.getScalarSizeInBits() >= 32 &&
12139         Subtarget->hasDQI() && Subtarget->hasVLX())
12140       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12141   }
12142   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12143     if (VT.getVectorElementType().getSizeInBits() >=8)
12144       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12145
12146     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12147     unsigned NumElts = InVT.getVectorNumElements();
12148     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12149     if (InVT.getSizeInBits() < 512) {
12150       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12151       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12152       InVT = ExtVT;
12153     }
12154
12155     SDValue OneV =
12156      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12157     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12158     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12159   }
12160
12161   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12162     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12163     if (Subtarget->hasInt256()) {
12164       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12165       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12166       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12167                                 ShufMask);
12168       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12169                          DAG.getIntPtrConstant(0, DL));
12170     }
12171
12172     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12173                                DAG.getIntPtrConstant(0, DL));
12174     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12175                                DAG.getIntPtrConstant(2, DL));
12176     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12177     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12178     static const int ShufMask[] = {0, 2, 4, 6};
12179     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12180   }
12181
12182   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12183     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12184     if (Subtarget->hasInt256()) {
12185       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12186
12187       SmallVector<SDValue,32> pshufbMask;
12188       for (unsigned i = 0; i < 2; ++i) {
12189         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12190         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12191         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12192         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12193         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12194         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12195         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12196         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12197         for (unsigned j = 0; j < 8; ++j)
12198           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12199       }
12200       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12201       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12202       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12203
12204       static const int ShufMask[] = {0,  2,  -1,  -1};
12205       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12206                                 &ShufMask[0]);
12207       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12208                        DAG.getIntPtrConstant(0, DL));
12209       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12210     }
12211
12212     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12213                                DAG.getIntPtrConstant(0, DL));
12214
12215     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12216                                DAG.getIntPtrConstant(4, DL));
12217
12218     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12219     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12220
12221     // The PSHUFB mask:
12222     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12223                                    -1, -1, -1, -1, -1, -1, -1, -1};
12224
12225     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12226     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12227     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12228
12229     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12230     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12231
12232     // The MOVLHPS Mask:
12233     static const int ShufMask2[] = {0, 1, 4, 5};
12234     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12235     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12236   }
12237
12238   // Handle truncation of V256 to V128 using shuffles.
12239   if (!VT.is128BitVector() || !InVT.is256BitVector())
12240     return SDValue();
12241
12242   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12243
12244   unsigned NumElems = VT.getVectorNumElements();
12245   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12246
12247   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12248   // Prepare truncation shuffle mask
12249   for (unsigned i = 0; i != NumElems; ++i)
12250     MaskVec[i] = i * 2;
12251   SDValue V = DAG.getVectorShuffle(NVT, DL,
12252                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12253                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12254   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12255                      DAG.getIntPtrConstant(0, DL));
12256 }
12257
12258 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12259                                            SelectionDAG &DAG) const {
12260   assert(!Op.getSimpleValueType().isVector());
12261
12262   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12263     /*IsSigned=*/ true, /*IsReplace=*/ false);
12264   SDValue FIST = Vals.first, StackSlot = Vals.second;
12265   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12266   if (!FIST.getNode()) return Op;
12267
12268   if (StackSlot.getNode())
12269     // Load the result.
12270     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12271                        FIST, StackSlot, MachinePointerInfo(),
12272                        false, false, false, 0);
12273
12274   // The node is the result.
12275   return FIST;
12276 }
12277
12278 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12279                                            SelectionDAG &DAG) const {
12280   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12281     /*IsSigned=*/ false, /*IsReplace=*/ false);
12282   SDValue FIST = Vals.first, StackSlot = Vals.second;
12283   assert(FIST.getNode() && "Unexpected failure");
12284
12285   if (StackSlot.getNode())
12286     // Load the result.
12287     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12288                        FIST, StackSlot, MachinePointerInfo(),
12289                        false, false, false, 0);
12290
12291   // The node is the result.
12292   return FIST;
12293 }
12294
12295 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12296   SDLoc DL(Op);
12297   MVT VT = Op.getSimpleValueType();
12298   SDValue In = Op.getOperand(0);
12299   MVT SVT = In.getSimpleValueType();
12300
12301   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12302
12303   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12304                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12305                                  In, DAG.getUNDEF(SVT)));
12306 }
12307
12308 /// The only differences between FABS and FNEG are the mask and the logic op.
12309 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12310 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12311   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12312          "Wrong opcode for lowering FABS or FNEG.");
12313
12314   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12315
12316   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12317   // into an FNABS. We'll lower the FABS after that if it is still in use.
12318   if (IsFABS)
12319     for (SDNode *User : Op->uses())
12320       if (User->getOpcode() == ISD::FNEG)
12321         return Op;
12322
12323   SDValue Op0 = Op.getOperand(0);
12324   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12325
12326   SDLoc dl(Op);
12327   MVT VT = Op.getSimpleValueType();
12328   // Assume scalar op for initialization; update for vector if needed.
12329   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12330   // generate a 16-byte vector constant and logic op even for the scalar case.
12331   // Using a 16-byte mask allows folding the load of the mask with
12332   // the logic op, so it can save (~4 bytes) on code size.
12333   MVT EltVT = VT;
12334   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12335   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12336   // decide if we should generate a 16-byte constant mask when we only need 4 or
12337   // 8 bytes for the scalar case.
12338   if (VT.isVector()) {
12339     EltVT = VT.getVectorElementType();
12340     NumElts = VT.getVectorNumElements();
12341   }
12342
12343   unsigned EltBits = EltVT.getSizeInBits();
12344   LLVMContext *Context = DAG.getContext();
12345   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12346   APInt MaskElt =
12347     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12348   Constant *C = ConstantInt::get(*Context, MaskElt);
12349   C = ConstantVector::getSplat(NumElts, C);
12350   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12351   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12352   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12353   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12354                              MachinePointerInfo::getConstantPool(),
12355                              false, false, false, Alignment);
12356
12357   if (VT.isVector()) {
12358     // For a vector, cast operands to a vector type, perform the logic op,
12359     // and cast the result back to the original value type.
12360     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12361     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12362     SDValue Operand = IsFNABS ?
12363       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12364       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12365     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12366     return DAG.getNode(ISD::BITCAST, dl, VT,
12367                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12368   }
12369
12370   // If not vector, then scalar.
12371   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12372   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12373   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12374 }
12375
12376 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12377   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12378   LLVMContext *Context = DAG.getContext();
12379   SDValue Op0 = Op.getOperand(0);
12380   SDValue Op1 = Op.getOperand(1);
12381   SDLoc dl(Op);
12382   MVT VT = Op.getSimpleValueType();
12383   MVT SrcVT = Op1.getSimpleValueType();
12384
12385   // If second operand is smaller, extend it first.
12386   if (SrcVT.bitsLT(VT)) {
12387     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12388     SrcVT = VT;
12389   }
12390   // And if it is bigger, shrink it first.
12391   if (SrcVT.bitsGT(VT)) {
12392     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12393     SrcVT = VT;
12394   }
12395
12396   // At this point the operands and the result should have the same
12397   // type, and that won't be f80 since that is not custom lowered.
12398
12399   const fltSemantics &Sem =
12400       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12401   const unsigned SizeInBits = VT.getSizeInBits();
12402
12403   SmallVector<Constant *, 4> CV(
12404       VT == MVT::f64 ? 2 : 4,
12405       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12406
12407   // First, clear all bits but the sign bit from the second operand (sign).
12408   CV[0] = ConstantFP::get(*Context,
12409                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12410   Constant *C = ConstantVector::get(CV);
12411   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12412   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12413                               MachinePointerInfo::getConstantPool(),
12414                               false, false, false, 16);
12415   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12416
12417   // Next, clear the sign bit from the first operand (magnitude).
12418   // If it's a constant, we can clear it here.
12419   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12420     APFloat APF = Op0CN->getValueAPF();
12421     // If the magnitude is a positive zero, the sign bit alone is enough.
12422     if (APF.isPosZero())
12423       return SignBit;
12424     APF.clearSign();
12425     CV[0] = ConstantFP::get(*Context, APF);
12426   } else {
12427     CV[0] = ConstantFP::get(
12428         *Context,
12429         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12430   }
12431   C = ConstantVector::get(CV);
12432   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12433   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12434                             MachinePointerInfo::getConstantPool(),
12435                             false, false, false, 16);
12436   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12437   if (!isa<ConstantFPSDNode>(Op0))
12438     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12439
12440   // OR the magnitude value with the sign bit.
12441   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12442 }
12443
12444 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12445   SDValue N0 = Op.getOperand(0);
12446   SDLoc dl(Op);
12447   MVT VT = Op.getSimpleValueType();
12448
12449   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12450   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12451                                   DAG.getConstant(1, dl, VT));
12452   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12453 }
12454
12455 // Check whether an OR'd tree is PTEST-able.
12456 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12457                                       SelectionDAG &DAG) {
12458   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12459
12460   if (!Subtarget->hasSSE41())
12461     return SDValue();
12462
12463   if (!Op->hasOneUse())
12464     return SDValue();
12465
12466   SDNode *N = Op.getNode();
12467   SDLoc DL(N);
12468
12469   SmallVector<SDValue, 8> Opnds;
12470   DenseMap<SDValue, unsigned> VecInMap;
12471   SmallVector<SDValue, 8> VecIns;
12472   EVT VT = MVT::Other;
12473
12474   // Recognize a special case where a vector is casted into wide integer to
12475   // test all 0s.
12476   Opnds.push_back(N->getOperand(0));
12477   Opnds.push_back(N->getOperand(1));
12478
12479   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12480     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12481     // BFS traverse all OR'd operands.
12482     if (I->getOpcode() == ISD::OR) {
12483       Opnds.push_back(I->getOperand(0));
12484       Opnds.push_back(I->getOperand(1));
12485       // Re-evaluate the number of nodes to be traversed.
12486       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12487       continue;
12488     }
12489
12490     // Quit if a non-EXTRACT_VECTOR_ELT
12491     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12492       return SDValue();
12493
12494     // Quit if without a constant index.
12495     SDValue Idx = I->getOperand(1);
12496     if (!isa<ConstantSDNode>(Idx))
12497       return SDValue();
12498
12499     SDValue ExtractedFromVec = I->getOperand(0);
12500     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12501     if (M == VecInMap.end()) {
12502       VT = ExtractedFromVec.getValueType();
12503       // Quit if not 128/256-bit vector.
12504       if (!VT.is128BitVector() && !VT.is256BitVector())
12505         return SDValue();
12506       // Quit if not the same type.
12507       if (VecInMap.begin() != VecInMap.end() &&
12508           VT != VecInMap.begin()->first.getValueType())
12509         return SDValue();
12510       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12511       VecIns.push_back(ExtractedFromVec);
12512     }
12513     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12514   }
12515
12516   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12517          "Not extracted from 128-/256-bit vector.");
12518
12519   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12520
12521   for (DenseMap<SDValue, unsigned>::const_iterator
12522         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12523     // Quit if not all elements are used.
12524     if (I->second != FullMask)
12525       return SDValue();
12526   }
12527
12528   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12529
12530   // Cast all vectors into TestVT for PTEST.
12531   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12532     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12533
12534   // If more than one full vectors are evaluated, OR them first before PTEST.
12535   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12536     // Each iteration will OR 2 nodes and append the result until there is only
12537     // 1 node left, i.e. the final OR'd value of all vectors.
12538     SDValue LHS = VecIns[Slot];
12539     SDValue RHS = VecIns[Slot + 1];
12540     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12541   }
12542
12543   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12544                      VecIns.back(), VecIns.back());
12545 }
12546
12547 /// \brief return true if \c Op has a use that doesn't just read flags.
12548 static bool hasNonFlagsUse(SDValue Op) {
12549   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12550        ++UI) {
12551     SDNode *User = *UI;
12552     unsigned UOpNo = UI.getOperandNo();
12553     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12554       // Look pass truncate.
12555       UOpNo = User->use_begin().getOperandNo();
12556       User = *User->use_begin();
12557     }
12558
12559     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12560         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12561       return true;
12562   }
12563   return false;
12564 }
12565
12566 /// Emit nodes that will be selected as "test Op0,Op0", or something
12567 /// equivalent.
12568 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12569                                     SelectionDAG &DAG) const {
12570   if (Op.getValueType() == MVT::i1) {
12571     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12572     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12573                        DAG.getConstant(0, dl, MVT::i8));
12574   }
12575   // CF and OF aren't always set the way we want. Determine which
12576   // of these we need.
12577   bool NeedCF = false;
12578   bool NeedOF = false;
12579   switch (X86CC) {
12580   default: break;
12581   case X86::COND_A: case X86::COND_AE:
12582   case X86::COND_B: case X86::COND_BE:
12583     NeedCF = true;
12584     break;
12585   case X86::COND_G: case X86::COND_GE:
12586   case X86::COND_L: case X86::COND_LE:
12587   case X86::COND_O: case X86::COND_NO: {
12588     // Check if we really need to set the
12589     // Overflow flag. If NoSignedWrap is present
12590     // that is not actually needed.
12591     switch (Op->getOpcode()) {
12592     case ISD::ADD:
12593     case ISD::SUB:
12594     case ISD::MUL:
12595     case ISD::SHL: {
12596       const BinaryWithFlagsSDNode *BinNode =
12597           cast<BinaryWithFlagsSDNode>(Op.getNode());
12598       if (BinNode->Flags.hasNoSignedWrap())
12599         break;
12600     }
12601     default:
12602       NeedOF = true;
12603       break;
12604     }
12605     break;
12606   }
12607   }
12608   // See if we can use the EFLAGS value from the operand instead of
12609   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12610   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12611   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12612     // Emit a CMP with 0, which is the TEST pattern.
12613     //if (Op.getValueType() == MVT::i1)
12614     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12615     //                     DAG.getConstant(0, MVT::i1));
12616     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12617                        DAG.getConstant(0, dl, Op.getValueType()));
12618   }
12619   unsigned Opcode = 0;
12620   unsigned NumOperands = 0;
12621
12622   // Truncate operations may prevent the merge of the SETCC instruction
12623   // and the arithmetic instruction before it. Attempt to truncate the operands
12624   // of the arithmetic instruction and use a reduced bit-width instruction.
12625   bool NeedTruncation = false;
12626   SDValue ArithOp = Op;
12627   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12628     SDValue Arith = Op->getOperand(0);
12629     // Both the trunc and the arithmetic op need to have one user each.
12630     if (Arith->hasOneUse())
12631       switch (Arith.getOpcode()) {
12632         default: break;
12633         case ISD::ADD:
12634         case ISD::SUB:
12635         case ISD::AND:
12636         case ISD::OR:
12637         case ISD::XOR: {
12638           NeedTruncation = true;
12639           ArithOp = Arith;
12640         }
12641       }
12642   }
12643
12644   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12645   // which may be the result of a CAST.  We use the variable 'Op', which is the
12646   // non-casted variable when we check for possible users.
12647   switch (ArithOp.getOpcode()) {
12648   case ISD::ADD:
12649     // Due to an isel shortcoming, be conservative if this add is likely to be
12650     // selected as part of a load-modify-store instruction. When the root node
12651     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12652     // uses of other nodes in the match, such as the ADD in this case. This
12653     // leads to the ADD being left around and reselected, with the result being
12654     // two adds in the output.  Alas, even if none our users are stores, that
12655     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12656     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12657     // climbing the DAG back to the root, and it doesn't seem to be worth the
12658     // effort.
12659     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12660          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12661       if (UI->getOpcode() != ISD::CopyToReg &&
12662           UI->getOpcode() != ISD::SETCC &&
12663           UI->getOpcode() != ISD::STORE)
12664         goto default_case;
12665
12666     if (ConstantSDNode *C =
12667         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12668       // An add of one will be selected as an INC.
12669       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12670         Opcode = X86ISD::INC;
12671         NumOperands = 1;
12672         break;
12673       }
12674
12675       // An add of negative one (subtract of one) will be selected as a DEC.
12676       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12677         Opcode = X86ISD::DEC;
12678         NumOperands = 1;
12679         break;
12680       }
12681     }
12682
12683     // Otherwise use a regular EFLAGS-setting add.
12684     Opcode = X86ISD::ADD;
12685     NumOperands = 2;
12686     break;
12687   case ISD::SHL:
12688   case ISD::SRL:
12689     // If we have a constant logical shift that's only used in a comparison
12690     // against zero turn it into an equivalent AND. This allows turning it into
12691     // a TEST instruction later.
12692     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12693         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12694       EVT VT = Op.getValueType();
12695       unsigned BitWidth = VT.getSizeInBits();
12696       unsigned ShAmt = Op->getConstantOperandVal(1);
12697       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12698         break;
12699       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12700                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12701                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12702       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12703         break;
12704       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12705                                 DAG.getConstant(Mask, dl, VT));
12706       DAG.ReplaceAllUsesWith(Op, New);
12707       Op = New;
12708     }
12709     break;
12710
12711   case ISD::AND:
12712     // If the primary and result isn't used, don't bother using X86ISD::AND,
12713     // because a TEST instruction will be better.
12714     if (!hasNonFlagsUse(Op))
12715       break;
12716     // FALL THROUGH
12717   case ISD::SUB:
12718   case ISD::OR:
12719   case ISD::XOR:
12720     // Due to the ISEL shortcoming noted above, be conservative if this op is
12721     // likely to be selected as part of a load-modify-store instruction.
12722     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12723            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12724       if (UI->getOpcode() == ISD::STORE)
12725         goto default_case;
12726
12727     // Otherwise use a regular EFLAGS-setting instruction.
12728     switch (ArithOp.getOpcode()) {
12729     default: llvm_unreachable("unexpected operator!");
12730     case ISD::SUB: Opcode = X86ISD::SUB; break;
12731     case ISD::XOR: Opcode = X86ISD::XOR; break;
12732     case ISD::AND: Opcode = X86ISD::AND; break;
12733     case ISD::OR: {
12734       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12735         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12736         if (EFLAGS.getNode())
12737           return EFLAGS;
12738       }
12739       Opcode = X86ISD::OR;
12740       break;
12741     }
12742     }
12743
12744     NumOperands = 2;
12745     break;
12746   case X86ISD::ADD:
12747   case X86ISD::SUB:
12748   case X86ISD::INC:
12749   case X86ISD::DEC:
12750   case X86ISD::OR:
12751   case X86ISD::XOR:
12752   case X86ISD::AND:
12753     return SDValue(Op.getNode(), 1);
12754   default:
12755   default_case:
12756     break;
12757   }
12758
12759   // If we found that truncation is beneficial, perform the truncation and
12760   // update 'Op'.
12761   if (NeedTruncation) {
12762     EVT VT = Op.getValueType();
12763     SDValue WideVal = Op->getOperand(0);
12764     EVT WideVT = WideVal.getValueType();
12765     unsigned ConvertedOp = 0;
12766     // Use a target machine opcode to prevent further DAGCombine
12767     // optimizations that may separate the arithmetic operations
12768     // from the setcc node.
12769     switch (WideVal.getOpcode()) {
12770       default: break;
12771       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12772       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12773       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12774       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12775       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12776     }
12777
12778     if (ConvertedOp) {
12779       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12780       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12781         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12782         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12783         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12784       }
12785     }
12786   }
12787
12788   if (Opcode == 0)
12789     // Emit a CMP with 0, which is the TEST pattern.
12790     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12791                        DAG.getConstant(0, dl, Op.getValueType()));
12792
12793   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12794   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12795
12796   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12797   DAG.ReplaceAllUsesWith(Op, New);
12798   return SDValue(New.getNode(), 1);
12799 }
12800
12801 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12802 /// equivalent.
12803 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12804                                    SDLoc dl, SelectionDAG &DAG) const {
12805   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12806     if (C->getAPIntValue() == 0)
12807       return EmitTest(Op0, X86CC, dl, DAG);
12808
12809      if (Op0.getValueType() == MVT::i1)
12810        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12811   }
12812
12813   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12814        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12815     // Do the comparison at i32 if it's smaller, besides the Atom case.
12816     // This avoids subregister aliasing issues. Keep the smaller reference
12817     // if we're optimizing for size, however, as that'll allow better folding
12818     // of memory operations.
12819     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12820         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12821             Attribute::MinSize) &&
12822         !Subtarget->isAtom()) {
12823       unsigned ExtendOp =
12824           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12825       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12826       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12827     }
12828     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12829     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12830     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12831                               Op0, Op1);
12832     return SDValue(Sub.getNode(), 1);
12833   }
12834   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12835 }
12836
12837 /// Convert a comparison if required by the subtarget.
12838 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12839                                                  SelectionDAG &DAG) const {
12840   // If the subtarget does not support the FUCOMI instruction, floating-point
12841   // comparisons have to be converted.
12842   if (Subtarget->hasCMov() ||
12843       Cmp.getOpcode() != X86ISD::CMP ||
12844       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12845       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12846     return Cmp;
12847
12848   // The instruction selector will select an FUCOM instruction instead of
12849   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12850   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12851   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12852   SDLoc dl(Cmp);
12853   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12854   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12855   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12856                             DAG.getConstant(8, dl, MVT::i8));
12857   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12858   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12859 }
12860
12861 /// The minimum architected relative accuracy is 2^-12. We need one
12862 /// Newton-Raphson step to have a good float result (24 bits of precision).
12863 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12864                                             DAGCombinerInfo &DCI,
12865                                             unsigned &RefinementSteps,
12866                                             bool &UseOneConstNR) const {
12867   // FIXME: We should use instruction latency models to calculate the cost of
12868   // each potential sequence, but this is very hard to do reliably because
12869   // at least Intel's Core* chips have variable timing based on the number of
12870   // significant digits in the divisor and/or sqrt operand.
12871   if (!Subtarget->useSqrtEst())
12872     return SDValue();
12873
12874   EVT VT = Op.getValueType();
12875
12876   // SSE1 has rsqrtss and rsqrtps.
12877   // TODO: Add support for AVX512 (v16f32).
12878   // It is likely not profitable to do this for f64 because a double-precision
12879   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12880   // instructions: convert to single, rsqrtss, convert back to double, refine
12881   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12882   // along with FMA, this could be a throughput win.
12883   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12884       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12885     RefinementSteps = 1;
12886     UseOneConstNR = false;
12887     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12888   }
12889   return SDValue();
12890 }
12891
12892 /// The minimum architected relative accuracy is 2^-12. We need one
12893 /// Newton-Raphson step to have a good float result (24 bits of precision).
12894 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12895                                             DAGCombinerInfo &DCI,
12896                                             unsigned &RefinementSteps) const {
12897   // FIXME: We should use instruction latency models to calculate the cost of
12898   // each potential sequence, but this is very hard to do reliably because
12899   // at least Intel's Core* chips have variable timing based on the number of
12900   // significant digits in the divisor.
12901   if (!Subtarget->useReciprocalEst())
12902     return SDValue();
12903
12904   EVT VT = Op.getValueType();
12905
12906   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12907   // TODO: Add support for AVX512 (v16f32).
12908   // It is likely not profitable to do this for f64 because a double-precision
12909   // reciprocal estimate with refinement on x86 prior to FMA requires
12910   // 15 instructions: convert to single, rcpss, convert back to double, refine
12911   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12912   // along with FMA, this could be a throughput win.
12913   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12914       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12915     RefinementSteps = ReciprocalEstimateRefinementSteps;
12916     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12917   }
12918   return SDValue();
12919 }
12920
12921 /// If we have at least two divisions that use the same divisor, convert to
12922 /// multplication by a reciprocal. This may need to be adjusted for a given
12923 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12924 /// This is because we still need one division to calculate the reciprocal and
12925 /// then we need two multiplies by that reciprocal as replacements for the
12926 /// original divisions.
12927 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12928   return NumUsers > 1;
12929 }
12930
12931 static bool isAllOnes(SDValue V) {
12932   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12933   return C && C->isAllOnesValue();
12934 }
12935
12936 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12937 /// if it's possible.
12938 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12939                                      SDLoc dl, SelectionDAG &DAG) const {
12940   SDValue Op0 = And.getOperand(0);
12941   SDValue Op1 = And.getOperand(1);
12942   if (Op0.getOpcode() == ISD::TRUNCATE)
12943     Op0 = Op0.getOperand(0);
12944   if (Op1.getOpcode() == ISD::TRUNCATE)
12945     Op1 = Op1.getOperand(0);
12946
12947   SDValue LHS, RHS;
12948   if (Op1.getOpcode() == ISD::SHL)
12949     std::swap(Op0, Op1);
12950   if (Op0.getOpcode() == ISD::SHL) {
12951     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12952       if (And00C->getZExtValue() == 1) {
12953         // If we looked past a truncate, check that it's only truncating away
12954         // known zeros.
12955         unsigned BitWidth = Op0.getValueSizeInBits();
12956         unsigned AndBitWidth = And.getValueSizeInBits();
12957         if (BitWidth > AndBitWidth) {
12958           APInt Zeros, Ones;
12959           DAG.computeKnownBits(Op0, Zeros, Ones);
12960           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12961             return SDValue();
12962         }
12963         LHS = Op1;
12964         RHS = Op0.getOperand(1);
12965       }
12966   } else if (Op1.getOpcode() == ISD::Constant) {
12967     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12968     uint64_t AndRHSVal = AndRHS->getZExtValue();
12969     SDValue AndLHS = Op0;
12970
12971     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12972       LHS = AndLHS.getOperand(0);
12973       RHS = AndLHS.getOperand(1);
12974     }
12975
12976     // Use BT if the immediate can't be encoded in a TEST instruction.
12977     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12978       LHS = AndLHS;
12979       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
12980     }
12981   }
12982
12983   if (LHS.getNode()) {
12984     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12985     // instruction.  Since the shift amount is in-range-or-undefined, we know
12986     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12987     // the encoding for the i16 version is larger than the i32 version.
12988     // Also promote i16 to i32 for performance / code size reason.
12989     if (LHS.getValueType() == MVT::i8 ||
12990         LHS.getValueType() == MVT::i16)
12991       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12992
12993     // If the operand types disagree, extend the shift amount to match.  Since
12994     // BT ignores high bits (like shifts) we can use anyextend.
12995     if (LHS.getValueType() != RHS.getValueType())
12996       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12997
12998     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12999     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13000     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13001                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13002   }
13003
13004   return SDValue();
13005 }
13006
13007 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13008 /// mask CMPs.
13009 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13010                               SDValue &Op1) {
13011   unsigned SSECC;
13012   bool Swap = false;
13013
13014   // SSE Condition code mapping:
13015   //  0 - EQ
13016   //  1 - LT
13017   //  2 - LE
13018   //  3 - UNORD
13019   //  4 - NEQ
13020   //  5 - NLT
13021   //  6 - NLE
13022   //  7 - ORD
13023   switch (SetCCOpcode) {
13024   default: llvm_unreachable("Unexpected SETCC condition");
13025   case ISD::SETOEQ:
13026   case ISD::SETEQ:  SSECC = 0; break;
13027   case ISD::SETOGT:
13028   case ISD::SETGT:  Swap = true; // Fallthrough
13029   case ISD::SETLT:
13030   case ISD::SETOLT: SSECC = 1; break;
13031   case ISD::SETOGE:
13032   case ISD::SETGE:  Swap = true; // Fallthrough
13033   case ISD::SETLE:
13034   case ISD::SETOLE: SSECC = 2; break;
13035   case ISD::SETUO:  SSECC = 3; break;
13036   case ISD::SETUNE:
13037   case ISD::SETNE:  SSECC = 4; break;
13038   case ISD::SETULE: Swap = true; // Fallthrough
13039   case ISD::SETUGE: SSECC = 5; break;
13040   case ISD::SETULT: Swap = true; // Fallthrough
13041   case ISD::SETUGT: SSECC = 6; break;
13042   case ISD::SETO:   SSECC = 7; break;
13043   case ISD::SETUEQ:
13044   case ISD::SETONE: SSECC = 8; break;
13045   }
13046   if (Swap)
13047     std::swap(Op0, Op1);
13048
13049   return SSECC;
13050 }
13051
13052 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13053 // ones, and then concatenate the result back.
13054 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13055   MVT VT = Op.getSimpleValueType();
13056
13057   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13058          "Unsupported value type for operation");
13059
13060   unsigned NumElems = VT.getVectorNumElements();
13061   SDLoc dl(Op);
13062   SDValue CC = Op.getOperand(2);
13063
13064   // Extract the LHS vectors
13065   SDValue LHS = Op.getOperand(0);
13066   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13067   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13068
13069   // Extract the RHS vectors
13070   SDValue RHS = Op.getOperand(1);
13071   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13072   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13073
13074   // Issue the operation on the smaller types and concatenate the result back
13075   MVT EltVT = VT.getVectorElementType();
13076   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13077   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13078                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13079                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13080 }
13081
13082 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13083   SDValue Op0 = Op.getOperand(0);
13084   SDValue Op1 = Op.getOperand(1);
13085   SDValue CC = Op.getOperand(2);
13086   MVT VT = Op.getSimpleValueType();
13087   SDLoc dl(Op);
13088
13089   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13090          "Unexpected type for boolean compare operation");
13091   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13092   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13093                                DAG.getConstant(-1, dl, VT));
13094   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13095                                DAG.getConstant(-1, dl, VT));
13096   switch (SetCCOpcode) {
13097   default: llvm_unreachable("Unexpected SETCC condition");
13098   case ISD::SETNE:
13099     // (x != y) -> ~(x ^ y)
13100     return DAG.getNode(ISD::XOR, dl, VT,
13101                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13102                        DAG.getConstant(-1, dl, VT));
13103   case ISD::SETEQ:
13104     // (x == y) -> (x ^ y)
13105     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13106   case ISD::SETUGT:
13107   case ISD::SETGT:
13108     // (x > y) -> (x & ~y)
13109     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13110   case ISD::SETULT:
13111   case ISD::SETLT:
13112     // (x < y) -> (~x & y)
13113     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13114   case ISD::SETULE:
13115   case ISD::SETLE:
13116     // (x <= y) -> (~x | y)
13117     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13118   case ISD::SETUGE:
13119   case ISD::SETGE:
13120     // (x >=y) -> (x | ~y)
13121     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13122   }
13123 }
13124
13125 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13126                                      const X86Subtarget *Subtarget) {
13127   SDValue Op0 = Op.getOperand(0);
13128   SDValue Op1 = Op.getOperand(1);
13129   SDValue CC = Op.getOperand(2);
13130   MVT VT = Op.getSimpleValueType();
13131   SDLoc dl(Op);
13132
13133   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13134          Op.getValueType().getScalarType() == MVT::i1 &&
13135          "Cannot set masked compare for this operation");
13136
13137   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13138   unsigned  Opc = 0;
13139   bool Unsigned = false;
13140   bool Swap = false;
13141   unsigned SSECC;
13142   switch (SetCCOpcode) {
13143   default: llvm_unreachable("Unexpected SETCC condition");
13144   case ISD::SETNE:  SSECC = 4; break;
13145   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13146   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13147   case ISD::SETLT:  Swap = true; //fall-through
13148   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13149   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13150   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13151   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13152   case ISD::SETULE: Unsigned = true; //fall-through
13153   case ISD::SETLE:  SSECC = 2; break;
13154   }
13155
13156   if (Swap)
13157     std::swap(Op0, Op1);
13158   if (Opc)
13159     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13160   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13161   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13162                      DAG.getConstant(SSECC, dl, MVT::i8));
13163 }
13164
13165 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13166 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13167 /// return an empty value.
13168 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13169 {
13170   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13171   if (!BV)
13172     return SDValue();
13173
13174   MVT VT = Op1.getSimpleValueType();
13175   MVT EVT = VT.getVectorElementType();
13176   unsigned n = VT.getVectorNumElements();
13177   SmallVector<SDValue, 8> ULTOp1;
13178
13179   for (unsigned i = 0; i < n; ++i) {
13180     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13181     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13182       return SDValue();
13183
13184     // Avoid underflow.
13185     APInt Val = Elt->getAPIntValue();
13186     if (Val == 0)
13187       return SDValue();
13188
13189     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13190   }
13191
13192   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13193 }
13194
13195 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13196                            SelectionDAG &DAG) {
13197   SDValue Op0 = Op.getOperand(0);
13198   SDValue Op1 = Op.getOperand(1);
13199   SDValue CC = Op.getOperand(2);
13200   MVT VT = Op.getSimpleValueType();
13201   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13202   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13203   SDLoc dl(Op);
13204
13205   if (isFP) {
13206 #ifndef NDEBUG
13207     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13208     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13209 #endif
13210
13211     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13212     unsigned Opc = X86ISD::CMPP;
13213     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13214       assert(VT.getVectorNumElements() <= 16);
13215       Opc = X86ISD::CMPM;
13216     }
13217     // In the two special cases we can't handle, emit two comparisons.
13218     if (SSECC == 8) {
13219       unsigned CC0, CC1;
13220       unsigned CombineOpc;
13221       if (SetCCOpcode == ISD::SETUEQ) {
13222         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13223       } else {
13224         assert(SetCCOpcode == ISD::SETONE);
13225         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13226       }
13227
13228       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13229                                  DAG.getConstant(CC0, dl, MVT::i8));
13230       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13231                                  DAG.getConstant(CC1, dl, MVT::i8));
13232       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13233     }
13234     // Handle all other FP comparisons here.
13235     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13236                        DAG.getConstant(SSECC, dl, MVT::i8));
13237   }
13238
13239   // Break 256-bit integer vector compare into smaller ones.
13240   if (VT.is256BitVector() && !Subtarget->hasInt256())
13241     return Lower256IntVSETCC(Op, DAG);
13242
13243   EVT OpVT = Op1.getValueType();
13244   if (OpVT.getVectorElementType() == MVT::i1)
13245     return LowerBoolVSETCC_AVX512(Op, DAG);
13246
13247   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13248   if (Subtarget->hasAVX512()) {
13249     if (Op1.getValueType().is512BitVector() ||
13250         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13251         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13252       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13253
13254     // In AVX-512 architecture setcc returns mask with i1 elements,
13255     // But there is no compare instruction for i8 and i16 elements in KNL.
13256     // We are not talking about 512-bit operands in this case, these
13257     // types are illegal.
13258     if (MaskResult &&
13259         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13260          OpVT.getVectorElementType().getSizeInBits() >= 8))
13261       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13262                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13263   }
13264
13265   // We are handling one of the integer comparisons here.  Since SSE only has
13266   // GT and EQ comparisons for integer, swapping operands and multiple
13267   // operations may be required for some comparisons.
13268   unsigned Opc;
13269   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13270   bool Subus = false;
13271
13272   switch (SetCCOpcode) {
13273   default: llvm_unreachable("Unexpected SETCC condition");
13274   case ISD::SETNE:  Invert = true;
13275   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13276   case ISD::SETLT:  Swap = true;
13277   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13278   case ISD::SETGE:  Swap = true;
13279   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13280                     Invert = true; break;
13281   case ISD::SETULT: Swap = true;
13282   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13283                     FlipSigns = true; break;
13284   case ISD::SETUGE: Swap = true;
13285   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13286                     FlipSigns = true; Invert = true; break;
13287   }
13288
13289   // Special case: Use min/max operations for SETULE/SETUGE
13290   MVT VET = VT.getVectorElementType();
13291   bool hasMinMax =
13292        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13293     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13294
13295   if (hasMinMax) {
13296     switch (SetCCOpcode) {
13297     default: break;
13298     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13299     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13300     }
13301
13302     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13303   }
13304
13305   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13306   if (!MinMax && hasSubus) {
13307     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13308     // Op0 u<= Op1:
13309     //   t = psubus Op0, Op1
13310     //   pcmpeq t, <0..0>
13311     switch (SetCCOpcode) {
13312     default: break;
13313     case ISD::SETULT: {
13314       // If the comparison is against a constant we can turn this into a
13315       // setule.  With psubus, setule does not require a swap.  This is
13316       // beneficial because the constant in the register is no longer
13317       // destructed as the destination so it can be hoisted out of a loop.
13318       // Only do this pre-AVX since vpcmp* is no longer destructive.
13319       if (Subtarget->hasAVX())
13320         break;
13321       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13322       if (ULEOp1.getNode()) {
13323         Op1 = ULEOp1;
13324         Subus = true; Invert = false; Swap = false;
13325       }
13326       break;
13327     }
13328     // Psubus is better than flip-sign because it requires no inversion.
13329     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13330     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13331     }
13332
13333     if (Subus) {
13334       Opc = X86ISD::SUBUS;
13335       FlipSigns = false;
13336     }
13337   }
13338
13339   if (Swap)
13340     std::swap(Op0, Op1);
13341
13342   // Check that the operation in question is available (most are plain SSE2,
13343   // but PCMPGTQ and PCMPEQQ have different requirements).
13344   if (VT == MVT::v2i64) {
13345     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13346       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13347
13348       // First cast everything to the right type.
13349       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13350       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13351
13352       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13353       // bits of the inputs before performing those operations. The lower
13354       // compare is always unsigned.
13355       SDValue SB;
13356       if (FlipSigns) {
13357         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13358       } else {
13359         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13360         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13361         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13362                          Sign, Zero, Sign, Zero);
13363       }
13364       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13365       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13366
13367       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13368       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13369       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13370
13371       // Create masks for only the low parts/high parts of the 64 bit integers.
13372       static const int MaskHi[] = { 1, 1, 3, 3 };
13373       static const int MaskLo[] = { 0, 0, 2, 2 };
13374       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13375       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13376       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13377
13378       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13379       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13380
13381       if (Invert)
13382         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13383
13384       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13385     }
13386
13387     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13388       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13389       // pcmpeqd + pshufd + pand.
13390       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13391
13392       // First cast everything to the right type.
13393       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13394       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13395
13396       // Do the compare.
13397       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13398
13399       // Make sure the lower and upper halves are both all-ones.
13400       static const int Mask[] = { 1, 0, 3, 2 };
13401       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13402       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13403
13404       if (Invert)
13405         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13406
13407       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13408     }
13409   }
13410
13411   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13412   // bits of the inputs before performing those operations.
13413   if (FlipSigns) {
13414     EVT EltVT = VT.getVectorElementType();
13415     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13416                                  VT);
13417     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13418     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13419   }
13420
13421   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13422
13423   // If the logical-not of the result is required, perform that now.
13424   if (Invert)
13425     Result = DAG.getNOT(dl, Result, VT);
13426
13427   if (MinMax)
13428     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13429
13430   if (Subus)
13431     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13432                          getZeroVector(VT, Subtarget, DAG, dl));
13433
13434   return Result;
13435 }
13436
13437 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13438
13439   MVT VT = Op.getSimpleValueType();
13440
13441   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13442
13443   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13444          && "SetCC type must be 8-bit or 1-bit integer");
13445   SDValue Op0 = Op.getOperand(0);
13446   SDValue Op1 = Op.getOperand(1);
13447   SDLoc dl(Op);
13448   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13449
13450   // Optimize to BT if possible.
13451   // Lower (X & (1 << N)) == 0 to BT(X, N).
13452   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13453   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13454   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13455       Op1.getOpcode() == ISD::Constant &&
13456       cast<ConstantSDNode>(Op1)->isNullValue() &&
13457       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13458     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13459     if (NewSetCC.getNode()) {
13460       if (VT == MVT::i1)
13461         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13462       return NewSetCC;
13463     }
13464   }
13465
13466   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13467   // these.
13468   if (Op1.getOpcode() == ISD::Constant &&
13469       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13470        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13471       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13472
13473     // If the input is a setcc, then reuse the input setcc or use a new one with
13474     // the inverted condition.
13475     if (Op0.getOpcode() == X86ISD::SETCC) {
13476       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13477       bool Invert = (CC == ISD::SETNE) ^
13478         cast<ConstantSDNode>(Op1)->isNullValue();
13479       if (!Invert)
13480         return Op0;
13481
13482       CCode = X86::GetOppositeBranchCondition(CCode);
13483       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13484                                   DAG.getConstant(CCode, dl, MVT::i8),
13485                                   Op0.getOperand(1));
13486       if (VT == MVT::i1)
13487         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13488       return SetCC;
13489     }
13490   }
13491   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13492       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13493       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13494
13495     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13496     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13497   }
13498
13499   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13500   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13501   if (X86CC == X86::COND_INVALID)
13502     return SDValue();
13503
13504   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13505   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13506   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13507                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13508   if (VT == MVT::i1)
13509     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13510   return SetCC;
13511 }
13512
13513 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13514 static bool isX86LogicalCmp(SDValue Op) {
13515   unsigned Opc = Op.getNode()->getOpcode();
13516   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13517       Opc == X86ISD::SAHF)
13518     return true;
13519   if (Op.getResNo() == 1 &&
13520       (Opc == X86ISD::ADD ||
13521        Opc == X86ISD::SUB ||
13522        Opc == X86ISD::ADC ||
13523        Opc == X86ISD::SBB ||
13524        Opc == X86ISD::SMUL ||
13525        Opc == X86ISD::UMUL ||
13526        Opc == X86ISD::INC ||
13527        Opc == X86ISD::DEC ||
13528        Opc == X86ISD::OR ||
13529        Opc == X86ISD::XOR ||
13530        Opc == X86ISD::AND))
13531     return true;
13532
13533   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13534     return true;
13535
13536   return false;
13537 }
13538
13539 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13540   if (V.getOpcode() != ISD::TRUNCATE)
13541     return false;
13542
13543   SDValue VOp0 = V.getOperand(0);
13544   unsigned InBits = VOp0.getValueSizeInBits();
13545   unsigned Bits = V.getValueSizeInBits();
13546   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13547 }
13548
13549 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13550   bool addTest = true;
13551   SDValue Cond  = Op.getOperand(0);
13552   SDValue Op1 = Op.getOperand(1);
13553   SDValue Op2 = Op.getOperand(2);
13554   SDLoc DL(Op);
13555   EVT VT = Op1.getValueType();
13556   SDValue CC;
13557
13558   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13559   // are available or VBLENDV if AVX is available.
13560   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13561   if (Cond.getOpcode() == ISD::SETCC &&
13562       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13563        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13564       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13565     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13566     int SSECC = translateX86FSETCC(
13567         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13568
13569     if (SSECC != 8) {
13570       if (Subtarget->hasAVX512()) {
13571         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13572                                   DAG.getConstant(SSECC, DL, MVT::i8));
13573         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13574       }
13575
13576       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13577                                 DAG.getConstant(SSECC, DL, MVT::i8));
13578
13579       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13580       // of 3 logic instructions for size savings and potentially speed.
13581       // Unfortunately, there is no scalar form of VBLENDV.
13582
13583       // If either operand is a constant, don't try this. We can expect to
13584       // optimize away at least one of the logic instructions later in that
13585       // case, so that sequence would be faster than a variable blend.
13586
13587       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13588       // uses XMM0 as the selection register. That may need just as many
13589       // instructions as the AND/ANDN/OR sequence due to register moves, so
13590       // don't bother.
13591
13592       if (Subtarget->hasAVX() &&
13593           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13594
13595         // Convert to vectors, do a VSELECT, and convert back to scalar.
13596         // All of the conversions should be optimized away.
13597
13598         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13599         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13600         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13601         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13602
13603         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13604         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13605
13606         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13607
13608         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13609                            VSel, DAG.getIntPtrConstant(0, DL));
13610       }
13611       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13612       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13613       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13614     }
13615   }
13616
13617   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13618     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13619     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13620                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13621     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13622                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13623     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13624                                     Cond, Op1, Op2);
13625     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13626   }
13627
13628   if (Cond.getOpcode() == ISD::SETCC) {
13629     SDValue NewCond = LowerSETCC(Cond, DAG);
13630     if (NewCond.getNode())
13631       Cond = NewCond;
13632   }
13633
13634   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13635   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13636   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13637   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13638   if (Cond.getOpcode() == X86ISD::SETCC &&
13639       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13640       isZero(Cond.getOperand(1).getOperand(1))) {
13641     SDValue Cmp = Cond.getOperand(1);
13642
13643     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13644
13645     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13646         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13647       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13648
13649       SDValue CmpOp0 = Cmp.getOperand(0);
13650       // Apply further optimizations for special cases
13651       // (select (x != 0), -1, 0) -> neg & sbb
13652       // (select (x == 0), 0, -1) -> neg & sbb
13653       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13654         if (YC->isNullValue() &&
13655             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13656           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13657           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13658                                     DAG.getConstant(0, DL,
13659                                                     CmpOp0.getValueType()),
13660                                     CmpOp0);
13661           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13662                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13663                                     SDValue(Neg.getNode(), 1));
13664           return Res;
13665         }
13666
13667       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13668                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13669       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13670
13671       SDValue Res =   // Res = 0 or -1.
13672         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13673                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13674
13675       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13676         Res = DAG.getNOT(DL, Res, Res.getValueType());
13677
13678       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13679       if (!N2C || !N2C->isNullValue())
13680         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13681       return Res;
13682     }
13683   }
13684
13685   // Look past (and (setcc_carry (cmp ...)), 1).
13686   if (Cond.getOpcode() == ISD::AND &&
13687       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13688     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13689     if (C && C->getAPIntValue() == 1)
13690       Cond = Cond.getOperand(0);
13691   }
13692
13693   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13694   // setting operand in place of the X86ISD::SETCC.
13695   unsigned CondOpcode = Cond.getOpcode();
13696   if (CondOpcode == X86ISD::SETCC ||
13697       CondOpcode == X86ISD::SETCC_CARRY) {
13698     CC = Cond.getOperand(0);
13699
13700     SDValue Cmp = Cond.getOperand(1);
13701     unsigned Opc = Cmp.getOpcode();
13702     MVT VT = Op.getSimpleValueType();
13703
13704     bool IllegalFPCMov = false;
13705     if (VT.isFloatingPoint() && !VT.isVector() &&
13706         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13707       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13708
13709     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13710         Opc == X86ISD::BT) { // FIXME
13711       Cond = Cmp;
13712       addTest = false;
13713     }
13714   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13715              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13716              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13717               Cond.getOperand(0).getValueType() != MVT::i8)) {
13718     SDValue LHS = Cond.getOperand(0);
13719     SDValue RHS = Cond.getOperand(1);
13720     unsigned X86Opcode;
13721     unsigned X86Cond;
13722     SDVTList VTs;
13723     switch (CondOpcode) {
13724     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13725     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13726     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13727     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13728     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13729     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13730     default: llvm_unreachable("unexpected overflowing operator");
13731     }
13732     if (CondOpcode == ISD::UMULO)
13733       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13734                           MVT::i32);
13735     else
13736       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13737
13738     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13739
13740     if (CondOpcode == ISD::UMULO)
13741       Cond = X86Op.getValue(2);
13742     else
13743       Cond = X86Op.getValue(1);
13744
13745     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13746     addTest = false;
13747   }
13748
13749   if (addTest) {
13750     // Look pass the truncate if the high bits are known zero.
13751     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13752         Cond = Cond.getOperand(0);
13753
13754     // We know the result of AND is compared against zero. Try to match
13755     // it to BT.
13756     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13757       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13758       if (NewSetCC.getNode()) {
13759         CC = NewSetCC.getOperand(0);
13760         Cond = NewSetCC.getOperand(1);
13761         addTest = false;
13762       }
13763     }
13764   }
13765
13766   if (addTest) {
13767     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13768     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13769   }
13770
13771   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13772   // a <  b ?  0 : -1 -> RES = setcc_carry
13773   // a >= b ? -1 :  0 -> RES = setcc_carry
13774   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13775   if (Cond.getOpcode() == X86ISD::SUB) {
13776     Cond = ConvertCmpIfNecessary(Cond, DAG);
13777     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13778
13779     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13780         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13781       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13782                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13783                                 Cond);
13784       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13785         return DAG.getNOT(DL, Res, Res.getValueType());
13786       return Res;
13787     }
13788   }
13789
13790   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13791   // widen the cmov and push the truncate through. This avoids introducing a new
13792   // branch during isel and doesn't add any extensions.
13793   if (Op.getValueType() == MVT::i8 &&
13794       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13795     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13796     if (T1.getValueType() == T2.getValueType() &&
13797         // Blacklist CopyFromReg to avoid partial register stalls.
13798         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13799       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13800       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13801       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13802     }
13803   }
13804
13805   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13806   // condition is true.
13807   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13808   SDValue Ops[] = { Op2, Op1, CC, Cond };
13809   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13810 }
13811
13812 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13813                                        SelectionDAG &DAG) {
13814   MVT VT = Op->getSimpleValueType(0);
13815   SDValue In = Op->getOperand(0);
13816   MVT InVT = In.getSimpleValueType();
13817   MVT VTElt = VT.getVectorElementType();
13818   MVT InVTElt = InVT.getVectorElementType();
13819   SDLoc dl(Op);
13820
13821   // SKX processor
13822   if ((InVTElt == MVT::i1) &&
13823       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13824         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13825
13826        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13827         VTElt.getSizeInBits() <= 16)) ||
13828
13829        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13830         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13831
13832        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13833         VTElt.getSizeInBits() >= 32))))
13834     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13835
13836   unsigned int NumElts = VT.getVectorNumElements();
13837
13838   if (NumElts != 8 && NumElts != 16)
13839     return SDValue();
13840
13841   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13842     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13843       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13844     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13845   }
13846
13847   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13848   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13849   SDValue NegOne =
13850    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13851                    ExtVT);
13852   SDValue Zero =
13853    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13854
13855   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13856   if (VT.is512BitVector())
13857     return V;
13858   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13859 }
13860
13861 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13862                                 SelectionDAG &DAG) {
13863   MVT VT = Op->getSimpleValueType(0);
13864   SDValue In = Op->getOperand(0);
13865   MVT InVT = In.getSimpleValueType();
13866   SDLoc dl(Op);
13867
13868   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13869     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13870
13871   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13872       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13873       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13874     return SDValue();
13875
13876   if (Subtarget->hasInt256())
13877     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13878
13879   // Optimize vectors in AVX mode
13880   // Sign extend  v8i16 to v8i32 and
13881   //              v4i32 to v4i64
13882   //
13883   // Divide input vector into two parts
13884   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13885   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13886   // concat the vectors to original VT
13887
13888   unsigned NumElems = InVT.getVectorNumElements();
13889   SDValue Undef = DAG.getUNDEF(InVT);
13890
13891   SmallVector<int,8> ShufMask1(NumElems, -1);
13892   for (unsigned i = 0; i != NumElems/2; ++i)
13893     ShufMask1[i] = i;
13894
13895   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13896
13897   SmallVector<int,8> ShufMask2(NumElems, -1);
13898   for (unsigned i = 0; i != NumElems/2; ++i)
13899     ShufMask2[i] = i + NumElems/2;
13900
13901   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13902
13903   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13904                                 VT.getVectorNumElements()/2);
13905
13906   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13907   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13908
13909   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13910 }
13911
13912 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13913 // may emit an illegal shuffle but the expansion is still better than scalar
13914 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13915 // we'll emit a shuffle and a arithmetic shift.
13916 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13917 // TODO: It is possible to support ZExt by zeroing the undef values during
13918 // the shuffle phase or after the shuffle.
13919 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13920                                  SelectionDAG &DAG) {
13921   MVT RegVT = Op.getSimpleValueType();
13922   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13923   assert(RegVT.isInteger() &&
13924          "We only custom lower integer vector sext loads.");
13925
13926   // Nothing useful we can do without SSE2 shuffles.
13927   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13928
13929   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13930   SDLoc dl(Ld);
13931   EVT MemVT = Ld->getMemoryVT();
13932   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13933   unsigned RegSz = RegVT.getSizeInBits();
13934
13935   ISD::LoadExtType Ext = Ld->getExtensionType();
13936
13937   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13938          && "Only anyext and sext are currently implemented.");
13939   assert(MemVT != RegVT && "Cannot extend to the same type");
13940   assert(MemVT.isVector() && "Must load a vector from memory");
13941
13942   unsigned NumElems = RegVT.getVectorNumElements();
13943   unsigned MemSz = MemVT.getSizeInBits();
13944   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13945
13946   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13947     // The only way in which we have a legal 256-bit vector result but not the
13948     // integer 256-bit operations needed to directly lower a sextload is if we
13949     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13950     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13951     // correctly legalized. We do this late to allow the canonical form of
13952     // sextload to persist throughout the rest of the DAG combiner -- it wants
13953     // to fold together any extensions it can, and so will fuse a sign_extend
13954     // of an sextload into a sextload targeting a wider value.
13955     SDValue Load;
13956     if (MemSz == 128) {
13957       // Just switch this to a normal load.
13958       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13959                                        "it must be a legal 128-bit vector "
13960                                        "type!");
13961       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13962                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13963                   Ld->isInvariant(), Ld->getAlignment());
13964     } else {
13965       assert(MemSz < 128 &&
13966              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13967       // Do an sext load to a 128-bit vector type. We want to use the same
13968       // number of elements, but elements half as wide. This will end up being
13969       // recursively lowered by this routine, but will succeed as we definitely
13970       // have all the necessary features if we're using AVX1.
13971       EVT HalfEltVT =
13972           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13973       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13974       Load =
13975           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13976                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13977                          Ld->isNonTemporal(), Ld->isInvariant(),
13978                          Ld->getAlignment());
13979     }
13980
13981     // Replace chain users with the new chain.
13982     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13983     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13984
13985     // Finally, do a normal sign-extend to the desired register.
13986     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13987   }
13988
13989   // All sizes must be a power of two.
13990   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13991          "Non-power-of-two elements are not custom lowered!");
13992
13993   // Attempt to load the original value using scalar loads.
13994   // Find the largest scalar type that divides the total loaded size.
13995   MVT SclrLoadTy = MVT::i8;
13996   for (MVT Tp : MVT::integer_valuetypes()) {
13997     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13998       SclrLoadTy = Tp;
13999     }
14000   }
14001
14002   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14003   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14004       (64 <= MemSz))
14005     SclrLoadTy = MVT::f64;
14006
14007   // Calculate the number of scalar loads that we need to perform
14008   // in order to load our vector from memory.
14009   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14010
14011   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14012          "Can only lower sext loads with a single scalar load!");
14013
14014   unsigned loadRegZize = RegSz;
14015   if (Ext == ISD::SEXTLOAD && RegSz == 256)
14016     loadRegZize /= 2;
14017
14018   // Represent our vector as a sequence of elements which are the
14019   // largest scalar that we can load.
14020   EVT LoadUnitVecVT = EVT::getVectorVT(
14021       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14022
14023   // Represent the data using the same element type that is stored in
14024   // memory. In practice, we ''widen'' MemVT.
14025   EVT WideVecVT =
14026       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14027                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14028
14029   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14030          "Invalid vector type");
14031
14032   // We can't shuffle using an illegal type.
14033   assert(TLI.isTypeLegal(WideVecVT) &&
14034          "We only lower types that form legal widened vector types");
14035
14036   SmallVector<SDValue, 8> Chains;
14037   SDValue Ptr = Ld->getBasePtr();
14038   SDValue Increment =
14039       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14040   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14041
14042   for (unsigned i = 0; i < NumLoads; ++i) {
14043     // Perform a single load.
14044     SDValue ScalarLoad =
14045         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14046                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14047                     Ld->getAlignment());
14048     Chains.push_back(ScalarLoad.getValue(1));
14049     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14050     // another round of DAGCombining.
14051     if (i == 0)
14052       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14053     else
14054       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14055                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14056
14057     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14058   }
14059
14060   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14061
14062   // Bitcast the loaded value to a vector of the original element type, in
14063   // the size of the target vector type.
14064   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14065   unsigned SizeRatio = RegSz / MemSz;
14066
14067   if (Ext == ISD::SEXTLOAD) {
14068     // If we have SSE4.1, we can directly emit a VSEXT node.
14069     if (Subtarget->hasSSE41()) {
14070       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14071       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14072       return Sext;
14073     }
14074
14075     // Otherwise we'll shuffle the small elements in the high bits of the
14076     // larger type and perform an arithmetic shift. If the shift is not legal
14077     // it's better to scalarize.
14078     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14079            "We can't implement a sext load without an arithmetic right shift!");
14080
14081     // Redistribute the loaded elements into the different locations.
14082     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14083     for (unsigned i = 0; i != NumElems; ++i)
14084       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14085
14086     SDValue Shuff = DAG.getVectorShuffle(
14087         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14088
14089     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14090
14091     // Build the arithmetic shift.
14092     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14093                    MemVT.getVectorElementType().getSizeInBits();
14094     Shuff =
14095         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14096                     DAG.getConstant(Amt, dl, RegVT));
14097
14098     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14099     return Shuff;
14100   }
14101
14102   // Redistribute the loaded elements into the different locations.
14103   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14104   for (unsigned i = 0; i != NumElems; ++i)
14105     ShuffleVec[i * SizeRatio] = i;
14106
14107   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14108                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14109
14110   // Bitcast to the requested type.
14111   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14112   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14113   return Shuff;
14114 }
14115
14116 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14117 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14118 // from the AND / OR.
14119 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14120   Opc = Op.getOpcode();
14121   if (Opc != ISD::OR && Opc != ISD::AND)
14122     return false;
14123   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14124           Op.getOperand(0).hasOneUse() &&
14125           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14126           Op.getOperand(1).hasOneUse());
14127 }
14128
14129 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14130 // 1 and that the SETCC node has a single use.
14131 static bool isXor1OfSetCC(SDValue Op) {
14132   if (Op.getOpcode() != ISD::XOR)
14133     return false;
14134   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14135   if (N1C && N1C->getAPIntValue() == 1) {
14136     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14137       Op.getOperand(0).hasOneUse();
14138   }
14139   return false;
14140 }
14141
14142 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14143   bool addTest = true;
14144   SDValue Chain = Op.getOperand(0);
14145   SDValue Cond  = Op.getOperand(1);
14146   SDValue Dest  = Op.getOperand(2);
14147   SDLoc dl(Op);
14148   SDValue CC;
14149   bool Inverted = false;
14150
14151   if (Cond.getOpcode() == ISD::SETCC) {
14152     // Check for setcc([su]{add,sub,mul}o == 0).
14153     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14154         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14155         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14156         Cond.getOperand(0).getResNo() == 1 &&
14157         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14158          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14159          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14160          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14161          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14162          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14163       Inverted = true;
14164       Cond = Cond.getOperand(0);
14165     } else {
14166       SDValue NewCond = LowerSETCC(Cond, DAG);
14167       if (NewCond.getNode())
14168         Cond = NewCond;
14169     }
14170   }
14171 #if 0
14172   // FIXME: LowerXALUO doesn't handle these!!
14173   else if (Cond.getOpcode() == X86ISD::ADD  ||
14174            Cond.getOpcode() == X86ISD::SUB  ||
14175            Cond.getOpcode() == X86ISD::SMUL ||
14176            Cond.getOpcode() == X86ISD::UMUL)
14177     Cond = LowerXALUO(Cond, DAG);
14178 #endif
14179
14180   // Look pass (and (setcc_carry (cmp ...)), 1).
14181   if (Cond.getOpcode() == ISD::AND &&
14182       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14183     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14184     if (C && C->getAPIntValue() == 1)
14185       Cond = Cond.getOperand(0);
14186   }
14187
14188   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14189   // setting operand in place of the X86ISD::SETCC.
14190   unsigned CondOpcode = Cond.getOpcode();
14191   if (CondOpcode == X86ISD::SETCC ||
14192       CondOpcode == X86ISD::SETCC_CARRY) {
14193     CC = Cond.getOperand(0);
14194
14195     SDValue Cmp = Cond.getOperand(1);
14196     unsigned Opc = Cmp.getOpcode();
14197     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14198     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14199       Cond = Cmp;
14200       addTest = false;
14201     } else {
14202       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14203       default: break;
14204       case X86::COND_O:
14205       case X86::COND_B:
14206         // These can only come from an arithmetic instruction with overflow,
14207         // e.g. SADDO, UADDO.
14208         Cond = Cond.getNode()->getOperand(1);
14209         addTest = false;
14210         break;
14211       }
14212     }
14213   }
14214   CondOpcode = Cond.getOpcode();
14215   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14216       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14217       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14218        Cond.getOperand(0).getValueType() != MVT::i8)) {
14219     SDValue LHS = Cond.getOperand(0);
14220     SDValue RHS = Cond.getOperand(1);
14221     unsigned X86Opcode;
14222     unsigned X86Cond;
14223     SDVTList VTs;
14224     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14225     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14226     // X86ISD::INC).
14227     switch (CondOpcode) {
14228     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14229     case ISD::SADDO:
14230       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14231         if (C->isOne()) {
14232           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14233           break;
14234         }
14235       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14236     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14237     case ISD::SSUBO:
14238       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14239         if (C->isOne()) {
14240           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14241           break;
14242         }
14243       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14244     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14245     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14246     default: llvm_unreachable("unexpected overflowing operator");
14247     }
14248     if (Inverted)
14249       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14250     if (CondOpcode == ISD::UMULO)
14251       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14252                           MVT::i32);
14253     else
14254       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14255
14256     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14257
14258     if (CondOpcode == ISD::UMULO)
14259       Cond = X86Op.getValue(2);
14260     else
14261       Cond = X86Op.getValue(1);
14262
14263     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14264     addTest = false;
14265   } else {
14266     unsigned CondOpc;
14267     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14268       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14269       if (CondOpc == ISD::OR) {
14270         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14271         // two branches instead of an explicit OR instruction with a
14272         // separate test.
14273         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14274             isX86LogicalCmp(Cmp)) {
14275           CC = Cond.getOperand(0).getOperand(0);
14276           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14277                               Chain, Dest, CC, Cmp);
14278           CC = Cond.getOperand(1).getOperand(0);
14279           Cond = Cmp;
14280           addTest = false;
14281         }
14282       } else { // ISD::AND
14283         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14284         // two branches instead of an explicit AND instruction with a
14285         // separate test. However, we only do this if this block doesn't
14286         // have a fall-through edge, because this requires an explicit
14287         // jmp when the condition is false.
14288         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14289             isX86LogicalCmp(Cmp) &&
14290             Op.getNode()->hasOneUse()) {
14291           X86::CondCode CCode =
14292             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14293           CCode = X86::GetOppositeBranchCondition(CCode);
14294           CC = DAG.getConstant(CCode, dl, MVT::i8);
14295           SDNode *User = *Op.getNode()->use_begin();
14296           // Look for an unconditional branch following this conditional branch.
14297           // We need this because we need to reverse the successors in order
14298           // to implement FCMP_OEQ.
14299           if (User->getOpcode() == ISD::BR) {
14300             SDValue FalseBB = User->getOperand(1);
14301             SDNode *NewBR =
14302               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14303             assert(NewBR == User);
14304             (void)NewBR;
14305             Dest = FalseBB;
14306
14307             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14308                                 Chain, Dest, CC, Cmp);
14309             X86::CondCode CCode =
14310               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14311             CCode = X86::GetOppositeBranchCondition(CCode);
14312             CC = DAG.getConstant(CCode, dl, MVT::i8);
14313             Cond = Cmp;
14314             addTest = false;
14315           }
14316         }
14317       }
14318     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14319       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14320       // It should be transformed during dag combiner except when the condition
14321       // is set by a arithmetics with overflow node.
14322       X86::CondCode CCode =
14323         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14324       CCode = X86::GetOppositeBranchCondition(CCode);
14325       CC = DAG.getConstant(CCode, dl, MVT::i8);
14326       Cond = Cond.getOperand(0).getOperand(1);
14327       addTest = false;
14328     } else if (Cond.getOpcode() == ISD::SETCC &&
14329                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14330       // For FCMP_OEQ, we can emit
14331       // two branches instead of an explicit AND instruction with a
14332       // separate test. However, we only do this if this block doesn't
14333       // have a fall-through edge, because this requires an explicit
14334       // jmp when the condition is false.
14335       if (Op.getNode()->hasOneUse()) {
14336         SDNode *User = *Op.getNode()->use_begin();
14337         // Look for an unconditional branch following this conditional branch.
14338         // We need this because we need to reverse the successors in order
14339         // to implement FCMP_OEQ.
14340         if (User->getOpcode() == ISD::BR) {
14341           SDValue FalseBB = User->getOperand(1);
14342           SDNode *NewBR =
14343             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14344           assert(NewBR == User);
14345           (void)NewBR;
14346           Dest = FalseBB;
14347
14348           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14349                                     Cond.getOperand(0), Cond.getOperand(1));
14350           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14351           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14352           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14353                               Chain, Dest, CC, Cmp);
14354           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14355           Cond = Cmp;
14356           addTest = false;
14357         }
14358       }
14359     } else if (Cond.getOpcode() == ISD::SETCC &&
14360                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14361       // For FCMP_UNE, we can emit
14362       // two branches instead of an explicit AND instruction with a
14363       // separate test. However, we only do this if this block doesn't
14364       // have a fall-through edge, because this requires an explicit
14365       // jmp when the condition is false.
14366       if (Op.getNode()->hasOneUse()) {
14367         SDNode *User = *Op.getNode()->use_begin();
14368         // Look for an unconditional branch following this conditional branch.
14369         // We need this because we need to reverse the successors in order
14370         // to implement FCMP_UNE.
14371         if (User->getOpcode() == ISD::BR) {
14372           SDValue FalseBB = User->getOperand(1);
14373           SDNode *NewBR =
14374             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14375           assert(NewBR == User);
14376           (void)NewBR;
14377
14378           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14379                                     Cond.getOperand(0), Cond.getOperand(1));
14380           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14381           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14382           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14383                               Chain, Dest, CC, Cmp);
14384           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14385           Cond = Cmp;
14386           addTest = false;
14387           Dest = FalseBB;
14388         }
14389       }
14390     }
14391   }
14392
14393   if (addTest) {
14394     // Look pass the truncate if the high bits are known zero.
14395     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14396         Cond = Cond.getOperand(0);
14397
14398     // We know the result of AND is compared against zero. Try to match
14399     // it to BT.
14400     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14401       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14402       if (NewSetCC.getNode()) {
14403         CC = NewSetCC.getOperand(0);
14404         Cond = NewSetCC.getOperand(1);
14405         addTest = false;
14406       }
14407     }
14408   }
14409
14410   if (addTest) {
14411     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14412     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14413     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14414   }
14415   Cond = ConvertCmpIfNecessary(Cond, DAG);
14416   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14417                      Chain, Dest, CC, Cond);
14418 }
14419
14420 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14421 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14422 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14423 // that the guard pages used by the OS virtual memory manager are allocated in
14424 // correct sequence.
14425 SDValue
14426 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14427                                            SelectionDAG &DAG) const {
14428   MachineFunction &MF = DAG.getMachineFunction();
14429   bool SplitStack = MF.shouldSplitStack();
14430   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14431                SplitStack;
14432   SDLoc dl(Op);
14433
14434   if (!Lower) {
14435     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14436     SDNode* Node = Op.getNode();
14437
14438     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14439     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14440         " not tell us which reg is the stack pointer!");
14441     EVT VT = Node->getValueType(0);
14442     SDValue Tmp1 = SDValue(Node, 0);
14443     SDValue Tmp2 = SDValue(Node, 1);
14444     SDValue Tmp3 = Node->getOperand(2);
14445     SDValue Chain = Tmp1.getOperand(0);
14446
14447     // Chain the dynamic stack allocation so that it doesn't modify the stack
14448     // pointer when other instructions are using the stack.
14449     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14450         SDLoc(Node));
14451
14452     SDValue Size = Tmp2.getOperand(1);
14453     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14454     Chain = SP.getValue(1);
14455     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14456     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14457     unsigned StackAlign = TFI.getStackAlignment();
14458     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14459     if (Align > StackAlign)
14460       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14461           DAG.getConstant(-(uint64_t)Align, dl, VT));
14462     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14463
14464     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14465         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14466         SDLoc(Node));
14467
14468     SDValue Ops[2] = { Tmp1, Tmp2 };
14469     return DAG.getMergeValues(Ops, dl);
14470   }
14471
14472   // Get the inputs.
14473   SDValue Chain = Op.getOperand(0);
14474   SDValue Size  = Op.getOperand(1);
14475   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14476   EVT VT = Op.getNode()->getValueType(0);
14477
14478   bool Is64Bit = Subtarget->is64Bit();
14479   EVT SPTy = getPointerTy();
14480
14481   if (SplitStack) {
14482     MachineRegisterInfo &MRI = MF.getRegInfo();
14483
14484     if (Is64Bit) {
14485       // The 64 bit implementation of segmented stacks needs to clobber both r10
14486       // r11. This makes it impossible to use it along with nested parameters.
14487       const Function *F = MF.getFunction();
14488
14489       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14490            I != E; ++I)
14491         if (I->hasNestAttr())
14492           report_fatal_error("Cannot use segmented stacks with functions that "
14493                              "have nested arguments.");
14494     }
14495
14496     const TargetRegisterClass *AddrRegClass =
14497       getRegClassFor(getPointerTy());
14498     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14499     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14500     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14501                                 DAG.getRegister(Vreg, SPTy));
14502     SDValue Ops1[2] = { Value, Chain };
14503     return DAG.getMergeValues(Ops1, dl);
14504   } else {
14505     SDValue Flag;
14506     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14507
14508     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14509     Flag = Chain.getValue(1);
14510     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14511
14512     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14513
14514     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14515     unsigned SPReg = RegInfo->getStackRegister();
14516     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14517     Chain = SP.getValue(1);
14518
14519     if (Align) {
14520       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14521                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14522       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14523     }
14524
14525     SDValue Ops1[2] = { SP, Chain };
14526     return DAG.getMergeValues(Ops1, dl);
14527   }
14528 }
14529
14530 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14531   MachineFunction &MF = DAG.getMachineFunction();
14532   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14533
14534   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14535   SDLoc DL(Op);
14536
14537   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14538     // vastart just stores the address of the VarArgsFrameIndex slot into the
14539     // memory location argument.
14540     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14541                                    getPointerTy());
14542     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14543                         MachinePointerInfo(SV), false, false, 0);
14544   }
14545
14546   // __va_list_tag:
14547   //   gp_offset         (0 - 6 * 8)
14548   //   fp_offset         (48 - 48 + 8 * 16)
14549   //   overflow_arg_area (point to parameters coming in memory).
14550   //   reg_save_area
14551   SmallVector<SDValue, 8> MemOps;
14552   SDValue FIN = Op.getOperand(1);
14553   // Store gp_offset
14554   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14555                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14556                                                DL, MVT::i32),
14557                                FIN, MachinePointerInfo(SV), false, false, 0);
14558   MemOps.push_back(Store);
14559
14560   // Store fp_offset
14561   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14562                     FIN, DAG.getIntPtrConstant(4, DL));
14563   Store = DAG.getStore(Op.getOperand(0), DL,
14564                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14565                                        MVT::i32),
14566                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14567   MemOps.push_back(Store);
14568
14569   // Store ptr to overflow_arg_area
14570   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14571                     FIN, DAG.getIntPtrConstant(4, DL));
14572   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14573                                     getPointerTy());
14574   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14575                        MachinePointerInfo(SV, 8),
14576                        false, false, 0);
14577   MemOps.push_back(Store);
14578
14579   // Store ptr to reg_save_area.
14580   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14581                     FIN, DAG.getIntPtrConstant(8, DL));
14582   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14583                                     getPointerTy());
14584   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14585                        MachinePointerInfo(SV, 16), false, false, 0);
14586   MemOps.push_back(Store);
14587   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14588 }
14589
14590 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14591   assert(Subtarget->is64Bit() &&
14592          "LowerVAARG only handles 64-bit va_arg!");
14593   assert((Subtarget->isTargetLinux() ||
14594           Subtarget->isTargetDarwin()) &&
14595           "Unhandled target in LowerVAARG");
14596   assert(Op.getNode()->getNumOperands() == 4);
14597   SDValue Chain = Op.getOperand(0);
14598   SDValue SrcPtr = Op.getOperand(1);
14599   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14600   unsigned Align = Op.getConstantOperandVal(3);
14601   SDLoc dl(Op);
14602
14603   EVT ArgVT = Op.getNode()->getValueType(0);
14604   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14605   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14606   uint8_t ArgMode;
14607
14608   // Decide which area this value should be read from.
14609   // TODO: Implement the AMD64 ABI in its entirety. This simple
14610   // selection mechanism works only for the basic types.
14611   if (ArgVT == MVT::f80) {
14612     llvm_unreachable("va_arg for f80 not yet implemented");
14613   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14614     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14615   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14616     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14617   } else {
14618     llvm_unreachable("Unhandled argument type in LowerVAARG");
14619   }
14620
14621   if (ArgMode == 2) {
14622     // Sanity Check: Make sure using fp_offset makes sense.
14623     assert(!Subtarget->useSoftFloat() &&
14624            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14625                Attribute::NoImplicitFloat)) &&
14626            Subtarget->hasSSE1());
14627   }
14628
14629   // Insert VAARG_64 node into the DAG
14630   // VAARG_64 returns two values: Variable Argument Address, Chain
14631   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14632                        DAG.getConstant(ArgMode, dl, MVT::i8),
14633                        DAG.getConstant(Align, dl, MVT::i32)};
14634   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14635   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14636                                           VTs, InstOps, MVT::i64,
14637                                           MachinePointerInfo(SV),
14638                                           /*Align=*/0,
14639                                           /*Volatile=*/false,
14640                                           /*ReadMem=*/true,
14641                                           /*WriteMem=*/true);
14642   Chain = VAARG.getValue(1);
14643
14644   // Load the next argument and return it
14645   return DAG.getLoad(ArgVT, dl,
14646                      Chain,
14647                      VAARG,
14648                      MachinePointerInfo(),
14649                      false, false, false, 0);
14650 }
14651
14652 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14653                            SelectionDAG &DAG) {
14654   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14655   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14656   SDValue Chain = Op.getOperand(0);
14657   SDValue DstPtr = Op.getOperand(1);
14658   SDValue SrcPtr = Op.getOperand(2);
14659   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14660   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14661   SDLoc DL(Op);
14662
14663   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14664                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14665                        false, false,
14666                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14667 }
14668
14669 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14670 // amount is a constant. Takes immediate version of shift as input.
14671 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14672                                           SDValue SrcOp, uint64_t ShiftAmt,
14673                                           SelectionDAG &DAG) {
14674   MVT ElementType = VT.getVectorElementType();
14675
14676   // Fold this packed shift into its first operand if ShiftAmt is 0.
14677   if (ShiftAmt == 0)
14678     return SrcOp;
14679
14680   // Check for ShiftAmt >= element width
14681   if (ShiftAmt >= ElementType.getSizeInBits()) {
14682     if (Opc == X86ISD::VSRAI)
14683       ShiftAmt = ElementType.getSizeInBits() - 1;
14684     else
14685       return DAG.getConstant(0, dl, VT);
14686   }
14687
14688   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14689          && "Unknown target vector shift-by-constant node");
14690
14691   // Fold this packed vector shift into a build vector if SrcOp is a
14692   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14693   if (VT == SrcOp.getSimpleValueType() &&
14694       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14695     SmallVector<SDValue, 8> Elts;
14696     unsigned NumElts = SrcOp->getNumOperands();
14697     ConstantSDNode *ND;
14698
14699     switch(Opc) {
14700     default: llvm_unreachable(nullptr);
14701     case X86ISD::VSHLI:
14702       for (unsigned i=0; i!=NumElts; ++i) {
14703         SDValue CurrentOp = SrcOp->getOperand(i);
14704         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14705           Elts.push_back(CurrentOp);
14706           continue;
14707         }
14708         ND = cast<ConstantSDNode>(CurrentOp);
14709         const APInt &C = ND->getAPIntValue();
14710         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14711       }
14712       break;
14713     case X86ISD::VSRLI:
14714       for (unsigned i=0; i!=NumElts; ++i) {
14715         SDValue CurrentOp = SrcOp->getOperand(i);
14716         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14717           Elts.push_back(CurrentOp);
14718           continue;
14719         }
14720         ND = cast<ConstantSDNode>(CurrentOp);
14721         const APInt &C = ND->getAPIntValue();
14722         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14723       }
14724       break;
14725     case X86ISD::VSRAI:
14726       for (unsigned i=0; i!=NumElts; ++i) {
14727         SDValue CurrentOp = SrcOp->getOperand(i);
14728         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14729           Elts.push_back(CurrentOp);
14730           continue;
14731         }
14732         ND = cast<ConstantSDNode>(CurrentOp);
14733         const APInt &C = ND->getAPIntValue();
14734         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14735       }
14736       break;
14737     }
14738
14739     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14740   }
14741
14742   return DAG.getNode(Opc, dl, VT, SrcOp,
14743                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14744 }
14745
14746 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14747 // may or may not be a constant. Takes immediate version of shift as input.
14748 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14749                                    SDValue SrcOp, SDValue ShAmt,
14750                                    SelectionDAG &DAG) {
14751   MVT SVT = ShAmt.getSimpleValueType();
14752   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14753
14754   // Catch shift-by-constant.
14755   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14756     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14757                                       CShAmt->getZExtValue(), DAG);
14758
14759   // Change opcode to non-immediate version
14760   switch (Opc) {
14761     default: llvm_unreachable("Unknown target vector shift node");
14762     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14763     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14764     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14765   }
14766
14767   const X86Subtarget &Subtarget =
14768       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14769   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14770       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14771     // Let the shuffle legalizer expand this shift amount node.
14772     SDValue Op0 = ShAmt.getOperand(0);
14773     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14774     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14775   } else {
14776     // Need to build a vector containing shift amount.
14777     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14778     SmallVector<SDValue, 4> ShOps;
14779     ShOps.push_back(ShAmt);
14780     if (SVT == MVT::i32) {
14781       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14782       ShOps.push_back(DAG.getUNDEF(SVT));
14783     }
14784     ShOps.push_back(DAG.getUNDEF(SVT));
14785
14786     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14787     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14788   }
14789
14790   // The return type has to be a 128-bit type with the same element
14791   // type as the input type.
14792   MVT EltVT = VT.getVectorElementType();
14793   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14794
14795   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14796   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14797 }
14798
14799 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14800 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14801 /// necessary casting for \p Mask when lowering masking intrinsics.
14802 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14803                                     SDValue PreservedSrc,
14804                                     const X86Subtarget *Subtarget,
14805                                     SelectionDAG &DAG) {
14806     EVT VT = Op.getValueType();
14807     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14808                                   MVT::i1, VT.getVectorNumElements());
14809     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14810                                      Mask.getValueType().getSizeInBits());
14811     SDLoc dl(Op);
14812
14813     assert(MaskVT.isSimple() && "invalid mask type");
14814
14815     if (isAllOnes(Mask))
14816       return Op;
14817
14818     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14819     // are extracted by EXTRACT_SUBVECTOR.
14820     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14821                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14822                               DAG.getIntPtrConstant(0, dl));
14823
14824     switch (Op.getOpcode()) {
14825       default: break;
14826       case X86ISD::PCMPEQM:
14827       case X86ISD::PCMPGTM:
14828       case X86ISD::CMPM:
14829       case X86ISD::CMPMU:
14830         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14831     }
14832     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14833       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14834     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14835 }
14836
14837 /// \brief Creates an SDNode for a predicated scalar operation.
14838 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14839 /// The mask is comming as MVT::i8 and it should be truncated
14840 /// to MVT::i1 while lowering masking intrinsics.
14841 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14842 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14843 /// a scalar instruction.
14844 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14845                                     SDValue PreservedSrc,
14846                                     const X86Subtarget *Subtarget,
14847                                     SelectionDAG &DAG) {
14848     if (isAllOnes(Mask))
14849       return Op;
14850
14851     EVT VT = Op.getValueType();
14852     SDLoc dl(Op);
14853     // The mask should be of type MVT::i1
14854     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14855
14856     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14857       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14858     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14859 }
14860
14861 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14862                                        SelectionDAG &DAG) {
14863   SDLoc dl(Op);
14864   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14865   EVT VT = Op.getValueType();
14866   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14867   if (IntrData) {
14868     switch(IntrData->Type) {
14869     case INTR_TYPE_1OP:
14870       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14871     case INTR_TYPE_2OP:
14872       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14873         Op.getOperand(2));
14874     case INTR_TYPE_3OP:
14875       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14876         Op.getOperand(2), Op.getOperand(3));
14877     case INTR_TYPE_1OP_MASK_RM: {
14878       SDValue Src = Op.getOperand(1);
14879       SDValue Src0 = Op.getOperand(2);
14880       SDValue Mask = Op.getOperand(3);
14881       SDValue RoundingMode = Op.getOperand(4);
14882       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14883                                               RoundingMode),
14884                                   Mask, Src0, Subtarget, DAG);
14885     }
14886     case INTR_TYPE_SCALAR_MASK_RM: {
14887       SDValue Src1 = Op.getOperand(1);
14888       SDValue Src2 = Op.getOperand(2);
14889       SDValue Src0 = Op.getOperand(3);
14890       SDValue Mask = Op.getOperand(4);
14891       // There are 2 kinds of intrinsics in this group:
14892       // (1) With supress-all-exceptions (sae) - 6 operands
14893       // (2) With rounding mode and sae - 7 operands.
14894       if (Op.getNumOperands() == 6) {
14895         SDValue Sae  = Op.getOperand(5);
14896         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14897                                                 Sae),
14898                                     Mask, Src0, Subtarget, DAG);
14899       }
14900       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14901       SDValue RoundingMode  = Op.getOperand(5);
14902       SDValue Sae  = Op.getOperand(6);
14903       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14904                                               RoundingMode, Sae),
14905                                   Mask, Src0, Subtarget, DAG);
14906     }
14907     case INTR_TYPE_2OP_MASK: {
14908       SDValue Src1 = Op.getOperand(1);
14909       SDValue Src2 = Op.getOperand(2);
14910       SDValue PassThru = Op.getOperand(3);
14911       SDValue Mask = Op.getOperand(4);
14912       // We specify 2 possible opcodes for intrinsics with rounding modes.
14913       // First, we check if the intrinsic may have non-default rounding mode,
14914       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14915       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14916       if (IntrWithRoundingModeOpcode != 0) {
14917         SDValue Rnd = Op.getOperand(5);
14918         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14919         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14920           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14921                                       dl, Op.getValueType(),
14922                                       Src1, Src2, Rnd),
14923                                       Mask, PassThru, Subtarget, DAG);
14924         }
14925       }
14926       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14927                                               Src1,Src2),
14928                                   Mask, PassThru, Subtarget, DAG);
14929     }
14930     case FMA_OP_MASK: {
14931       SDValue Src1 = Op.getOperand(1);
14932       SDValue Src2 = Op.getOperand(2);
14933       SDValue Src3 = Op.getOperand(3);
14934       SDValue Mask = Op.getOperand(4);
14935       // We specify 2 possible opcodes for intrinsics with rounding modes.
14936       // First, we check if the intrinsic may have non-default rounding mode,
14937       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14938       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14939       if (IntrWithRoundingModeOpcode != 0) {
14940         SDValue Rnd = Op.getOperand(5);
14941         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14942             X86::STATIC_ROUNDING::CUR_DIRECTION)
14943           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14944                                                   dl, Op.getValueType(),
14945                                                   Src1, Src2, Src3, Rnd),
14946                                       Mask, Src1, Subtarget, DAG);
14947       }
14948       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14949                                               dl, Op.getValueType(),
14950                                               Src1, Src2, Src3),
14951                                   Mask, Src1, Subtarget, DAG);
14952     }
14953     case CMP_MASK:
14954     case CMP_MASK_CC: {
14955       // Comparison intrinsics with masks.
14956       // Example of transformation:
14957       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14958       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14959       // (i8 (bitcast
14960       //   (v8i1 (insert_subvector undef,
14961       //           (v2i1 (and (PCMPEQM %a, %b),
14962       //                      (extract_subvector
14963       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14964       EVT VT = Op.getOperand(1).getValueType();
14965       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14966                                     VT.getVectorNumElements());
14967       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14968       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14969                                        Mask.getValueType().getSizeInBits());
14970       SDValue Cmp;
14971       if (IntrData->Type == CMP_MASK_CC) {
14972         SDValue CC = Op.getOperand(3);
14973         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
14974         // We specify 2 possible opcodes for intrinsics with rounding modes.
14975         // First, we check if the intrinsic may have non-default rounding mode,
14976         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14977         if (IntrData->Opc1 != 0) {
14978           SDValue Rnd = Op.getOperand(5);
14979           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14980               X86::STATIC_ROUNDING::CUR_DIRECTION)
14981             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
14982                               Op.getOperand(2), CC, Rnd);
14983         }
14984         //default rounding mode
14985         if(!Cmp.getNode())
14986             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14987                               Op.getOperand(2), CC);
14988
14989       } else {
14990         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14991         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14992                           Op.getOperand(2));
14993       }
14994       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14995                                              DAG.getTargetConstant(0, dl,
14996                                                                    MaskVT),
14997                                              Subtarget, DAG);
14998       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14999                                 DAG.getUNDEF(BitcastVT), CmpMask,
15000                                 DAG.getIntPtrConstant(0, dl));
15001       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15002     }
15003     case COMI: { // Comparison intrinsics
15004       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15005       SDValue LHS = Op.getOperand(1);
15006       SDValue RHS = Op.getOperand(2);
15007       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15008       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15009       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15010       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15011                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15012       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15013     }
15014     case VSHIFT:
15015       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15016                                  Op.getOperand(1), Op.getOperand(2), DAG);
15017     case VSHIFT_MASK:
15018       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15019                                                       Op.getSimpleValueType(),
15020                                                       Op.getOperand(1),
15021                                                       Op.getOperand(2), DAG),
15022                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15023                                   DAG);
15024     case COMPRESS_EXPAND_IN_REG: {
15025       SDValue Mask = Op.getOperand(3);
15026       SDValue DataToCompress = Op.getOperand(1);
15027       SDValue PassThru = Op.getOperand(2);
15028       if (isAllOnes(Mask)) // return data as is
15029         return Op.getOperand(1);
15030       EVT VT = Op.getValueType();
15031       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15032                                     VT.getVectorNumElements());
15033       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15034                                        Mask.getValueType().getSizeInBits());
15035       SDLoc dl(Op);
15036       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15037                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15038                                   DAG.getIntPtrConstant(0, dl));
15039
15040       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15041                          PassThru);
15042     }
15043     case BLEND: {
15044       SDValue Mask = Op.getOperand(3);
15045       EVT VT = Op.getValueType();
15046       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15047                                     VT.getVectorNumElements());
15048       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15049                                        Mask.getValueType().getSizeInBits());
15050       SDLoc dl(Op);
15051       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15052                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15053                                   DAG.getIntPtrConstant(0, dl));
15054       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15055                          Op.getOperand(2));
15056     }
15057     default:
15058       break;
15059     }
15060   }
15061
15062   switch (IntNo) {
15063   default: return SDValue();    // Don't custom lower most intrinsics.
15064
15065   case Intrinsic::x86_avx2_permd:
15066   case Intrinsic::x86_avx2_permps:
15067     // Operands intentionally swapped. Mask is last operand to intrinsic,
15068     // but second operand for node/instruction.
15069     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15070                        Op.getOperand(2), Op.getOperand(1));
15071
15072   case Intrinsic::x86_avx512_mask_valign_q_512:
15073   case Intrinsic::x86_avx512_mask_valign_d_512:
15074     // Vector source operands are swapped.
15075     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15076                                             Op.getValueType(), Op.getOperand(2),
15077                                             Op.getOperand(1),
15078                                             Op.getOperand(3)),
15079                                 Op.getOperand(5), Op.getOperand(4),
15080                                 Subtarget, DAG);
15081
15082   // ptest and testp intrinsics. The intrinsic these come from are designed to
15083   // return an integer value, not just an instruction so lower it to the ptest
15084   // or testp pattern and a setcc for the result.
15085   case Intrinsic::x86_sse41_ptestz:
15086   case Intrinsic::x86_sse41_ptestc:
15087   case Intrinsic::x86_sse41_ptestnzc:
15088   case Intrinsic::x86_avx_ptestz_256:
15089   case Intrinsic::x86_avx_ptestc_256:
15090   case Intrinsic::x86_avx_ptestnzc_256:
15091   case Intrinsic::x86_avx_vtestz_ps:
15092   case Intrinsic::x86_avx_vtestc_ps:
15093   case Intrinsic::x86_avx_vtestnzc_ps:
15094   case Intrinsic::x86_avx_vtestz_pd:
15095   case Intrinsic::x86_avx_vtestc_pd:
15096   case Intrinsic::x86_avx_vtestnzc_pd:
15097   case Intrinsic::x86_avx_vtestz_ps_256:
15098   case Intrinsic::x86_avx_vtestc_ps_256:
15099   case Intrinsic::x86_avx_vtestnzc_ps_256:
15100   case Intrinsic::x86_avx_vtestz_pd_256:
15101   case Intrinsic::x86_avx_vtestc_pd_256:
15102   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15103     bool IsTestPacked = false;
15104     unsigned X86CC;
15105     switch (IntNo) {
15106     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15107     case Intrinsic::x86_avx_vtestz_ps:
15108     case Intrinsic::x86_avx_vtestz_pd:
15109     case Intrinsic::x86_avx_vtestz_ps_256:
15110     case Intrinsic::x86_avx_vtestz_pd_256:
15111       IsTestPacked = true; // Fallthrough
15112     case Intrinsic::x86_sse41_ptestz:
15113     case Intrinsic::x86_avx_ptestz_256:
15114       // ZF = 1
15115       X86CC = X86::COND_E;
15116       break;
15117     case Intrinsic::x86_avx_vtestc_ps:
15118     case Intrinsic::x86_avx_vtestc_pd:
15119     case Intrinsic::x86_avx_vtestc_ps_256:
15120     case Intrinsic::x86_avx_vtestc_pd_256:
15121       IsTestPacked = true; // Fallthrough
15122     case Intrinsic::x86_sse41_ptestc:
15123     case Intrinsic::x86_avx_ptestc_256:
15124       // CF = 1
15125       X86CC = X86::COND_B;
15126       break;
15127     case Intrinsic::x86_avx_vtestnzc_ps:
15128     case Intrinsic::x86_avx_vtestnzc_pd:
15129     case Intrinsic::x86_avx_vtestnzc_ps_256:
15130     case Intrinsic::x86_avx_vtestnzc_pd_256:
15131       IsTestPacked = true; // Fallthrough
15132     case Intrinsic::x86_sse41_ptestnzc:
15133     case Intrinsic::x86_avx_ptestnzc_256:
15134       // ZF and CF = 0
15135       X86CC = X86::COND_A;
15136       break;
15137     }
15138
15139     SDValue LHS = Op.getOperand(1);
15140     SDValue RHS = Op.getOperand(2);
15141     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15142     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15143     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15144     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15145     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15146   }
15147   case Intrinsic::x86_avx512_kortestz_w:
15148   case Intrinsic::x86_avx512_kortestc_w: {
15149     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15150     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15151     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15152     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15153     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15154     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15155     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15156   }
15157
15158   case Intrinsic::x86_sse42_pcmpistria128:
15159   case Intrinsic::x86_sse42_pcmpestria128:
15160   case Intrinsic::x86_sse42_pcmpistric128:
15161   case Intrinsic::x86_sse42_pcmpestric128:
15162   case Intrinsic::x86_sse42_pcmpistrio128:
15163   case Intrinsic::x86_sse42_pcmpestrio128:
15164   case Intrinsic::x86_sse42_pcmpistris128:
15165   case Intrinsic::x86_sse42_pcmpestris128:
15166   case Intrinsic::x86_sse42_pcmpistriz128:
15167   case Intrinsic::x86_sse42_pcmpestriz128: {
15168     unsigned Opcode;
15169     unsigned X86CC;
15170     switch (IntNo) {
15171     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15172     case Intrinsic::x86_sse42_pcmpistria128:
15173       Opcode = X86ISD::PCMPISTRI;
15174       X86CC = X86::COND_A;
15175       break;
15176     case Intrinsic::x86_sse42_pcmpestria128:
15177       Opcode = X86ISD::PCMPESTRI;
15178       X86CC = X86::COND_A;
15179       break;
15180     case Intrinsic::x86_sse42_pcmpistric128:
15181       Opcode = X86ISD::PCMPISTRI;
15182       X86CC = X86::COND_B;
15183       break;
15184     case Intrinsic::x86_sse42_pcmpestric128:
15185       Opcode = X86ISD::PCMPESTRI;
15186       X86CC = X86::COND_B;
15187       break;
15188     case Intrinsic::x86_sse42_pcmpistrio128:
15189       Opcode = X86ISD::PCMPISTRI;
15190       X86CC = X86::COND_O;
15191       break;
15192     case Intrinsic::x86_sse42_pcmpestrio128:
15193       Opcode = X86ISD::PCMPESTRI;
15194       X86CC = X86::COND_O;
15195       break;
15196     case Intrinsic::x86_sse42_pcmpistris128:
15197       Opcode = X86ISD::PCMPISTRI;
15198       X86CC = X86::COND_S;
15199       break;
15200     case Intrinsic::x86_sse42_pcmpestris128:
15201       Opcode = X86ISD::PCMPESTRI;
15202       X86CC = X86::COND_S;
15203       break;
15204     case Intrinsic::x86_sse42_pcmpistriz128:
15205       Opcode = X86ISD::PCMPISTRI;
15206       X86CC = X86::COND_E;
15207       break;
15208     case Intrinsic::x86_sse42_pcmpestriz128:
15209       Opcode = X86ISD::PCMPESTRI;
15210       X86CC = X86::COND_E;
15211       break;
15212     }
15213     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15214     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15215     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15216     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15217                                 DAG.getConstant(X86CC, dl, MVT::i8),
15218                                 SDValue(PCMP.getNode(), 1));
15219     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15220   }
15221
15222   case Intrinsic::x86_sse42_pcmpistri128:
15223   case Intrinsic::x86_sse42_pcmpestri128: {
15224     unsigned Opcode;
15225     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15226       Opcode = X86ISD::PCMPISTRI;
15227     else
15228       Opcode = X86ISD::PCMPESTRI;
15229
15230     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15231     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15232     return DAG.getNode(Opcode, dl, VTs, NewOps);
15233   }
15234   }
15235 }
15236
15237 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15238                               SDValue Src, SDValue Mask, SDValue Base,
15239                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15240                               const X86Subtarget * Subtarget) {
15241   SDLoc dl(Op);
15242   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15243   assert(C && "Invalid scale type");
15244   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15245   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15246                              Index.getSimpleValueType().getVectorNumElements());
15247   SDValue MaskInReg;
15248   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15249   if (MaskC)
15250     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15251   else
15252     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15253   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15254   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15255   SDValue Segment = DAG.getRegister(0, MVT::i32);
15256   if (Src.getOpcode() == ISD::UNDEF)
15257     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15258   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15259   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15260   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15261   return DAG.getMergeValues(RetOps, dl);
15262 }
15263
15264 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15265                                SDValue Src, SDValue Mask, SDValue Base,
15266                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15267   SDLoc dl(Op);
15268   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15269   assert(C && "Invalid scale type");
15270   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15271   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15272   SDValue Segment = DAG.getRegister(0, MVT::i32);
15273   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15274                              Index.getSimpleValueType().getVectorNumElements());
15275   SDValue MaskInReg;
15276   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15277   if (MaskC)
15278     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15279   else
15280     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15281   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15282   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15283   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15284   return SDValue(Res, 1);
15285 }
15286
15287 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15288                                SDValue Mask, SDValue Base, SDValue Index,
15289                                SDValue ScaleOp, SDValue Chain) {
15290   SDLoc dl(Op);
15291   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15292   assert(C && "Invalid scale type");
15293   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15294   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15295   SDValue Segment = DAG.getRegister(0, MVT::i32);
15296   EVT MaskVT =
15297     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15298   SDValue MaskInReg;
15299   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15300   if (MaskC)
15301     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15302   else
15303     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15304   //SDVTList VTs = DAG.getVTList(MVT::Other);
15305   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15306   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15307   return SDValue(Res, 0);
15308 }
15309
15310 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15311 // read performance monitor counters (x86_rdpmc).
15312 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15313                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15314                               SmallVectorImpl<SDValue> &Results) {
15315   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15316   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15317   SDValue LO, HI;
15318
15319   // The ECX register is used to select the index of the performance counter
15320   // to read.
15321   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15322                                    N->getOperand(2));
15323   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15324
15325   // Reads the content of a 64-bit performance counter and returns it in the
15326   // registers EDX:EAX.
15327   if (Subtarget->is64Bit()) {
15328     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15329     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15330                             LO.getValue(2));
15331   } else {
15332     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15333     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15334                             LO.getValue(2));
15335   }
15336   Chain = HI.getValue(1);
15337
15338   if (Subtarget->is64Bit()) {
15339     // The EAX register is loaded with the low-order 32 bits. The EDX register
15340     // is loaded with the supported high-order bits of the counter.
15341     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15342                               DAG.getConstant(32, DL, MVT::i8));
15343     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15344     Results.push_back(Chain);
15345     return;
15346   }
15347
15348   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15349   SDValue Ops[] = { LO, HI };
15350   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15351   Results.push_back(Pair);
15352   Results.push_back(Chain);
15353 }
15354
15355 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15356 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15357 // also used to custom lower READCYCLECOUNTER nodes.
15358 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15359                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15360                               SmallVectorImpl<SDValue> &Results) {
15361   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15362   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15363   SDValue LO, HI;
15364
15365   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15366   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15367   // and the EAX register is loaded with the low-order 32 bits.
15368   if (Subtarget->is64Bit()) {
15369     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15370     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15371                             LO.getValue(2));
15372   } else {
15373     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15374     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15375                             LO.getValue(2));
15376   }
15377   SDValue Chain = HI.getValue(1);
15378
15379   if (Opcode == X86ISD::RDTSCP_DAG) {
15380     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15381
15382     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15383     // the ECX register. Add 'ecx' explicitly to the chain.
15384     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15385                                      HI.getValue(2));
15386     // Explicitly store the content of ECX at the location passed in input
15387     // to the 'rdtscp' intrinsic.
15388     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15389                          MachinePointerInfo(), false, false, 0);
15390   }
15391
15392   if (Subtarget->is64Bit()) {
15393     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15394     // the EAX register is loaded with the low-order 32 bits.
15395     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15396                               DAG.getConstant(32, DL, MVT::i8));
15397     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15398     Results.push_back(Chain);
15399     return;
15400   }
15401
15402   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15403   SDValue Ops[] = { LO, HI };
15404   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15405   Results.push_back(Pair);
15406   Results.push_back(Chain);
15407 }
15408
15409 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15410                                      SelectionDAG &DAG) {
15411   SmallVector<SDValue, 2> Results;
15412   SDLoc DL(Op);
15413   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15414                           Results);
15415   return DAG.getMergeValues(Results, DL);
15416 }
15417
15418
15419 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15420                                       SelectionDAG &DAG) {
15421   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15422
15423   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15424   if (!IntrData)
15425     return SDValue();
15426
15427   SDLoc dl(Op);
15428   switch(IntrData->Type) {
15429   default:
15430     llvm_unreachable("Unknown Intrinsic Type");
15431     break;
15432   case RDSEED:
15433   case RDRAND: {
15434     // Emit the node with the right value type.
15435     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15436     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15437
15438     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15439     // Otherwise return the value from Rand, which is always 0, casted to i32.
15440     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15441                       DAG.getConstant(1, dl, Op->getValueType(1)),
15442                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15443                       SDValue(Result.getNode(), 1) };
15444     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15445                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15446                                   Ops);
15447
15448     // Return { result, isValid, chain }.
15449     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15450                        SDValue(Result.getNode(), 2));
15451   }
15452   case GATHER: {
15453   //gather(v1, mask, index, base, scale);
15454     SDValue Chain = Op.getOperand(0);
15455     SDValue Src   = Op.getOperand(2);
15456     SDValue Base  = Op.getOperand(3);
15457     SDValue Index = Op.getOperand(4);
15458     SDValue Mask  = Op.getOperand(5);
15459     SDValue Scale = Op.getOperand(6);
15460     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15461                          Chain, Subtarget);
15462   }
15463   case SCATTER: {
15464   //scatter(base, mask, index, v1, scale);
15465     SDValue Chain = Op.getOperand(0);
15466     SDValue Base  = Op.getOperand(2);
15467     SDValue Mask  = Op.getOperand(3);
15468     SDValue Index = Op.getOperand(4);
15469     SDValue Src   = Op.getOperand(5);
15470     SDValue Scale = Op.getOperand(6);
15471     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15472                           Scale, Chain);
15473   }
15474   case PREFETCH: {
15475     SDValue Hint = Op.getOperand(6);
15476     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15477     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15478     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15479     SDValue Chain = Op.getOperand(0);
15480     SDValue Mask  = Op.getOperand(2);
15481     SDValue Index = Op.getOperand(3);
15482     SDValue Base  = Op.getOperand(4);
15483     SDValue Scale = Op.getOperand(5);
15484     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15485   }
15486   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15487   case RDTSC: {
15488     SmallVector<SDValue, 2> Results;
15489     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15490                             Results);
15491     return DAG.getMergeValues(Results, dl);
15492   }
15493   // Read Performance Monitoring Counters.
15494   case RDPMC: {
15495     SmallVector<SDValue, 2> Results;
15496     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15497     return DAG.getMergeValues(Results, dl);
15498   }
15499   // XTEST intrinsics.
15500   case XTEST: {
15501     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15502     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15503     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15504                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15505                                 InTrans);
15506     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15507     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15508                        Ret, SDValue(InTrans.getNode(), 1));
15509   }
15510   // ADC/ADCX/SBB
15511   case ADX: {
15512     SmallVector<SDValue, 2> Results;
15513     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15514     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15515     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15516                                 DAG.getConstant(-1, dl, MVT::i8));
15517     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15518                               Op.getOperand(4), GenCF.getValue(1));
15519     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15520                                  Op.getOperand(5), MachinePointerInfo(),
15521                                  false, false, 0);
15522     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15523                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15524                                 Res.getValue(1));
15525     Results.push_back(SetCC);
15526     Results.push_back(Store);
15527     return DAG.getMergeValues(Results, dl);
15528   }
15529   case COMPRESS_TO_MEM: {
15530     SDLoc dl(Op);
15531     SDValue Mask = Op.getOperand(4);
15532     SDValue DataToCompress = Op.getOperand(3);
15533     SDValue Addr = Op.getOperand(2);
15534     SDValue Chain = Op.getOperand(0);
15535
15536     if (isAllOnes(Mask)) // return just a store
15537       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15538                           MachinePointerInfo(), false, false, 0);
15539
15540     EVT VT = DataToCompress.getValueType();
15541     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15542                                   VT.getVectorNumElements());
15543     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15544                                      Mask.getValueType().getSizeInBits());
15545     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15546                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15547                                 DAG.getIntPtrConstant(0, dl));
15548
15549     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15550                                       DataToCompress, DAG.getUNDEF(VT));
15551     return DAG.getStore(Chain, dl, Compressed, Addr,
15552                         MachinePointerInfo(), false, false, 0);
15553   }
15554   case EXPAND_FROM_MEM: {
15555     SDLoc dl(Op);
15556     SDValue Mask = Op.getOperand(4);
15557     SDValue PathThru = Op.getOperand(3);
15558     SDValue Addr = Op.getOperand(2);
15559     SDValue Chain = Op.getOperand(0);
15560     EVT VT = Op.getValueType();
15561
15562     if (isAllOnes(Mask)) // return just a load
15563       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15564                          false, 0);
15565     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15566                                   VT.getVectorNumElements());
15567     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15568                                      Mask.getValueType().getSizeInBits());
15569     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15570                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15571                                 DAG.getIntPtrConstant(0, dl));
15572
15573     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15574                                    false, false, false, 0);
15575
15576     SDValue Results[] = {
15577         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15578         Chain};
15579     return DAG.getMergeValues(Results, dl);
15580   }
15581   }
15582 }
15583
15584 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15585                                            SelectionDAG &DAG) const {
15586   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15587   MFI->setReturnAddressIsTaken(true);
15588
15589   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15590     return SDValue();
15591
15592   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15593   SDLoc dl(Op);
15594   EVT PtrVT = getPointerTy();
15595
15596   if (Depth > 0) {
15597     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15598     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15599     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15600     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15601                        DAG.getNode(ISD::ADD, dl, PtrVT,
15602                                    FrameAddr, Offset),
15603                        MachinePointerInfo(), false, false, false, 0);
15604   }
15605
15606   // Just load the return address.
15607   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15608   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15609                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15610 }
15611
15612 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15613   MachineFunction &MF = DAG.getMachineFunction();
15614   MachineFrameInfo *MFI = MF.getFrameInfo();
15615   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15616   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15617   EVT VT = Op.getValueType();
15618
15619   MFI->setFrameAddressIsTaken(true);
15620
15621   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15622     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15623     // is not possible to crawl up the stack without looking at the unwind codes
15624     // simultaneously.
15625     int FrameAddrIndex = FuncInfo->getFAIndex();
15626     if (!FrameAddrIndex) {
15627       // Set up a frame object for the return address.
15628       unsigned SlotSize = RegInfo->getSlotSize();
15629       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15630           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15631       FuncInfo->setFAIndex(FrameAddrIndex);
15632     }
15633     return DAG.getFrameIndex(FrameAddrIndex, VT);
15634   }
15635
15636   unsigned FrameReg =
15637       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15638   SDLoc dl(Op);  // FIXME probably not meaningful
15639   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15640   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15641           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15642          "Invalid Frame Register!");
15643   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15644   while (Depth--)
15645     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15646                             MachinePointerInfo(),
15647                             false, false, false, 0);
15648   return FrameAddr;
15649 }
15650
15651 // FIXME? Maybe this could be a TableGen attribute on some registers and
15652 // this table could be generated automatically from RegInfo.
15653 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15654                                               EVT VT) const {
15655   unsigned Reg = StringSwitch<unsigned>(RegName)
15656                        .Case("esp", X86::ESP)
15657                        .Case("rsp", X86::RSP)
15658                        .Default(0);
15659   if (Reg)
15660     return Reg;
15661   report_fatal_error("Invalid register name global variable");
15662 }
15663
15664 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15665                                                      SelectionDAG &DAG) const {
15666   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15667   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15668 }
15669
15670 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15671   SDValue Chain     = Op.getOperand(0);
15672   SDValue Offset    = Op.getOperand(1);
15673   SDValue Handler   = Op.getOperand(2);
15674   SDLoc dl      (Op);
15675
15676   EVT PtrVT = getPointerTy();
15677   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15678   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15679   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15680           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15681          "Invalid Frame Register!");
15682   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15683   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15684
15685   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15686                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15687                                                        dl));
15688   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15689   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15690                        false, false, 0);
15691   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15692
15693   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15694                      DAG.getRegister(StoreAddrReg, PtrVT));
15695 }
15696
15697 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15698                                                SelectionDAG &DAG) const {
15699   SDLoc DL(Op);
15700   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15701                      DAG.getVTList(MVT::i32, MVT::Other),
15702                      Op.getOperand(0), Op.getOperand(1));
15703 }
15704
15705 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15706                                                 SelectionDAG &DAG) const {
15707   SDLoc DL(Op);
15708   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15709                      Op.getOperand(0), Op.getOperand(1));
15710 }
15711
15712 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15713   return Op.getOperand(0);
15714 }
15715
15716 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15717                                                 SelectionDAG &DAG) const {
15718   SDValue Root = Op.getOperand(0);
15719   SDValue Trmp = Op.getOperand(1); // trampoline
15720   SDValue FPtr = Op.getOperand(2); // nested function
15721   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15722   SDLoc dl (Op);
15723
15724   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15725   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15726
15727   if (Subtarget->is64Bit()) {
15728     SDValue OutChains[6];
15729
15730     // Large code-model.
15731     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15732     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15733
15734     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15735     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15736
15737     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15738
15739     // Load the pointer to the nested function into R11.
15740     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15741     SDValue Addr = Trmp;
15742     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15743                                 Addr, MachinePointerInfo(TrmpAddr),
15744                                 false, false, 0);
15745
15746     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15747                        DAG.getConstant(2, dl, MVT::i64));
15748     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15749                                 MachinePointerInfo(TrmpAddr, 2),
15750                                 false, false, 2);
15751
15752     // Load the 'nest' parameter value into R10.
15753     // R10 is specified in X86CallingConv.td
15754     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15755     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15756                        DAG.getConstant(10, dl, MVT::i64));
15757     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15758                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15759                                 false, false, 0);
15760
15761     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15762                        DAG.getConstant(12, dl, MVT::i64));
15763     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15764                                 MachinePointerInfo(TrmpAddr, 12),
15765                                 false, false, 2);
15766
15767     // Jump to the nested function.
15768     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15769     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15770                        DAG.getConstant(20, dl, MVT::i64));
15771     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15772                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15773                                 false, false, 0);
15774
15775     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15776     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15777                        DAG.getConstant(22, dl, MVT::i64));
15778     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15779                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15780                                 false, false, 0);
15781
15782     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15783   } else {
15784     const Function *Func =
15785       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15786     CallingConv::ID CC = Func->getCallingConv();
15787     unsigned NestReg;
15788
15789     switch (CC) {
15790     default:
15791       llvm_unreachable("Unsupported calling convention");
15792     case CallingConv::C:
15793     case CallingConv::X86_StdCall: {
15794       // Pass 'nest' parameter in ECX.
15795       // Must be kept in sync with X86CallingConv.td
15796       NestReg = X86::ECX;
15797
15798       // Check that ECX wasn't needed by an 'inreg' parameter.
15799       FunctionType *FTy = Func->getFunctionType();
15800       const AttributeSet &Attrs = Func->getAttributes();
15801
15802       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15803         unsigned InRegCount = 0;
15804         unsigned Idx = 1;
15805
15806         for (FunctionType::param_iterator I = FTy->param_begin(),
15807              E = FTy->param_end(); I != E; ++I, ++Idx)
15808           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15809             // FIXME: should only count parameters that are lowered to integers.
15810             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15811
15812         if (InRegCount > 2) {
15813           report_fatal_error("Nest register in use - reduce number of inreg"
15814                              " parameters!");
15815         }
15816       }
15817       break;
15818     }
15819     case CallingConv::X86_FastCall:
15820     case CallingConv::X86_ThisCall:
15821     case CallingConv::Fast:
15822       // Pass 'nest' parameter in EAX.
15823       // Must be kept in sync with X86CallingConv.td
15824       NestReg = X86::EAX;
15825       break;
15826     }
15827
15828     SDValue OutChains[4];
15829     SDValue Addr, Disp;
15830
15831     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15832                        DAG.getConstant(10, dl, MVT::i32));
15833     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15834
15835     // This is storing the opcode for MOV32ri.
15836     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15837     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15838     OutChains[0] = DAG.getStore(Root, dl,
15839                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15840                                 Trmp, MachinePointerInfo(TrmpAddr),
15841                                 false, false, 0);
15842
15843     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15844                        DAG.getConstant(1, dl, MVT::i32));
15845     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15846                                 MachinePointerInfo(TrmpAddr, 1),
15847                                 false, false, 1);
15848
15849     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15850     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15851                        DAG.getConstant(5, dl, MVT::i32));
15852     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15853                                 Addr, MachinePointerInfo(TrmpAddr, 5),
15854                                 false, false, 1);
15855
15856     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15857                        DAG.getConstant(6, dl, MVT::i32));
15858     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15859                                 MachinePointerInfo(TrmpAddr, 6),
15860                                 false, false, 1);
15861
15862     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15863   }
15864 }
15865
15866 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15867                                             SelectionDAG &DAG) const {
15868   /*
15869    The rounding mode is in bits 11:10 of FPSR, and has the following
15870    settings:
15871      00 Round to nearest
15872      01 Round to -inf
15873      10 Round to +inf
15874      11 Round to 0
15875
15876   FLT_ROUNDS, on the other hand, expects the following:
15877     -1 Undefined
15878      0 Round to 0
15879      1 Round to nearest
15880      2 Round to +inf
15881      3 Round to -inf
15882
15883   To perform the conversion, we do:
15884     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15885   */
15886
15887   MachineFunction &MF = DAG.getMachineFunction();
15888   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15889   unsigned StackAlignment = TFI.getStackAlignment();
15890   MVT VT = Op.getSimpleValueType();
15891   SDLoc DL(Op);
15892
15893   // Save FP Control Word to stack slot
15894   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15895   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15896
15897   MachineMemOperand *MMO =
15898    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15899                            MachineMemOperand::MOStore, 2, 2);
15900
15901   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15902   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15903                                           DAG.getVTList(MVT::Other),
15904                                           Ops, MVT::i16, MMO);
15905
15906   // Load FP Control Word from stack slot
15907   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15908                             MachinePointerInfo(), false, false, false, 0);
15909
15910   // Transform as necessary
15911   SDValue CWD1 =
15912     DAG.getNode(ISD::SRL, DL, MVT::i16,
15913                 DAG.getNode(ISD::AND, DL, MVT::i16,
15914                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
15915                 DAG.getConstant(11, DL, MVT::i8));
15916   SDValue CWD2 =
15917     DAG.getNode(ISD::SRL, DL, MVT::i16,
15918                 DAG.getNode(ISD::AND, DL, MVT::i16,
15919                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
15920                 DAG.getConstant(9, DL, MVT::i8));
15921
15922   SDValue RetVal =
15923     DAG.getNode(ISD::AND, DL, MVT::i16,
15924                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15925                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15926                             DAG.getConstant(1, DL, MVT::i16)),
15927                 DAG.getConstant(3, DL, MVT::i16));
15928
15929   return DAG.getNode((VT.getSizeInBits() < 16 ?
15930                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15931 }
15932
15933 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15934   MVT VT = Op.getSimpleValueType();
15935   EVT OpVT = VT;
15936   unsigned NumBits = VT.getSizeInBits();
15937   SDLoc dl(Op);
15938
15939   Op = Op.getOperand(0);
15940   if (VT == MVT::i8) {
15941     // Zero extend to i32 since there is not an i8 bsr.
15942     OpVT = MVT::i32;
15943     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15944   }
15945
15946   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15947   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15948   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15949
15950   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15951   SDValue Ops[] = {
15952     Op,
15953     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
15954     DAG.getConstant(X86::COND_E, dl, MVT::i8),
15955     Op.getValue(1)
15956   };
15957   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15958
15959   // Finally xor with NumBits-1.
15960   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15961                    DAG.getConstant(NumBits - 1, dl, OpVT));
15962
15963   if (VT == MVT::i8)
15964     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15965   return Op;
15966 }
15967
15968 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15969   MVT VT = Op.getSimpleValueType();
15970   EVT OpVT = VT;
15971   unsigned NumBits = VT.getSizeInBits();
15972   SDLoc dl(Op);
15973
15974   Op = Op.getOperand(0);
15975   if (VT == MVT::i8) {
15976     // Zero extend to i32 since there is not an i8 bsr.
15977     OpVT = MVT::i32;
15978     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15979   }
15980
15981   // Issue a bsr (scan bits in reverse).
15982   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15983   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15984
15985   // And xor with NumBits-1.
15986   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15987                    DAG.getConstant(NumBits - 1, dl, OpVT));
15988
15989   if (VT == MVT::i8)
15990     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15991   return Op;
15992 }
15993
15994 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15995   MVT VT = Op.getSimpleValueType();
15996   unsigned NumBits = VT.getSizeInBits();
15997   SDLoc dl(Op);
15998   Op = Op.getOperand(0);
15999
16000   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16001   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16002   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16003
16004   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16005   SDValue Ops[] = {
16006     Op,
16007     DAG.getConstant(NumBits, dl, VT),
16008     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16009     Op.getValue(1)
16010   };
16011   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16012 }
16013
16014 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16015 // ones, and then concatenate the result back.
16016 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16017   MVT VT = Op.getSimpleValueType();
16018
16019   assert(VT.is256BitVector() && VT.isInteger() &&
16020          "Unsupported value type for operation");
16021
16022   unsigned NumElems = VT.getVectorNumElements();
16023   SDLoc dl(Op);
16024
16025   // Extract the LHS vectors
16026   SDValue LHS = Op.getOperand(0);
16027   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16028   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16029
16030   // Extract the RHS vectors
16031   SDValue RHS = Op.getOperand(1);
16032   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16033   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16034
16035   MVT EltVT = VT.getVectorElementType();
16036   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16037
16038   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16039                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16040                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16041 }
16042
16043 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16044   assert(Op.getSimpleValueType().is256BitVector() &&
16045          Op.getSimpleValueType().isInteger() &&
16046          "Only handle AVX 256-bit vector integer operation");
16047   return Lower256IntArith(Op, DAG);
16048 }
16049
16050 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16051   assert(Op.getSimpleValueType().is256BitVector() &&
16052          Op.getSimpleValueType().isInteger() &&
16053          "Only handle AVX 256-bit vector integer operation");
16054   return Lower256IntArith(Op, DAG);
16055 }
16056
16057 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16058                         SelectionDAG &DAG) {
16059   SDLoc dl(Op);
16060   MVT VT = Op.getSimpleValueType();
16061
16062   // Decompose 256-bit ops into smaller 128-bit ops.
16063   if (VT.is256BitVector() && !Subtarget->hasInt256())
16064     return Lower256IntArith(Op, DAG);
16065
16066   SDValue A = Op.getOperand(0);
16067   SDValue B = Op.getOperand(1);
16068
16069   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16070   // pairs, multiply and truncate.
16071   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16072     if (Subtarget->hasInt256()) {
16073       if (VT == MVT::v32i8) {
16074         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16075         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16076         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16077         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16078         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16079         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16080         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16081         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16082                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16083                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16084       }
16085
16086       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16087       return DAG.getNode(
16088           ISD::TRUNCATE, dl, VT,
16089           DAG.getNode(ISD::MUL, dl, ExVT,
16090                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16091                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16092     }
16093
16094     assert(VT == MVT::v16i8 &&
16095            "Pre-AVX2 support only supports v16i8 multiplication");
16096     MVT ExVT = MVT::v8i16;
16097
16098     // Extract the lo parts and sign extend to i16
16099     SDValue ALo, BLo;
16100     if (Subtarget->hasSSE41()) {
16101       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16102       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16103     } else {
16104       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16105                               -1, 4, -1, 5, -1, 6, -1, 7};
16106       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16107       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16108       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16109       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16110       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16111       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16112     }
16113
16114     // Extract the hi parts and sign extend to i16
16115     SDValue AHi, BHi;
16116     if (Subtarget->hasSSE41()) {
16117       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16118                               -1, -1, -1, -1, -1, -1, -1, -1};
16119       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16120       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16121       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16122       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16123     } else {
16124       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16125                               -1, 12, -1, 13, -1, 14, -1, 15};
16126       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16127       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16128       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16129       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16130       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16131       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16132     }
16133
16134     // Multiply, mask the lower 8bits of the lo/hi results and pack
16135     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16136     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16137     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16138     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16139     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16140   }
16141
16142   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16143   if (VT == MVT::v4i32) {
16144     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16145            "Should not custom lower when pmuldq is available!");
16146
16147     // Extract the odd parts.
16148     static const int UnpackMask[] = { 1, -1, 3, -1 };
16149     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16150     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16151
16152     // Multiply the even parts.
16153     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16154     // Now multiply odd parts.
16155     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16156
16157     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16158     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16159
16160     // Merge the two vectors back together with a shuffle. This expands into 2
16161     // shuffles.
16162     static const int ShufMask[] = { 0, 4, 2, 6 };
16163     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16164   }
16165
16166   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16167          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16168
16169   //  Ahi = psrlqi(a, 32);
16170   //  Bhi = psrlqi(b, 32);
16171   //
16172   //  AloBlo = pmuludq(a, b);
16173   //  AloBhi = pmuludq(a, Bhi);
16174   //  AhiBlo = pmuludq(Ahi, b);
16175
16176   //  AloBhi = psllqi(AloBhi, 32);
16177   //  AhiBlo = psllqi(AhiBlo, 32);
16178   //  return AloBlo + AloBhi + AhiBlo;
16179
16180   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16181   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16182
16183   // Bit cast to 32-bit vectors for MULUDQ
16184   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16185                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16186   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16187   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16188   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16189   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16190
16191   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16192   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16193   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16194
16195   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16196   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16197
16198   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16199   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16200 }
16201
16202 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16203   assert(Subtarget->isTargetWin64() && "Unexpected target");
16204   EVT VT = Op.getValueType();
16205   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16206          "Unexpected return type for lowering");
16207
16208   RTLIB::Libcall LC;
16209   bool isSigned;
16210   switch (Op->getOpcode()) {
16211   default: llvm_unreachable("Unexpected request for libcall!");
16212   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16213   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16214   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16215   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16216   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16217   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16218   }
16219
16220   SDLoc dl(Op);
16221   SDValue InChain = DAG.getEntryNode();
16222
16223   TargetLowering::ArgListTy Args;
16224   TargetLowering::ArgListEntry Entry;
16225   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16226     EVT ArgVT = Op->getOperand(i).getValueType();
16227     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16228            "Unexpected argument type for lowering");
16229     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16230     Entry.Node = StackPtr;
16231     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16232                            false, false, 16);
16233     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16234     Entry.Ty = PointerType::get(ArgTy,0);
16235     Entry.isSExt = false;
16236     Entry.isZExt = false;
16237     Args.push_back(Entry);
16238   }
16239
16240   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16241                                          getPointerTy());
16242
16243   TargetLowering::CallLoweringInfo CLI(DAG);
16244   CLI.setDebugLoc(dl).setChain(InChain)
16245     .setCallee(getLibcallCallingConv(LC),
16246                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16247                Callee, std::move(Args), 0)
16248     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16249
16250   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16251   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16252 }
16253
16254 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16255                              SelectionDAG &DAG) {
16256   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16257   EVT VT = Op0.getValueType();
16258   SDLoc dl(Op);
16259
16260   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16261          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16262
16263   // PMULxD operations multiply each even value (starting at 0) of LHS with
16264   // the related value of RHS and produce a widen result.
16265   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16266   // => <2 x i64> <ae|cg>
16267   //
16268   // In other word, to have all the results, we need to perform two PMULxD:
16269   // 1. one with the even values.
16270   // 2. one with the odd values.
16271   // To achieve #2, with need to place the odd values at an even position.
16272   //
16273   // Place the odd value at an even position (basically, shift all values 1
16274   // step to the left):
16275   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16276   // <a|b|c|d> => <b|undef|d|undef>
16277   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16278   // <e|f|g|h> => <f|undef|h|undef>
16279   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16280
16281   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16282   // ints.
16283   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16284   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16285   unsigned Opcode =
16286       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16287   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16288   // => <2 x i64> <ae|cg>
16289   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16290                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16291   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16292   // => <2 x i64> <bf|dh>
16293   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16294                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16295
16296   // Shuffle it back into the right order.
16297   SDValue Highs, Lows;
16298   if (VT == MVT::v8i32) {
16299     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16300     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16301     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16302     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16303   } else {
16304     const int HighMask[] = {1, 5, 3, 7};
16305     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16306     const int LowMask[] = {0, 4, 2, 6};
16307     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16308   }
16309
16310   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16311   // unsigned multiply.
16312   if (IsSigned && !Subtarget->hasSSE41()) {
16313     SDValue ShAmt =
16314         DAG.getConstant(31, dl,
16315                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16316     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16317                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16318     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16319                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16320
16321     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16322     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16323   }
16324
16325   // The first result of MUL_LOHI is actually the low value, followed by the
16326   // high value.
16327   SDValue Ops[] = {Lows, Highs};
16328   return DAG.getMergeValues(Ops, dl);
16329 }
16330
16331 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16332                                          const X86Subtarget *Subtarget) {
16333   MVT VT = Op.getSimpleValueType();
16334   SDLoc dl(Op);
16335   SDValue R = Op.getOperand(0);
16336   SDValue Amt = Op.getOperand(1);
16337
16338   // Optimize shl/srl/sra with constant shift amount.
16339   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16340     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16341       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16342
16343       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16344           (Subtarget->hasInt256() &&
16345            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16346           (Subtarget->hasAVX512() &&
16347            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16348         if (Op.getOpcode() == ISD::SHL)
16349           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16350                                             DAG);
16351         if (Op.getOpcode() == ISD::SRL)
16352           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16353                                             DAG);
16354         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16355           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16356                                             DAG);
16357       }
16358
16359       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16360         unsigned NumElts = VT.getVectorNumElements();
16361         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16362
16363         if (Op.getOpcode() == ISD::SHL) {
16364           // Make a large shift.
16365           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16366                                                    R, ShiftAmt, DAG);
16367           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16368           // Zero out the rightmost bits.
16369           SmallVector<SDValue, 32> V(
16370               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16371           return DAG.getNode(ISD::AND, dl, VT, SHL,
16372                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16373         }
16374         if (Op.getOpcode() == ISD::SRL) {
16375           // Make a large shift.
16376           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16377                                                    R, ShiftAmt, DAG);
16378           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16379           // Zero out the leftmost bits.
16380           SmallVector<SDValue, 32> V(
16381               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16382           return DAG.getNode(ISD::AND, dl, VT, SRL,
16383                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16384         }
16385         if (Op.getOpcode() == ISD::SRA) {
16386           if (ShiftAmt == 7) {
16387             // R s>> 7  ===  R s< 0
16388             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16389             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16390           }
16391
16392           // R s>> a === ((R u>> a) ^ m) - m
16393           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16394           SmallVector<SDValue, 32> V(NumElts,
16395                                      DAG.getConstant(128 >> ShiftAmt, dl,
16396                                                      MVT::i8));
16397           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16398           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16399           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16400           return Res;
16401         }
16402         llvm_unreachable("Unknown shift opcode.");
16403       }
16404     }
16405   }
16406
16407   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16408   if (!Subtarget->is64Bit() &&
16409       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16410       Amt.getOpcode() == ISD::BITCAST &&
16411       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16412     Amt = Amt.getOperand(0);
16413     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16414                      VT.getVectorNumElements();
16415     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16416     uint64_t ShiftAmt = 0;
16417     for (unsigned i = 0; i != Ratio; ++i) {
16418       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16419       if (!C)
16420         return SDValue();
16421       // 6 == Log2(64)
16422       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16423     }
16424     // Check remaining shift amounts.
16425     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16426       uint64_t ShAmt = 0;
16427       for (unsigned j = 0; j != Ratio; ++j) {
16428         ConstantSDNode *C =
16429           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16430         if (!C)
16431           return SDValue();
16432         // 6 == Log2(64)
16433         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16434       }
16435       if (ShAmt != ShiftAmt)
16436         return SDValue();
16437     }
16438     switch (Op.getOpcode()) {
16439     default:
16440       llvm_unreachable("Unknown shift opcode!");
16441     case ISD::SHL:
16442       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16443                                         DAG);
16444     case ISD::SRL:
16445       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16446                                         DAG);
16447     case ISD::SRA:
16448       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16449                                         DAG);
16450     }
16451   }
16452
16453   return SDValue();
16454 }
16455
16456 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16457                                         const X86Subtarget* Subtarget) {
16458   MVT VT = Op.getSimpleValueType();
16459   SDLoc dl(Op);
16460   SDValue R = Op.getOperand(0);
16461   SDValue Amt = Op.getOperand(1);
16462
16463   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16464       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16465       (Subtarget->hasInt256() &&
16466        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16467         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16468        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16469     SDValue BaseShAmt;
16470     EVT EltVT = VT.getVectorElementType();
16471
16472     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16473       // Check if this build_vector node is doing a splat.
16474       // If so, then set BaseShAmt equal to the splat value.
16475       BaseShAmt = BV->getSplatValue();
16476       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16477         BaseShAmt = SDValue();
16478     } else {
16479       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16480         Amt = Amt.getOperand(0);
16481
16482       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16483       if (SVN && SVN->isSplat()) {
16484         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16485         SDValue InVec = Amt.getOperand(0);
16486         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16487           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16488                  "Unexpected shuffle index found!");
16489           BaseShAmt = InVec.getOperand(SplatIdx);
16490         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16491            if (ConstantSDNode *C =
16492                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16493              if (C->getZExtValue() == SplatIdx)
16494                BaseShAmt = InVec.getOperand(1);
16495            }
16496         }
16497
16498         if (!BaseShAmt)
16499           // Avoid introducing an extract element from a shuffle.
16500           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16501                                   DAG.getIntPtrConstant(SplatIdx, dl));
16502       }
16503     }
16504
16505     if (BaseShAmt.getNode()) {
16506       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16507       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16508         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16509       else if (EltVT.bitsLT(MVT::i32))
16510         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16511
16512       switch (Op.getOpcode()) {
16513       default:
16514         llvm_unreachable("Unknown shift opcode!");
16515       case ISD::SHL:
16516         switch (VT.SimpleTy) {
16517         default: return SDValue();
16518         case MVT::v2i64:
16519         case MVT::v4i32:
16520         case MVT::v8i16:
16521         case MVT::v4i64:
16522         case MVT::v8i32:
16523         case MVT::v16i16:
16524         case MVT::v16i32:
16525         case MVT::v8i64:
16526           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16527         }
16528       case ISD::SRA:
16529         switch (VT.SimpleTy) {
16530         default: return SDValue();
16531         case MVT::v4i32:
16532         case MVT::v8i16:
16533         case MVT::v8i32:
16534         case MVT::v16i16:
16535         case MVT::v16i32:
16536         case MVT::v8i64:
16537           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16538         }
16539       case ISD::SRL:
16540         switch (VT.SimpleTy) {
16541         default: return SDValue();
16542         case MVT::v2i64:
16543         case MVT::v4i32:
16544         case MVT::v8i16:
16545         case MVT::v4i64:
16546         case MVT::v8i32:
16547         case MVT::v16i16:
16548         case MVT::v16i32:
16549         case MVT::v8i64:
16550           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16551         }
16552       }
16553     }
16554   }
16555
16556   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16557   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16558       Amt.getOpcode() == ISD::BITCAST &&
16559       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16560     Amt = Amt.getOperand(0);
16561     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16562                      VT.getVectorNumElements();
16563     std::vector<SDValue> Vals(Ratio);
16564     for (unsigned i = 0; i != Ratio; ++i)
16565       Vals[i] = Amt.getOperand(i);
16566     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16567       for (unsigned j = 0; j != Ratio; ++j)
16568         if (Vals[j] != Amt.getOperand(i + j))
16569           return SDValue();
16570     }
16571     switch (Op.getOpcode()) {
16572     default:
16573       llvm_unreachable("Unknown shift opcode!");
16574     case ISD::SHL:
16575       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16576     case ISD::SRL:
16577       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16578     case ISD::SRA:
16579       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16580     }
16581   }
16582
16583   return SDValue();
16584 }
16585
16586 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16587                           SelectionDAG &DAG) {
16588   MVT VT = Op.getSimpleValueType();
16589   SDLoc dl(Op);
16590   SDValue R = Op.getOperand(0);
16591   SDValue Amt = Op.getOperand(1);
16592
16593   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16594   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16595
16596   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16597     return V;
16598
16599   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16600       return V;
16601
16602   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16603     return Op;
16604
16605   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16606   if (Subtarget->hasInt256()) {
16607     if (Op.getOpcode() == ISD::SRL &&
16608         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16609          VT == MVT::v4i64 || VT == MVT::v8i32))
16610       return Op;
16611     if (Op.getOpcode() == ISD::SHL &&
16612         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16613          VT == MVT::v4i64 || VT == MVT::v8i32))
16614       return Op;
16615     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16616       return Op;
16617   }
16618
16619   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16620   // shifts per-lane and then shuffle the partial results back together.
16621   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16622     // Splat the shift amounts so the scalar shifts above will catch it.
16623     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16624     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16625     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16626     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16627     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16628   }
16629
16630   // If possible, lower this packed shift into a vector multiply instead of
16631   // expanding it into a sequence of scalar shifts.
16632   // Do this only if the vector shift count is a constant build_vector.
16633   if (Op.getOpcode() == ISD::SHL &&
16634       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16635        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16636       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16637     SmallVector<SDValue, 8> Elts;
16638     EVT SVT = VT.getScalarType();
16639     unsigned SVTBits = SVT.getSizeInBits();
16640     const APInt &One = APInt(SVTBits, 1);
16641     unsigned NumElems = VT.getVectorNumElements();
16642
16643     for (unsigned i=0; i !=NumElems; ++i) {
16644       SDValue Op = Amt->getOperand(i);
16645       if (Op->getOpcode() == ISD::UNDEF) {
16646         Elts.push_back(Op);
16647         continue;
16648       }
16649
16650       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16651       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16652       uint64_t ShAmt = C.getZExtValue();
16653       if (ShAmt >= SVTBits) {
16654         Elts.push_back(DAG.getUNDEF(SVT));
16655         continue;
16656       }
16657       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16658     }
16659     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16660     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16661   }
16662
16663   // Lower SHL with variable shift amount.
16664   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16665     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16666
16667     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16668                      DAG.getConstant(0x3f800000U, dl, VT));
16669     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16670     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16671     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16672   }
16673
16674   // If possible, lower this shift as a sequence of two shifts by
16675   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16676   // Example:
16677   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16678   //
16679   // Could be rewritten as:
16680   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16681   //
16682   // The advantage is that the two shifts from the example would be
16683   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16684   // the vector shift into four scalar shifts plus four pairs of vector
16685   // insert/extract.
16686   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16687       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16688     unsigned TargetOpcode = X86ISD::MOVSS;
16689     bool CanBeSimplified;
16690     // The splat value for the first packed shift (the 'X' from the example).
16691     SDValue Amt1 = Amt->getOperand(0);
16692     // The splat value for the second packed shift (the 'Y' from the example).
16693     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16694                                         Amt->getOperand(2);
16695
16696     // See if it is possible to replace this node with a sequence of
16697     // two shifts followed by a MOVSS/MOVSD
16698     if (VT == MVT::v4i32) {
16699       // Check if it is legal to use a MOVSS.
16700       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16701                         Amt2 == Amt->getOperand(3);
16702       if (!CanBeSimplified) {
16703         // Otherwise, check if we can still simplify this node using a MOVSD.
16704         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16705                           Amt->getOperand(2) == Amt->getOperand(3);
16706         TargetOpcode = X86ISD::MOVSD;
16707         Amt2 = Amt->getOperand(2);
16708       }
16709     } else {
16710       // Do similar checks for the case where the machine value type
16711       // is MVT::v8i16.
16712       CanBeSimplified = Amt1 == Amt->getOperand(1);
16713       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16714         CanBeSimplified = Amt2 == Amt->getOperand(i);
16715
16716       if (!CanBeSimplified) {
16717         TargetOpcode = X86ISD::MOVSD;
16718         CanBeSimplified = true;
16719         Amt2 = Amt->getOperand(4);
16720         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16721           CanBeSimplified = Amt1 == Amt->getOperand(i);
16722         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16723           CanBeSimplified = Amt2 == Amt->getOperand(j);
16724       }
16725     }
16726
16727     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16728         isa<ConstantSDNode>(Amt2)) {
16729       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16730       EVT CastVT = MVT::v4i32;
16731       SDValue Splat1 =
16732         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16733       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16734       SDValue Splat2 =
16735         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16736       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16737       if (TargetOpcode == X86ISD::MOVSD)
16738         CastVT = MVT::v2i64;
16739       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16740       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16741       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16742                                             BitCast1, DAG);
16743       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16744     }
16745   }
16746
16747   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16748     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16749     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16750
16751     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16752     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16753     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16754
16755     // r = VSELECT(r, shl(r, 4), a);
16756     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16757     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16758
16759     // a += a
16760     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16761     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16762     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16763
16764     // r = VSELECT(r, shl(r, 2), a);
16765     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16766     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16767
16768     // a += a
16769     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16770     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16771     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16772
16773     // return VSELECT(r, r+r, a);
16774     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16775                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16776     return R;
16777   }
16778
16779   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16780   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16781   // solution better.
16782   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16783     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16784     unsigned ExtOpc =
16785         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16786     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16787     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16788     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16789                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16790   }
16791
16792   // Decompose 256-bit shifts into smaller 128-bit shifts.
16793   if (VT.is256BitVector()) {
16794     unsigned NumElems = VT.getVectorNumElements();
16795     MVT EltVT = VT.getVectorElementType();
16796     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16797
16798     // Extract the two vectors
16799     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16800     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16801
16802     // Recreate the shift amount vectors
16803     SDValue Amt1, Amt2;
16804     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16805       // Constant shift amount
16806       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16807       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16808       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16809
16810       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16811       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16812     } else {
16813       // Variable shift amount
16814       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16815       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16816     }
16817
16818     // Issue new vector shifts for the smaller types
16819     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16820     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16821
16822     // Concatenate the result back
16823     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16824   }
16825
16826   return SDValue();
16827 }
16828
16829 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16830   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16831   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16832   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16833   // has only one use.
16834   SDNode *N = Op.getNode();
16835   SDValue LHS = N->getOperand(0);
16836   SDValue RHS = N->getOperand(1);
16837   unsigned BaseOp = 0;
16838   unsigned Cond = 0;
16839   SDLoc DL(Op);
16840   switch (Op.getOpcode()) {
16841   default: llvm_unreachable("Unknown ovf instruction!");
16842   case ISD::SADDO:
16843     // A subtract of one will be selected as a INC. Note that INC doesn't
16844     // set CF, so we can't do this for UADDO.
16845     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16846       if (C->isOne()) {
16847         BaseOp = X86ISD::INC;
16848         Cond = X86::COND_O;
16849         break;
16850       }
16851     BaseOp = X86ISD::ADD;
16852     Cond = X86::COND_O;
16853     break;
16854   case ISD::UADDO:
16855     BaseOp = X86ISD::ADD;
16856     Cond = X86::COND_B;
16857     break;
16858   case ISD::SSUBO:
16859     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16860     // set CF, so we can't do this for USUBO.
16861     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16862       if (C->isOne()) {
16863         BaseOp = X86ISD::DEC;
16864         Cond = X86::COND_O;
16865         break;
16866       }
16867     BaseOp = X86ISD::SUB;
16868     Cond = X86::COND_O;
16869     break;
16870   case ISD::USUBO:
16871     BaseOp = X86ISD::SUB;
16872     Cond = X86::COND_B;
16873     break;
16874   case ISD::SMULO:
16875     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16876     Cond = X86::COND_O;
16877     break;
16878   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16879     if (N->getValueType(0) == MVT::i8) {
16880       BaseOp = X86ISD::UMUL8;
16881       Cond = X86::COND_O;
16882       break;
16883     }
16884     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16885                                  MVT::i32);
16886     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16887
16888     SDValue SetCC =
16889       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16890                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
16891                   SDValue(Sum.getNode(), 2));
16892
16893     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16894   }
16895   }
16896
16897   // Also sets EFLAGS.
16898   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16899   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16900
16901   SDValue SetCC =
16902     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16903                 DAG.getConstant(Cond, DL, MVT::i32),
16904                 SDValue(Sum.getNode(), 1));
16905
16906   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16907 }
16908
16909 /// Returns true if the operand type is exactly twice the native width, and
16910 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16911 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16912 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16913 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16914   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16915
16916   if (OpWidth == 64)
16917     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16918   else if (OpWidth == 128)
16919     return Subtarget->hasCmpxchg16b();
16920   else
16921     return false;
16922 }
16923
16924 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16925   return needsCmpXchgNb(SI->getValueOperand()->getType());
16926 }
16927
16928 // Note: this turns large loads into lock cmpxchg8b/16b.
16929 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16930 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16931   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16932   return needsCmpXchgNb(PTy->getElementType());
16933 }
16934
16935 TargetLoweringBase::AtomicRMWExpansionKind
16936 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16937   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16938   const Type *MemType = AI->getType();
16939
16940   // If the operand is too big, we must see if cmpxchg8/16b is available
16941   // and default to library calls otherwise.
16942   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16943     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16944                                    : AtomicRMWExpansionKind::None;
16945   }
16946
16947   AtomicRMWInst::BinOp Op = AI->getOperation();
16948   switch (Op) {
16949   default:
16950     llvm_unreachable("Unknown atomic operation");
16951   case AtomicRMWInst::Xchg:
16952   case AtomicRMWInst::Add:
16953   case AtomicRMWInst::Sub:
16954     // It's better to use xadd, xsub or xchg for these in all cases.
16955     return AtomicRMWExpansionKind::None;
16956   case AtomicRMWInst::Or:
16957   case AtomicRMWInst::And:
16958   case AtomicRMWInst::Xor:
16959     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16960     // prefix to a normal instruction for these operations.
16961     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16962                             : AtomicRMWExpansionKind::None;
16963   case AtomicRMWInst::Nand:
16964   case AtomicRMWInst::Max:
16965   case AtomicRMWInst::Min:
16966   case AtomicRMWInst::UMax:
16967   case AtomicRMWInst::UMin:
16968     // These always require a non-trivial set of data operations on x86. We must
16969     // use a cmpxchg loop.
16970     return AtomicRMWExpansionKind::CmpXChg;
16971   }
16972 }
16973
16974 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16975   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16976   // no-sse2). There isn't any reason to disable it if the target processor
16977   // supports it.
16978   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16979 }
16980
16981 LoadInst *
16982 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16983   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16984   const Type *MemType = AI->getType();
16985   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16986   // there is no benefit in turning such RMWs into loads, and it is actually
16987   // harmful as it introduces a mfence.
16988   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16989     return nullptr;
16990
16991   auto Builder = IRBuilder<>(AI);
16992   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16993   auto SynchScope = AI->getSynchScope();
16994   // We must restrict the ordering to avoid generating loads with Release or
16995   // ReleaseAcquire orderings.
16996   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16997   auto Ptr = AI->getPointerOperand();
16998
16999   // Before the load we need a fence. Here is an example lifted from
17000   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17001   // is required:
17002   // Thread 0:
17003   //   x.store(1, relaxed);
17004   //   r1 = y.fetch_add(0, release);
17005   // Thread 1:
17006   //   y.fetch_add(42, acquire);
17007   //   r2 = x.load(relaxed);
17008   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17009   // lowered to just a load without a fence. A mfence flushes the store buffer,
17010   // making the optimization clearly correct.
17011   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17012   // otherwise, we might be able to be more agressive on relaxed idempotent
17013   // rmw. In practice, they do not look useful, so we don't try to be
17014   // especially clever.
17015   if (SynchScope == SingleThread) {
17016     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17017     // the IR level, so we must wrap it in an intrinsic.
17018     return nullptr;
17019   } else if (hasMFENCE(*Subtarget)) {
17020     Function *MFence = llvm::Intrinsic::getDeclaration(M,
17021             Intrinsic::x86_sse2_mfence);
17022     Builder.CreateCall(MFence);
17023   } else {
17024     // FIXME: it might make sense to use a locked operation here but on a
17025     // different cache-line to prevent cache-line bouncing. In practice it
17026     // is probably a small win, and x86 processors without mfence are rare
17027     // enough that we do not bother.
17028     return nullptr;
17029   }
17030
17031   // Finally we can emit the atomic load.
17032   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17033           AI->getType()->getPrimitiveSizeInBits());
17034   Loaded->setAtomic(Order, SynchScope);
17035   AI->replaceAllUsesWith(Loaded);
17036   AI->eraseFromParent();
17037   return Loaded;
17038 }
17039
17040 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17041                                  SelectionDAG &DAG) {
17042   SDLoc dl(Op);
17043   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17044     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17045   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17046     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17047
17048   // The only fence that needs an instruction is a sequentially-consistent
17049   // cross-thread fence.
17050   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17051     if (hasMFENCE(*Subtarget))
17052       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17053
17054     SDValue Chain = Op.getOperand(0);
17055     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17056     SDValue Ops[] = {
17057       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17058       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17059       DAG.getRegister(0, MVT::i32),            // Index
17060       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17061       DAG.getRegister(0, MVT::i32),            // Segment.
17062       Zero,
17063       Chain
17064     };
17065     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17066     return SDValue(Res, 0);
17067   }
17068
17069   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17070   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17071 }
17072
17073 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17074                              SelectionDAG &DAG) {
17075   MVT T = Op.getSimpleValueType();
17076   SDLoc DL(Op);
17077   unsigned Reg = 0;
17078   unsigned size = 0;
17079   switch(T.SimpleTy) {
17080   default: llvm_unreachable("Invalid value type!");
17081   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17082   case MVT::i16: Reg = X86::AX;  size = 2; break;
17083   case MVT::i32: Reg = X86::EAX; size = 4; break;
17084   case MVT::i64:
17085     assert(Subtarget->is64Bit() && "Node not type legal!");
17086     Reg = X86::RAX; size = 8;
17087     break;
17088   }
17089   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17090                                   Op.getOperand(2), SDValue());
17091   SDValue Ops[] = { cpIn.getValue(0),
17092                     Op.getOperand(1),
17093                     Op.getOperand(3),
17094                     DAG.getTargetConstant(size, DL, MVT::i8),
17095                     cpIn.getValue(1) };
17096   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17097   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17098   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17099                                            Ops, T, MMO);
17100
17101   SDValue cpOut =
17102     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17103   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17104                                       MVT::i32, cpOut.getValue(2));
17105   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17106                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17107                                 EFLAGS);
17108
17109   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17110   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17111   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17112   return SDValue();
17113 }
17114
17115 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17116                             SelectionDAG &DAG) {
17117   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17118   MVT DstVT = Op.getSimpleValueType();
17119
17120   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17121     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17122     if (DstVT != MVT::f64)
17123       // This conversion needs to be expanded.
17124       return SDValue();
17125
17126     SDValue InVec = Op->getOperand(0);
17127     SDLoc dl(Op);
17128     unsigned NumElts = SrcVT.getVectorNumElements();
17129     EVT SVT = SrcVT.getVectorElementType();
17130
17131     // Widen the vector in input in the case of MVT::v2i32.
17132     // Example: from MVT::v2i32 to MVT::v4i32.
17133     SmallVector<SDValue, 16> Elts;
17134     for (unsigned i = 0, e = NumElts; i != e; ++i)
17135       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17136                                  DAG.getIntPtrConstant(i, dl)));
17137
17138     // Explicitly mark the extra elements as Undef.
17139     Elts.append(NumElts, DAG.getUNDEF(SVT));
17140
17141     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17142     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17143     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17144     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17145                        DAG.getIntPtrConstant(0, dl));
17146   }
17147
17148   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17149          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17150   assert((DstVT == MVT::i64 ||
17151           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17152          "Unexpected custom BITCAST");
17153   // i64 <=> MMX conversions are Legal.
17154   if (SrcVT==MVT::i64 && DstVT.isVector())
17155     return Op;
17156   if (DstVT==MVT::i64 && SrcVT.isVector())
17157     return Op;
17158   // MMX <=> MMX conversions are Legal.
17159   if (SrcVT.isVector() && DstVT.isVector())
17160     return Op;
17161   // All other conversions need to be expanded.
17162   return SDValue();
17163 }
17164
17165 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17166                           SelectionDAG &DAG) {
17167   SDNode *Node = Op.getNode();
17168   SDLoc dl(Node);
17169
17170   Op = Op.getOperand(0);
17171   EVT VT = Op.getValueType();
17172   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17173          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17174
17175   unsigned NumElts = VT.getVectorNumElements();
17176   EVT EltVT = VT.getVectorElementType();
17177   unsigned Len = EltVT.getSizeInBits();
17178
17179   // This is the vectorized version of the "best" algorithm from
17180   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17181   // with a minor tweak to use a series of adds + shifts instead of vector
17182   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17183   //
17184   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17185   //  v8i32 => Always profitable
17186   //
17187   // FIXME: There a couple of possible improvements:
17188   //
17189   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17190   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17191   //
17192   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17193          "CTPOP not implemented for this vector element type.");
17194
17195   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17196   // extra legalization.
17197   bool NeedsBitcast = EltVT == MVT::i32;
17198   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17199
17200   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17201                                   EltVT);
17202   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17203                                   EltVT);
17204   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17205                                   EltVT);
17206
17207   // v = v - ((v >> 1) & 0x55555555...)
17208   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17209   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17210   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17211   if (NeedsBitcast)
17212     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17213
17214   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17215   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17216   if (NeedsBitcast)
17217     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17218
17219   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17220   if (VT != And.getValueType())
17221     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17222   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17223
17224   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17225   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17226   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17227   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17228   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17229
17230   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17231   if (NeedsBitcast) {
17232     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17233     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17234     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17235   }
17236
17237   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17238   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17239   if (VT != AndRHS.getValueType()) {
17240     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17241     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17242   }
17243   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17244
17245   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17246   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17247   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17248   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17249   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17250
17251   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17252   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17253   if (NeedsBitcast) {
17254     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17255     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17256   }
17257   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17258   if (VT != And.getValueType())
17259     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17260
17261   // The algorithm mentioned above uses:
17262   //    v = (v * 0x01010101...) >> (Len - 8)
17263   //
17264   // Change it to use vector adds + vector shifts which yield faster results on
17265   // Haswell than using vector integer multiplication.
17266   //
17267   // For i32 elements:
17268   //    v = v + (v >> 8)
17269   //    v = v + (v >> 16)
17270   //
17271   // For i64 elements:
17272   //    v = v + (v >> 8)
17273   //    v = v + (v >> 16)
17274   //    v = v + (v >> 32)
17275   //
17276   Add = And;
17277   SmallVector<SDValue, 8> Csts;
17278   for (unsigned i = 8; i <= Len/2; i *= 2) {
17279     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17280     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17281     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17282     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17283     Csts.clear();
17284   }
17285
17286   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17287   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17288                                   EltVT);
17289   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17290   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17291   if (NeedsBitcast) {
17292     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17293     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17294   }
17295   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17296   if (VT != And.getValueType())
17297     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17298
17299   return And;
17300 }
17301
17302 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17303   SDNode *Node = Op.getNode();
17304   SDLoc dl(Node);
17305   EVT T = Node->getValueType(0);
17306   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17307                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17308   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17309                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17310                        Node->getOperand(0),
17311                        Node->getOperand(1), negOp,
17312                        cast<AtomicSDNode>(Node)->getMemOperand(),
17313                        cast<AtomicSDNode>(Node)->getOrdering(),
17314                        cast<AtomicSDNode>(Node)->getSynchScope());
17315 }
17316
17317 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17318   SDNode *Node = Op.getNode();
17319   SDLoc dl(Node);
17320   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17321
17322   // Convert seq_cst store -> xchg
17323   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17324   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17325   //        (The only way to get a 16-byte store is cmpxchg16b)
17326   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17327   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17328       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17329     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17330                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17331                                  Node->getOperand(0),
17332                                  Node->getOperand(1), Node->getOperand(2),
17333                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17334                                  cast<AtomicSDNode>(Node)->getOrdering(),
17335                                  cast<AtomicSDNode>(Node)->getSynchScope());
17336     return Swap.getValue(1);
17337   }
17338   // Other atomic stores have a simple pattern.
17339   return Op;
17340 }
17341
17342 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17343   EVT VT = Op.getNode()->getSimpleValueType(0);
17344
17345   // Let legalize expand this if it isn't a legal type yet.
17346   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17347     return SDValue();
17348
17349   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17350
17351   unsigned Opc;
17352   bool ExtraOp = false;
17353   switch (Op.getOpcode()) {
17354   default: llvm_unreachable("Invalid code");
17355   case ISD::ADDC: Opc = X86ISD::ADD; break;
17356   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17357   case ISD::SUBC: Opc = X86ISD::SUB; break;
17358   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17359   }
17360
17361   if (!ExtraOp)
17362     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17363                        Op.getOperand(1));
17364   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17365                      Op.getOperand(1), Op.getOperand(2));
17366 }
17367
17368 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17369                             SelectionDAG &DAG) {
17370   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17371
17372   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17373   // which returns the values as { float, float } (in XMM0) or
17374   // { double, double } (which is returned in XMM0, XMM1).
17375   SDLoc dl(Op);
17376   SDValue Arg = Op.getOperand(0);
17377   EVT ArgVT = Arg.getValueType();
17378   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17379
17380   TargetLowering::ArgListTy Args;
17381   TargetLowering::ArgListEntry Entry;
17382
17383   Entry.Node = Arg;
17384   Entry.Ty = ArgTy;
17385   Entry.isSExt = false;
17386   Entry.isZExt = false;
17387   Args.push_back(Entry);
17388
17389   bool isF64 = ArgVT == MVT::f64;
17390   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17391   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17392   // the results are returned via SRet in memory.
17393   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17395   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17396
17397   Type *RetTy = isF64
17398     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17399     : (Type*)VectorType::get(ArgTy, 4);
17400
17401   TargetLowering::CallLoweringInfo CLI(DAG);
17402   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17403     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17404
17405   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17406
17407   if (isF64)
17408     // Returned in xmm0 and xmm1.
17409     return CallResult.first;
17410
17411   // Returned in bits 0:31 and 32:64 xmm0.
17412   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17413                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17414   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17415                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17416   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17417   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17418 }
17419
17420 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17421                              SelectionDAG &DAG) {
17422   assert(Subtarget->hasAVX512() &&
17423          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17424
17425   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17426   EVT VT = N->getValue().getValueType();
17427   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17428   SDLoc dl(Op);
17429
17430   // X86 scatter kills mask register, so its type should be added to
17431   // the list of return values
17432   if (N->getNumValues() == 1) {
17433     SDValue Index = N->getIndex();
17434     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17435         !Index.getValueType().is512BitVector())
17436       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17437
17438     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17439     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17440                       N->getOperand(3), Index };
17441
17442     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17443     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17444     return SDValue(NewScatter.getNode(), 0);
17445   }
17446   return Op;
17447 }
17448
17449 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17450                             SelectionDAG &DAG) {
17451   assert(Subtarget->hasAVX512() &&
17452          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17453
17454   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17455   EVT VT = Op.getValueType();
17456   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17457   SDLoc dl(Op);
17458
17459   SDValue Index = N->getIndex();
17460   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17461       !Index.getValueType().is512BitVector()) {
17462     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17463     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17464                       N->getOperand(3), Index };
17465     DAG.UpdateNodeOperands(N, Ops);
17466   }
17467   return Op;
17468 }
17469
17470 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17471                                                     SelectionDAG &DAG) const {
17472   // TODO: Eventually, the lowering of these nodes should be informed by or
17473   // deferred to the GC strategy for the function in which they appear. For
17474   // now, however, they must be lowered to something. Since they are logically
17475   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17476   // require special handling for these nodes), lower them as literal NOOPs for
17477   // the time being.
17478   SmallVector<SDValue, 2> Ops;
17479
17480   Ops.push_back(Op.getOperand(0));
17481   if (Op->getGluedNode())
17482     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17483
17484   SDLoc OpDL(Op);
17485   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17486   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17487
17488   return NOOP;
17489 }
17490
17491 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17492                                                   SelectionDAG &DAG) const {
17493   // TODO: Eventually, the lowering of these nodes should be informed by or
17494   // deferred to the GC strategy for the function in which they appear. For
17495   // now, however, they must be lowered to something. Since they are logically
17496   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17497   // require special handling for these nodes), lower them as literal NOOPs for
17498   // the time being.
17499   SmallVector<SDValue, 2> Ops;
17500
17501   Ops.push_back(Op.getOperand(0));
17502   if (Op->getGluedNode())
17503     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17504
17505   SDLoc OpDL(Op);
17506   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17507   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17508
17509   return NOOP;
17510 }
17511
17512 /// LowerOperation - Provide custom lowering hooks for some operations.
17513 ///
17514 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17515   switch (Op.getOpcode()) {
17516   default: llvm_unreachable("Should not custom lower this!");
17517   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17518   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17519     return LowerCMP_SWAP(Op, Subtarget, DAG);
17520   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17521   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17522   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17523   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17524   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17525   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17526   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17527   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17528   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17529   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17530   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17531   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17532   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17533   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17534   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17535   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17536   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17537   case ISD::SHL_PARTS:
17538   case ISD::SRA_PARTS:
17539   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17540   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17541   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17542   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17543   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17544   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17545   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17546   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17547   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17548   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17549   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17550   case ISD::FABS:
17551   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17552   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17553   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17554   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17555   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17556   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17557   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17558   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17559   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17560   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17561   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17562   case ISD::INTRINSIC_VOID:
17563   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17564   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17565   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17566   case ISD::FRAME_TO_ARGS_OFFSET:
17567                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17568   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17569   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17570   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17571   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17572   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17573   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17574   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17575   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17576   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17577   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17578   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17579   case ISD::UMUL_LOHI:
17580   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17581   case ISD::SRA:
17582   case ISD::SRL:
17583   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17584   case ISD::SADDO:
17585   case ISD::UADDO:
17586   case ISD::SSUBO:
17587   case ISD::USUBO:
17588   case ISD::SMULO:
17589   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17590   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17591   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17592   case ISD::ADDC:
17593   case ISD::ADDE:
17594   case ISD::SUBC:
17595   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17596   case ISD::ADD:                return LowerADD(Op, DAG);
17597   case ISD::SUB:                return LowerSUB(Op, DAG);
17598   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17599   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17600   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17601   case ISD::GC_TRANSITION_START:
17602                                 return LowerGC_TRANSITION_START(Op, DAG);
17603   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17604   }
17605 }
17606
17607 /// ReplaceNodeResults - Replace a node with an illegal result type
17608 /// with a new node built out of custom code.
17609 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17610                                            SmallVectorImpl<SDValue>&Results,
17611                                            SelectionDAG &DAG) const {
17612   SDLoc dl(N);
17613   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17614   switch (N->getOpcode()) {
17615   default:
17616     llvm_unreachable("Do not know how to custom type legalize this operation!");
17617   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17618   case X86ISD::FMINC:
17619   case X86ISD::FMIN:
17620   case X86ISD::FMAXC:
17621   case X86ISD::FMAX: {
17622     EVT VT = N->getValueType(0);
17623     if (VT != MVT::v2f32)
17624       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17625     SDValue UNDEF = DAG.getUNDEF(VT);
17626     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17627                               N->getOperand(0), UNDEF);
17628     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17629                               N->getOperand(1), UNDEF);
17630     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17631     return;
17632   }
17633   case ISD::SIGN_EXTEND_INREG:
17634   case ISD::ADDC:
17635   case ISD::ADDE:
17636   case ISD::SUBC:
17637   case ISD::SUBE:
17638     // We don't want to expand or promote these.
17639     return;
17640   case ISD::SDIV:
17641   case ISD::UDIV:
17642   case ISD::SREM:
17643   case ISD::UREM:
17644   case ISD::SDIVREM:
17645   case ISD::UDIVREM: {
17646     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17647     Results.push_back(V);
17648     return;
17649   }
17650   case ISD::FP_TO_SINT:
17651     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
17652     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17653     if (N->getOperand(0).getValueType() == MVT::f16)
17654       break;
17655     // fallthrough
17656   case ISD::FP_TO_UINT: {
17657     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17658
17659     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17660       return;
17661
17662     std::pair<SDValue,SDValue> Vals =
17663         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17664     SDValue FIST = Vals.first, StackSlot = Vals.second;
17665     if (FIST.getNode()) {
17666       EVT VT = N->getValueType(0);
17667       // Return a load from the stack slot.
17668       if (StackSlot.getNode())
17669         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17670                                       MachinePointerInfo(),
17671                                       false, false, false, 0));
17672       else
17673         Results.push_back(FIST);
17674     }
17675     return;
17676   }
17677   case ISD::UINT_TO_FP: {
17678     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17679     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17680         N->getValueType(0) != MVT::v2f32)
17681       return;
17682     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17683                                  N->getOperand(0));
17684     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17685                                      MVT::f64);
17686     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17687     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17688                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17689     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17690     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17691     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17692     return;
17693   }
17694   case ISD::FP_ROUND: {
17695     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17696         return;
17697     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17698     Results.push_back(V);
17699     return;
17700   }
17701   case ISD::FP_EXTEND: {
17702     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17703     // No other ValueType for FP_EXTEND should reach this point.
17704     assert(N->getValueType(0) == MVT::v2f32 &&
17705            "Do not know how to legalize this Node");
17706     return;
17707   }
17708   case ISD::INTRINSIC_W_CHAIN: {
17709     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17710     switch (IntNo) {
17711     default : llvm_unreachable("Do not know how to custom type "
17712                                "legalize this intrinsic operation!");
17713     case Intrinsic::x86_rdtsc:
17714       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17715                                      Results);
17716     case Intrinsic::x86_rdtscp:
17717       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17718                                      Results);
17719     case Intrinsic::x86_rdpmc:
17720       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17721     }
17722   }
17723   case ISD::READCYCLECOUNTER: {
17724     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17725                                    Results);
17726   }
17727   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17728     EVT T = N->getValueType(0);
17729     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17730     bool Regs64bit = T == MVT::i128;
17731     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17732     SDValue cpInL, cpInH;
17733     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17734                         DAG.getConstant(0, dl, HalfT));
17735     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17736                         DAG.getConstant(1, dl, HalfT));
17737     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17738                              Regs64bit ? X86::RAX : X86::EAX,
17739                              cpInL, SDValue());
17740     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17741                              Regs64bit ? X86::RDX : X86::EDX,
17742                              cpInH, cpInL.getValue(1));
17743     SDValue swapInL, swapInH;
17744     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17745                           DAG.getConstant(0, dl, HalfT));
17746     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17747                           DAG.getConstant(1, dl, HalfT));
17748     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17749                                Regs64bit ? X86::RBX : X86::EBX,
17750                                swapInL, cpInH.getValue(1));
17751     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17752                                Regs64bit ? X86::RCX : X86::ECX,
17753                                swapInH, swapInL.getValue(1));
17754     SDValue Ops[] = { swapInH.getValue(0),
17755                       N->getOperand(1),
17756                       swapInH.getValue(1) };
17757     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17758     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17759     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17760                                   X86ISD::LCMPXCHG8_DAG;
17761     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17762     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17763                                         Regs64bit ? X86::RAX : X86::EAX,
17764                                         HalfT, Result.getValue(1));
17765     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17766                                         Regs64bit ? X86::RDX : X86::EDX,
17767                                         HalfT, cpOutL.getValue(2));
17768     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17769
17770     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17771                                         MVT::i32, cpOutH.getValue(2));
17772     SDValue Success =
17773         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17774                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17775     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17776
17777     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17778     Results.push_back(Success);
17779     Results.push_back(EFLAGS.getValue(1));
17780     return;
17781   }
17782   case ISD::ATOMIC_SWAP:
17783   case ISD::ATOMIC_LOAD_ADD:
17784   case ISD::ATOMIC_LOAD_SUB:
17785   case ISD::ATOMIC_LOAD_AND:
17786   case ISD::ATOMIC_LOAD_OR:
17787   case ISD::ATOMIC_LOAD_XOR:
17788   case ISD::ATOMIC_LOAD_NAND:
17789   case ISD::ATOMIC_LOAD_MIN:
17790   case ISD::ATOMIC_LOAD_MAX:
17791   case ISD::ATOMIC_LOAD_UMIN:
17792   case ISD::ATOMIC_LOAD_UMAX:
17793   case ISD::ATOMIC_LOAD: {
17794     // Delegate to generic TypeLegalization. Situations we can really handle
17795     // should have already been dealt with by AtomicExpandPass.cpp.
17796     break;
17797   }
17798   case ISD::BITCAST: {
17799     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17800     EVT DstVT = N->getValueType(0);
17801     EVT SrcVT = N->getOperand(0)->getValueType(0);
17802
17803     if (SrcVT != MVT::f64 ||
17804         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17805       return;
17806
17807     unsigned NumElts = DstVT.getVectorNumElements();
17808     EVT SVT = DstVT.getVectorElementType();
17809     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17810     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17811                                    MVT::v2f64, N->getOperand(0));
17812     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17813
17814     if (ExperimentalVectorWideningLegalization) {
17815       // If we are legalizing vectors by widening, we already have the desired
17816       // legal vector type, just return it.
17817       Results.push_back(ToVecInt);
17818       return;
17819     }
17820
17821     SmallVector<SDValue, 8> Elts;
17822     for (unsigned i = 0, e = NumElts; i != e; ++i)
17823       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17824                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17825
17826     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17827   }
17828   }
17829 }
17830
17831 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17832   switch ((X86ISD::NodeType)Opcode) {
17833   case X86ISD::FIRST_NUMBER:       break;
17834   case X86ISD::BSF:                return "X86ISD::BSF";
17835   case X86ISD::BSR:                return "X86ISD::BSR";
17836   case X86ISD::SHLD:               return "X86ISD::SHLD";
17837   case X86ISD::SHRD:               return "X86ISD::SHRD";
17838   case X86ISD::FAND:               return "X86ISD::FAND";
17839   case X86ISD::FANDN:              return "X86ISD::FANDN";
17840   case X86ISD::FOR:                return "X86ISD::FOR";
17841   case X86ISD::FXOR:               return "X86ISD::FXOR";
17842   case X86ISD::FSRL:               return "X86ISD::FSRL";
17843   case X86ISD::FILD:               return "X86ISD::FILD";
17844   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17845   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17846   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17847   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17848   case X86ISD::FLD:                return "X86ISD::FLD";
17849   case X86ISD::FST:                return "X86ISD::FST";
17850   case X86ISD::CALL:               return "X86ISD::CALL";
17851   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17852   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17853   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17854   case X86ISD::BT:                 return "X86ISD::BT";
17855   case X86ISD::CMP:                return "X86ISD::CMP";
17856   case X86ISD::COMI:               return "X86ISD::COMI";
17857   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17858   case X86ISD::CMPM:               return "X86ISD::CMPM";
17859   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17860   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
17861   case X86ISD::SETCC:              return "X86ISD::SETCC";
17862   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17863   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17864   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
17865   case X86ISD::CMOV:               return "X86ISD::CMOV";
17866   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17867   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17868   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17869   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17870   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17871   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17872   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17873   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
17874   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
17875   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
17876   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17877   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17878   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17879   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17880   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17881   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
17882   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17883   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17884   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17885   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17886   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17887   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
17888   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17889   case X86ISD::HADD:               return "X86ISD::HADD";
17890   case X86ISD::HSUB:               return "X86ISD::HSUB";
17891   case X86ISD::FHADD:              return "X86ISD::FHADD";
17892   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17893   case X86ISD::UMAX:               return "X86ISD::UMAX";
17894   case X86ISD::UMIN:               return "X86ISD::UMIN";
17895   case X86ISD::SMAX:               return "X86ISD::SMAX";
17896   case X86ISD::SMIN:               return "X86ISD::SMIN";
17897   case X86ISD::FMAX:               return "X86ISD::FMAX";
17898   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
17899   case X86ISD::FMIN:               return "X86ISD::FMIN";
17900   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
17901   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17902   case X86ISD::FMINC:              return "X86ISD::FMINC";
17903   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17904   case X86ISD::FRCP:               return "X86ISD::FRCP";
17905   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17906   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17907   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17908   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17909   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17910   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17911   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17912   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17913   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17914   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17915   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17916   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17917   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17918   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17919   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17920   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17921   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17922   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17923   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17924   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17925   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17926   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17927   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17928   case X86ISD::VSHL:               return "X86ISD::VSHL";
17929   case X86ISD::VSRL:               return "X86ISD::VSRL";
17930   case X86ISD::VSRA:               return "X86ISD::VSRA";
17931   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17932   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17933   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17934   case X86ISD::CMPP:               return "X86ISD::CMPP";
17935   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17936   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17937   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17938   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17939   case X86ISD::ADD:                return "X86ISD::ADD";
17940   case X86ISD::SUB:                return "X86ISD::SUB";
17941   case X86ISD::ADC:                return "X86ISD::ADC";
17942   case X86ISD::SBB:                return "X86ISD::SBB";
17943   case X86ISD::SMUL:               return "X86ISD::SMUL";
17944   case X86ISD::UMUL:               return "X86ISD::UMUL";
17945   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17946   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17947   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17948   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17949   case X86ISD::INC:                return "X86ISD::INC";
17950   case X86ISD::DEC:                return "X86ISD::DEC";
17951   case X86ISD::OR:                 return "X86ISD::OR";
17952   case X86ISD::XOR:                return "X86ISD::XOR";
17953   case X86ISD::AND:                return "X86ISD::AND";
17954   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17955   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17956   case X86ISD::PTEST:              return "X86ISD::PTEST";
17957   case X86ISD::TESTP:              return "X86ISD::TESTP";
17958   case X86ISD::TESTM:              return "X86ISD::TESTM";
17959   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17960   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17961   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17962   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17963   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17964   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17965   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17966   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17967   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17968   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17969   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17970   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17971   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17972   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17973   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17974   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17975   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17976   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17977   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17978   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17979   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17980   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17981   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17982   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17983   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
17984   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17985   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17986   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17987   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17988   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17989   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17990   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17991   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17992   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17993   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17994   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17995   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17996   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
17997   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
17998   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
17999   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18000   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18001   case X86ISD::SAHF:               return "X86ISD::SAHF";
18002   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18003   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18004   case X86ISD::FMADD:              return "X86ISD::FMADD";
18005   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18006   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18007   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18008   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18009   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18010   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18011   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18012   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18013   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18014   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18015   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18016   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18017   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18018   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18019   case X86ISD::XTEST:              return "X86ISD::XTEST";
18020   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18021   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18022   case X86ISD::SELECT:             return "X86ISD::SELECT";
18023   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18024   case X86ISD::RCP28:              return "X86ISD::RCP28";
18025   case X86ISD::EXP2:               return "X86ISD::EXP2";
18026   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18027   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18028   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18029   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18030   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18031   case X86ISD::ADDS:               return "X86ISD::ADDS";
18032   case X86ISD::SUBS:               return "X86ISD::SUBS";
18033   }
18034   return nullptr;
18035 }
18036
18037 // isLegalAddressingMode - Return true if the addressing mode represented
18038 // by AM is legal for this target, for a load/store of the specified type.
18039 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18040                                               Type *Ty) const {
18041   // X86 supports extremely general addressing modes.
18042   CodeModel::Model M = getTargetMachine().getCodeModel();
18043   Reloc::Model R = getTargetMachine().getRelocationModel();
18044
18045   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18046   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18047     return false;
18048
18049   if (AM.BaseGV) {
18050     unsigned GVFlags =
18051       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18052
18053     // If a reference to this global requires an extra load, we can't fold it.
18054     if (isGlobalStubReference(GVFlags))
18055       return false;
18056
18057     // If BaseGV requires a register for the PIC base, we cannot also have a
18058     // BaseReg specified.
18059     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18060       return false;
18061
18062     // If lower 4G is not available, then we must use rip-relative addressing.
18063     if ((M != CodeModel::Small || R != Reloc::Static) &&
18064         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18065       return false;
18066   }
18067
18068   switch (AM.Scale) {
18069   case 0:
18070   case 1:
18071   case 2:
18072   case 4:
18073   case 8:
18074     // These scales always work.
18075     break;
18076   case 3:
18077   case 5:
18078   case 9:
18079     // These scales are formed with basereg+scalereg.  Only accept if there is
18080     // no basereg yet.
18081     if (AM.HasBaseReg)
18082       return false;
18083     break;
18084   default:  // Other stuff never works.
18085     return false;
18086   }
18087
18088   return true;
18089 }
18090
18091 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18092   unsigned Bits = Ty->getScalarSizeInBits();
18093
18094   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18095   // particularly cheaper than those without.
18096   if (Bits == 8)
18097     return false;
18098
18099   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18100   // variable shifts just as cheap as scalar ones.
18101   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18102     return false;
18103
18104   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18105   // fully general vector.
18106   return true;
18107 }
18108
18109 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18110   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18111     return false;
18112   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18113   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18114   return NumBits1 > NumBits2;
18115 }
18116
18117 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18118   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18119     return false;
18120
18121   if (!isTypeLegal(EVT::getEVT(Ty1)))
18122     return false;
18123
18124   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18125
18126   // Assuming the caller doesn't have a zeroext or signext return parameter,
18127   // truncation all the way down to i1 is valid.
18128   return true;
18129 }
18130
18131 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18132   return isInt<32>(Imm);
18133 }
18134
18135 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18136   // Can also use sub to handle negated immediates.
18137   return isInt<32>(Imm);
18138 }
18139
18140 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18141   if (!VT1.isInteger() || !VT2.isInteger())
18142     return false;
18143   unsigned NumBits1 = VT1.getSizeInBits();
18144   unsigned NumBits2 = VT2.getSizeInBits();
18145   return NumBits1 > NumBits2;
18146 }
18147
18148 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18149   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18150   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18151 }
18152
18153 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18154   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18155   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18156 }
18157
18158 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18159   EVT VT1 = Val.getValueType();
18160   if (isZExtFree(VT1, VT2))
18161     return true;
18162
18163   if (Val.getOpcode() != ISD::LOAD)
18164     return false;
18165
18166   if (!VT1.isSimple() || !VT1.isInteger() ||
18167       !VT2.isSimple() || !VT2.isInteger())
18168     return false;
18169
18170   switch (VT1.getSimpleVT().SimpleTy) {
18171   default: break;
18172   case MVT::i8:
18173   case MVT::i16:
18174   case MVT::i32:
18175     // X86 has 8, 16, and 32-bit zero-extending loads.
18176     return true;
18177   }
18178
18179   return false;
18180 }
18181
18182 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18183
18184 bool
18185 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18186   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18187     return false;
18188
18189   VT = VT.getScalarType();
18190
18191   if (!VT.isSimple())
18192     return false;
18193
18194   switch (VT.getSimpleVT().SimpleTy) {
18195   case MVT::f32:
18196   case MVT::f64:
18197     return true;
18198   default:
18199     break;
18200   }
18201
18202   return false;
18203 }
18204
18205 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18206   // i16 instructions are longer (0x66 prefix) and potentially slower.
18207   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18208 }
18209
18210 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18211 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18212 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18213 /// are assumed to be legal.
18214 bool
18215 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18216                                       EVT VT) const {
18217   if (!VT.isSimple())
18218     return false;
18219
18220   // Not for i1 vectors
18221   if (VT.getScalarType() == MVT::i1)
18222     return false;
18223
18224   // Very little shuffling can be done for 64-bit vectors right now.
18225   if (VT.getSizeInBits() == 64)
18226     return false;
18227
18228   // We only care that the types being shuffled are legal. The lowering can
18229   // handle any possible shuffle mask that results.
18230   return isTypeLegal(VT.getSimpleVT());
18231 }
18232
18233 bool
18234 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18235                                           EVT VT) const {
18236   // Just delegate to the generic legality, clear masks aren't special.
18237   return isShuffleMaskLegal(Mask, VT);
18238 }
18239
18240 //===----------------------------------------------------------------------===//
18241 //                           X86 Scheduler Hooks
18242 //===----------------------------------------------------------------------===//
18243
18244 /// Utility function to emit xbegin specifying the start of an RTM region.
18245 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18246                                      const TargetInstrInfo *TII) {
18247   DebugLoc DL = MI->getDebugLoc();
18248
18249   const BasicBlock *BB = MBB->getBasicBlock();
18250   MachineFunction::iterator I = MBB;
18251   ++I;
18252
18253   // For the v = xbegin(), we generate
18254   //
18255   // thisMBB:
18256   //  xbegin sinkMBB
18257   //
18258   // mainMBB:
18259   //  eax = -1
18260   //
18261   // sinkMBB:
18262   //  v = eax
18263
18264   MachineBasicBlock *thisMBB = MBB;
18265   MachineFunction *MF = MBB->getParent();
18266   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18267   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18268   MF->insert(I, mainMBB);
18269   MF->insert(I, sinkMBB);
18270
18271   // Transfer the remainder of BB and its successor edges to sinkMBB.
18272   sinkMBB->splice(sinkMBB->begin(), MBB,
18273                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18274   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18275
18276   // thisMBB:
18277   //  xbegin sinkMBB
18278   //  # fallthrough to mainMBB
18279   //  # abortion to sinkMBB
18280   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18281   thisMBB->addSuccessor(mainMBB);
18282   thisMBB->addSuccessor(sinkMBB);
18283
18284   // mainMBB:
18285   //  EAX = -1
18286   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18287   mainMBB->addSuccessor(sinkMBB);
18288
18289   // sinkMBB:
18290   // EAX is live into the sinkMBB
18291   sinkMBB->addLiveIn(X86::EAX);
18292   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18293           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18294     .addReg(X86::EAX);
18295
18296   MI->eraseFromParent();
18297   return sinkMBB;
18298 }
18299
18300 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18301 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18302 // in the .td file.
18303 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18304                                        const TargetInstrInfo *TII) {
18305   unsigned Opc;
18306   switch (MI->getOpcode()) {
18307   default: llvm_unreachable("illegal opcode!");
18308   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18309   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18310   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18311   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18312   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18313   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18314   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18315   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18316   }
18317
18318   DebugLoc dl = MI->getDebugLoc();
18319   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18320
18321   unsigned NumArgs = MI->getNumOperands();
18322   for (unsigned i = 1; i < NumArgs; ++i) {
18323     MachineOperand &Op = MI->getOperand(i);
18324     if (!(Op.isReg() && Op.isImplicit()))
18325       MIB.addOperand(Op);
18326   }
18327   if (MI->hasOneMemOperand())
18328     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18329
18330   BuildMI(*BB, MI, dl,
18331     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18332     .addReg(X86::XMM0);
18333
18334   MI->eraseFromParent();
18335   return BB;
18336 }
18337
18338 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18339 // defs in an instruction pattern
18340 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18341                                        const TargetInstrInfo *TII) {
18342   unsigned Opc;
18343   switch (MI->getOpcode()) {
18344   default: llvm_unreachable("illegal opcode!");
18345   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18346   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18347   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18348   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18349   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18350   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18351   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18352   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18353   }
18354
18355   DebugLoc dl = MI->getDebugLoc();
18356   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18357
18358   unsigned NumArgs = MI->getNumOperands(); // remove the results
18359   for (unsigned i = 1; i < NumArgs; ++i) {
18360     MachineOperand &Op = MI->getOperand(i);
18361     if (!(Op.isReg() && Op.isImplicit()))
18362       MIB.addOperand(Op);
18363   }
18364   if (MI->hasOneMemOperand())
18365     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18366
18367   BuildMI(*BB, MI, dl,
18368     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18369     .addReg(X86::ECX);
18370
18371   MI->eraseFromParent();
18372   return BB;
18373 }
18374
18375 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18376                                       const X86Subtarget *Subtarget) {
18377   DebugLoc dl = MI->getDebugLoc();
18378   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18379   // Address into RAX/EAX, other two args into ECX, EDX.
18380   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18381   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18382   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18383   for (int i = 0; i < X86::AddrNumOperands; ++i)
18384     MIB.addOperand(MI->getOperand(i));
18385
18386   unsigned ValOps = X86::AddrNumOperands;
18387   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18388     .addReg(MI->getOperand(ValOps).getReg());
18389   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18390     .addReg(MI->getOperand(ValOps+1).getReg());
18391
18392   // The instruction doesn't actually take any operands though.
18393   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18394
18395   MI->eraseFromParent(); // The pseudo is gone now.
18396   return BB;
18397 }
18398
18399 MachineBasicBlock *
18400 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18401                                                  MachineBasicBlock *MBB) const {
18402   // Emit va_arg instruction on X86-64.
18403
18404   // Operands to this pseudo-instruction:
18405   // 0  ) Output        : destination address (reg)
18406   // 1-5) Input         : va_list address (addr, i64mem)
18407   // 6  ) ArgSize       : Size (in bytes) of vararg type
18408   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18409   // 8  ) Align         : Alignment of type
18410   // 9  ) EFLAGS (implicit-def)
18411
18412   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18413   static_assert(X86::AddrNumOperands == 5,
18414                 "VAARG_64 assumes 5 address operands");
18415
18416   unsigned DestReg = MI->getOperand(0).getReg();
18417   MachineOperand &Base = MI->getOperand(1);
18418   MachineOperand &Scale = MI->getOperand(2);
18419   MachineOperand &Index = MI->getOperand(3);
18420   MachineOperand &Disp = MI->getOperand(4);
18421   MachineOperand &Segment = MI->getOperand(5);
18422   unsigned ArgSize = MI->getOperand(6).getImm();
18423   unsigned ArgMode = MI->getOperand(7).getImm();
18424   unsigned Align = MI->getOperand(8).getImm();
18425
18426   // Memory Reference
18427   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18428   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18429   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18430
18431   // Machine Information
18432   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18433   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18434   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18435   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18436   DebugLoc DL = MI->getDebugLoc();
18437
18438   // struct va_list {
18439   //   i32   gp_offset
18440   //   i32   fp_offset
18441   //   i64   overflow_area (address)
18442   //   i64   reg_save_area (address)
18443   // }
18444   // sizeof(va_list) = 24
18445   // alignment(va_list) = 8
18446
18447   unsigned TotalNumIntRegs = 6;
18448   unsigned TotalNumXMMRegs = 8;
18449   bool UseGPOffset = (ArgMode == 1);
18450   bool UseFPOffset = (ArgMode == 2);
18451   unsigned MaxOffset = TotalNumIntRegs * 8 +
18452                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18453
18454   /* Align ArgSize to a multiple of 8 */
18455   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18456   bool NeedsAlign = (Align > 8);
18457
18458   MachineBasicBlock *thisMBB = MBB;
18459   MachineBasicBlock *overflowMBB;
18460   MachineBasicBlock *offsetMBB;
18461   MachineBasicBlock *endMBB;
18462
18463   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18464   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18465   unsigned OffsetReg = 0;
18466
18467   if (!UseGPOffset && !UseFPOffset) {
18468     // If we only pull from the overflow region, we don't create a branch.
18469     // We don't need to alter control flow.
18470     OffsetDestReg = 0; // unused
18471     OverflowDestReg = DestReg;
18472
18473     offsetMBB = nullptr;
18474     overflowMBB = thisMBB;
18475     endMBB = thisMBB;
18476   } else {
18477     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18478     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18479     // If not, pull from overflow_area. (branch to overflowMBB)
18480     //
18481     //       thisMBB
18482     //         |     .
18483     //         |        .
18484     //     offsetMBB   overflowMBB
18485     //         |        .
18486     //         |     .
18487     //        endMBB
18488
18489     // Registers for the PHI in endMBB
18490     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18491     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18492
18493     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18494     MachineFunction *MF = MBB->getParent();
18495     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18496     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18497     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18498
18499     MachineFunction::iterator MBBIter = MBB;
18500     ++MBBIter;
18501
18502     // Insert the new basic blocks
18503     MF->insert(MBBIter, offsetMBB);
18504     MF->insert(MBBIter, overflowMBB);
18505     MF->insert(MBBIter, endMBB);
18506
18507     // Transfer the remainder of MBB and its successor edges to endMBB.
18508     endMBB->splice(endMBB->begin(), thisMBB,
18509                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18510     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18511
18512     // Make offsetMBB and overflowMBB successors of thisMBB
18513     thisMBB->addSuccessor(offsetMBB);
18514     thisMBB->addSuccessor(overflowMBB);
18515
18516     // endMBB is a successor of both offsetMBB and overflowMBB
18517     offsetMBB->addSuccessor(endMBB);
18518     overflowMBB->addSuccessor(endMBB);
18519
18520     // Load the offset value into a register
18521     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18522     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18523       .addOperand(Base)
18524       .addOperand(Scale)
18525       .addOperand(Index)
18526       .addDisp(Disp, UseFPOffset ? 4 : 0)
18527       .addOperand(Segment)
18528       .setMemRefs(MMOBegin, MMOEnd);
18529
18530     // Check if there is enough room left to pull this argument.
18531     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18532       .addReg(OffsetReg)
18533       .addImm(MaxOffset + 8 - ArgSizeA8);
18534
18535     // Branch to "overflowMBB" if offset >= max
18536     // Fall through to "offsetMBB" otherwise
18537     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18538       .addMBB(overflowMBB);
18539   }
18540
18541   // In offsetMBB, emit code to use the reg_save_area.
18542   if (offsetMBB) {
18543     assert(OffsetReg != 0);
18544
18545     // Read the reg_save_area address.
18546     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18547     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18548       .addOperand(Base)
18549       .addOperand(Scale)
18550       .addOperand(Index)
18551       .addDisp(Disp, 16)
18552       .addOperand(Segment)
18553       .setMemRefs(MMOBegin, MMOEnd);
18554
18555     // Zero-extend the offset
18556     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18557       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18558         .addImm(0)
18559         .addReg(OffsetReg)
18560         .addImm(X86::sub_32bit);
18561
18562     // Add the offset to the reg_save_area to get the final address.
18563     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18564       .addReg(OffsetReg64)
18565       .addReg(RegSaveReg);
18566
18567     // Compute the offset for the next argument
18568     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18569     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18570       .addReg(OffsetReg)
18571       .addImm(UseFPOffset ? 16 : 8);
18572
18573     // Store it back into the va_list.
18574     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18575       .addOperand(Base)
18576       .addOperand(Scale)
18577       .addOperand(Index)
18578       .addDisp(Disp, UseFPOffset ? 4 : 0)
18579       .addOperand(Segment)
18580       .addReg(NextOffsetReg)
18581       .setMemRefs(MMOBegin, MMOEnd);
18582
18583     // Jump to endMBB
18584     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18585       .addMBB(endMBB);
18586   }
18587
18588   //
18589   // Emit code to use overflow area
18590   //
18591
18592   // Load the overflow_area address into a register.
18593   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18594   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18595     .addOperand(Base)
18596     .addOperand(Scale)
18597     .addOperand(Index)
18598     .addDisp(Disp, 8)
18599     .addOperand(Segment)
18600     .setMemRefs(MMOBegin, MMOEnd);
18601
18602   // If we need to align it, do so. Otherwise, just copy the address
18603   // to OverflowDestReg.
18604   if (NeedsAlign) {
18605     // Align the overflow address
18606     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18607     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18608
18609     // aligned_addr = (addr + (align-1)) & ~(align-1)
18610     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18611       .addReg(OverflowAddrReg)
18612       .addImm(Align-1);
18613
18614     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18615       .addReg(TmpReg)
18616       .addImm(~(uint64_t)(Align-1));
18617   } else {
18618     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18619       .addReg(OverflowAddrReg);
18620   }
18621
18622   // Compute the next overflow address after this argument.
18623   // (the overflow address should be kept 8-byte aligned)
18624   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18625   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18626     .addReg(OverflowDestReg)
18627     .addImm(ArgSizeA8);
18628
18629   // Store the new overflow address.
18630   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18631     .addOperand(Base)
18632     .addOperand(Scale)
18633     .addOperand(Index)
18634     .addDisp(Disp, 8)
18635     .addOperand(Segment)
18636     .addReg(NextAddrReg)
18637     .setMemRefs(MMOBegin, MMOEnd);
18638
18639   // If we branched, emit the PHI to the front of endMBB.
18640   if (offsetMBB) {
18641     BuildMI(*endMBB, endMBB->begin(), DL,
18642             TII->get(X86::PHI), DestReg)
18643       .addReg(OffsetDestReg).addMBB(offsetMBB)
18644       .addReg(OverflowDestReg).addMBB(overflowMBB);
18645   }
18646
18647   // Erase the pseudo instruction
18648   MI->eraseFromParent();
18649
18650   return endMBB;
18651 }
18652
18653 MachineBasicBlock *
18654 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18655                                                  MachineInstr *MI,
18656                                                  MachineBasicBlock *MBB) const {
18657   // Emit code to save XMM registers to the stack. The ABI says that the
18658   // number of registers to save is given in %al, so it's theoretically
18659   // possible to do an indirect jump trick to avoid saving all of them,
18660   // however this code takes a simpler approach and just executes all
18661   // of the stores if %al is non-zero. It's less code, and it's probably
18662   // easier on the hardware branch predictor, and stores aren't all that
18663   // expensive anyway.
18664
18665   // Create the new basic blocks. One block contains all the XMM stores,
18666   // and one block is the final destination regardless of whether any
18667   // stores were performed.
18668   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18669   MachineFunction *F = MBB->getParent();
18670   MachineFunction::iterator MBBIter = MBB;
18671   ++MBBIter;
18672   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18673   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18674   F->insert(MBBIter, XMMSaveMBB);
18675   F->insert(MBBIter, EndMBB);
18676
18677   // Transfer the remainder of MBB and its successor edges to EndMBB.
18678   EndMBB->splice(EndMBB->begin(), MBB,
18679                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18680   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18681
18682   // The original block will now fall through to the XMM save block.
18683   MBB->addSuccessor(XMMSaveMBB);
18684   // The XMMSaveMBB will fall through to the end block.
18685   XMMSaveMBB->addSuccessor(EndMBB);
18686
18687   // Now add the instructions.
18688   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18689   DebugLoc DL = MI->getDebugLoc();
18690
18691   unsigned CountReg = MI->getOperand(0).getReg();
18692   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18693   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18694
18695   if (!Subtarget->isTargetWin64()) {
18696     // If %al is 0, branch around the XMM save block.
18697     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18698     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18699     MBB->addSuccessor(EndMBB);
18700   }
18701
18702   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18703   // that was just emitted, but clearly shouldn't be "saved".
18704   assert((MI->getNumOperands() <= 3 ||
18705           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18706           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18707          && "Expected last argument to be EFLAGS");
18708   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18709   // In the XMM save block, save all the XMM argument registers.
18710   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18711     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18712     MachineMemOperand *MMO =
18713       F->getMachineMemOperand(
18714           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18715         MachineMemOperand::MOStore,
18716         /*Size=*/16, /*Align=*/16);
18717     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18718       .addFrameIndex(RegSaveFrameIndex)
18719       .addImm(/*Scale=*/1)
18720       .addReg(/*IndexReg=*/0)
18721       .addImm(/*Disp=*/Offset)
18722       .addReg(/*Segment=*/0)
18723       .addReg(MI->getOperand(i).getReg())
18724       .addMemOperand(MMO);
18725   }
18726
18727   MI->eraseFromParent();   // The pseudo instruction is gone now.
18728
18729   return EndMBB;
18730 }
18731
18732 // The EFLAGS operand of SelectItr might be missing a kill marker
18733 // because there were multiple uses of EFLAGS, and ISel didn't know
18734 // which to mark. Figure out whether SelectItr should have had a
18735 // kill marker, and set it if it should. Returns the correct kill
18736 // marker value.
18737 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18738                                      MachineBasicBlock* BB,
18739                                      const TargetRegisterInfo* TRI) {
18740   // Scan forward through BB for a use/def of EFLAGS.
18741   MachineBasicBlock::iterator miI(std::next(SelectItr));
18742   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18743     const MachineInstr& mi = *miI;
18744     if (mi.readsRegister(X86::EFLAGS))
18745       return false;
18746     if (mi.definesRegister(X86::EFLAGS))
18747       break; // Should have kill-flag - update below.
18748   }
18749
18750   // If we hit the end of the block, check whether EFLAGS is live into a
18751   // successor.
18752   if (miI == BB->end()) {
18753     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18754                                           sEnd = BB->succ_end();
18755          sItr != sEnd; ++sItr) {
18756       MachineBasicBlock* succ = *sItr;
18757       if (succ->isLiveIn(X86::EFLAGS))
18758         return false;
18759     }
18760   }
18761
18762   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18763   // out. SelectMI should have a kill flag on EFLAGS.
18764   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18765   return true;
18766 }
18767
18768 MachineBasicBlock *
18769 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18770                                      MachineBasicBlock *BB) const {
18771   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18772   DebugLoc DL = MI->getDebugLoc();
18773
18774   // To "insert" a SELECT_CC instruction, we actually have to insert the
18775   // diamond control-flow pattern.  The incoming instruction knows the
18776   // destination vreg to set, the condition code register to branch on, the
18777   // true/false values to select between, and a branch opcode to use.
18778   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18779   MachineFunction::iterator It = BB;
18780   ++It;
18781
18782   //  thisMBB:
18783   //  ...
18784   //   TrueVal = ...
18785   //   cmpTY ccX, r1, r2
18786   //   bCC copy1MBB
18787   //   fallthrough --> copy0MBB
18788   MachineBasicBlock *thisMBB = BB;
18789   MachineFunction *F = BB->getParent();
18790
18791   // We also lower double CMOVs:
18792   //   (CMOV (CMOV F, T, cc1), T, cc2)
18793   // to two successives branches.  For that, we look for another CMOV as the
18794   // following instruction.
18795   //
18796   // Without this, we would add a PHI between the two jumps, which ends up
18797   // creating a few copies all around. For instance, for
18798   //
18799   //    (sitofp (zext (fcmp une)))
18800   //
18801   // we would generate:
18802   //
18803   //         ucomiss %xmm1, %xmm0
18804   //         movss  <1.0f>, %xmm0
18805   //         movaps  %xmm0, %xmm1
18806   //         jne     .LBB5_2
18807   //         xorps   %xmm1, %xmm1
18808   // .LBB5_2:
18809   //         jp      .LBB5_4
18810   //         movaps  %xmm1, %xmm0
18811   // .LBB5_4:
18812   //         retq
18813   //
18814   // because this custom-inserter would have generated:
18815   //
18816   //   A
18817   //   | \
18818   //   |  B
18819   //   | /
18820   //   C
18821   //   | \
18822   //   |  D
18823   //   | /
18824   //   E
18825   //
18826   // A: X = ...; Y = ...
18827   // B: empty
18828   // C: Z = PHI [X, A], [Y, B]
18829   // D: empty
18830   // E: PHI [X, C], [Z, D]
18831   //
18832   // If we lower both CMOVs in a single step, we can instead generate:
18833   //
18834   //   A
18835   //   | \
18836   //   |  C
18837   //   | /|
18838   //   |/ |
18839   //   |  |
18840   //   |  D
18841   //   | /
18842   //   E
18843   //
18844   // A: X = ...; Y = ...
18845   // D: empty
18846   // E: PHI [X, A], [X, C], [Y, D]
18847   //
18848   // Which, in our sitofp/fcmp example, gives us something like:
18849   //
18850   //         ucomiss %xmm1, %xmm0
18851   //         movss  <1.0f>, %xmm0
18852   //         jne     .LBB5_4
18853   //         jp      .LBB5_4
18854   //         xorps   %xmm0, %xmm0
18855   // .LBB5_4:
18856   //         retq
18857   //
18858   MachineInstr *NextCMOV = nullptr;
18859   MachineBasicBlock::iterator NextMIIt =
18860       std::next(MachineBasicBlock::iterator(MI));
18861   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18862       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18863       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18864     NextCMOV = &*NextMIIt;
18865
18866   MachineBasicBlock *jcc1MBB = nullptr;
18867
18868   // If we have a double CMOV, we lower it to two successive branches to
18869   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18870   if (NextCMOV) {
18871     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18872     F->insert(It, jcc1MBB);
18873     jcc1MBB->addLiveIn(X86::EFLAGS);
18874   }
18875
18876   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18877   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18878   F->insert(It, copy0MBB);
18879   F->insert(It, sinkMBB);
18880
18881   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18882   // live into the sink and copy blocks.
18883   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18884
18885   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18886   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18887       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18888     copy0MBB->addLiveIn(X86::EFLAGS);
18889     sinkMBB->addLiveIn(X86::EFLAGS);
18890   }
18891
18892   // Transfer the remainder of BB and its successor edges to sinkMBB.
18893   sinkMBB->splice(sinkMBB->begin(), BB,
18894                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18895   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18896
18897   // Add the true and fallthrough blocks as its successors.
18898   if (NextCMOV) {
18899     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18900     BB->addSuccessor(jcc1MBB);
18901
18902     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18903     // jump to the sinkMBB.
18904     jcc1MBB->addSuccessor(copy0MBB);
18905     jcc1MBB->addSuccessor(sinkMBB);
18906   } else {
18907     BB->addSuccessor(copy0MBB);
18908   }
18909
18910   // The true block target of the first (or only) branch is always sinkMBB.
18911   BB->addSuccessor(sinkMBB);
18912
18913   // Create the conditional branch instruction.
18914   unsigned Opc =
18915     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18916   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18917
18918   if (NextCMOV) {
18919     unsigned Opc2 = X86::GetCondBranchFromCond(
18920         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18921     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18922   }
18923
18924   //  copy0MBB:
18925   //   %FalseValue = ...
18926   //   # fallthrough to sinkMBB
18927   copy0MBB->addSuccessor(sinkMBB);
18928
18929   //  sinkMBB:
18930   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18931   //  ...
18932   MachineInstrBuilder MIB =
18933       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18934               MI->getOperand(0).getReg())
18935           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18936           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18937
18938   // If we have a double CMOV, the second Jcc provides the same incoming
18939   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18940   if (NextCMOV) {
18941     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18942     // Copy the PHI result to the register defined by the second CMOV.
18943     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18944             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18945         .addReg(MI->getOperand(0).getReg());
18946     NextCMOV->eraseFromParent();
18947   }
18948
18949   MI->eraseFromParent();   // The pseudo instruction is gone now.
18950   return sinkMBB;
18951 }
18952
18953 MachineBasicBlock *
18954 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18955                                         MachineBasicBlock *BB) const {
18956   MachineFunction *MF = BB->getParent();
18957   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18958   DebugLoc DL = MI->getDebugLoc();
18959   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18960
18961   assert(MF->shouldSplitStack());
18962
18963   const bool Is64Bit = Subtarget->is64Bit();
18964   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18965
18966   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18967   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18968
18969   // BB:
18970   //  ... [Till the alloca]
18971   // If stacklet is not large enough, jump to mallocMBB
18972   //
18973   // bumpMBB:
18974   //  Allocate by subtracting from RSP
18975   //  Jump to continueMBB
18976   //
18977   // mallocMBB:
18978   //  Allocate by call to runtime
18979   //
18980   // continueMBB:
18981   //  ...
18982   //  [rest of original BB]
18983   //
18984
18985   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18986   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18987   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18988
18989   MachineRegisterInfo &MRI = MF->getRegInfo();
18990   const TargetRegisterClass *AddrRegClass =
18991     getRegClassFor(getPointerTy());
18992
18993   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18994     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18995     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18996     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18997     sizeVReg = MI->getOperand(1).getReg(),
18998     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18999
19000   MachineFunction::iterator MBBIter = BB;
19001   ++MBBIter;
19002
19003   MF->insert(MBBIter, bumpMBB);
19004   MF->insert(MBBIter, mallocMBB);
19005   MF->insert(MBBIter, continueMBB);
19006
19007   continueMBB->splice(continueMBB->begin(), BB,
19008                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19009   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19010
19011   // Add code to the main basic block to check if the stack limit has been hit,
19012   // and if so, jump to mallocMBB otherwise to bumpMBB.
19013   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19014   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19015     .addReg(tmpSPVReg).addReg(sizeVReg);
19016   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19017     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19018     .addReg(SPLimitVReg);
19019   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19020
19021   // bumpMBB simply decreases the stack pointer, since we know the current
19022   // stacklet has enough space.
19023   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19024     .addReg(SPLimitVReg);
19025   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19026     .addReg(SPLimitVReg);
19027   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19028
19029   // Calls into a routine in libgcc to allocate more space from the heap.
19030   const uint32_t *RegMask =
19031       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19032   if (IsLP64) {
19033     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19034       .addReg(sizeVReg);
19035     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19036       .addExternalSymbol("__morestack_allocate_stack_space")
19037       .addRegMask(RegMask)
19038       .addReg(X86::RDI, RegState::Implicit)
19039       .addReg(X86::RAX, RegState::ImplicitDefine);
19040   } else if (Is64Bit) {
19041     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19042       .addReg(sizeVReg);
19043     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19044       .addExternalSymbol("__morestack_allocate_stack_space")
19045       .addRegMask(RegMask)
19046       .addReg(X86::EDI, RegState::Implicit)
19047       .addReg(X86::EAX, RegState::ImplicitDefine);
19048   } else {
19049     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19050       .addImm(12);
19051     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19052     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19053       .addExternalSymbol("__morestack_allocate_stack_space")
19054       .addRegMask(RegMask)
19055       .addReg(X86::EAX, RegState::ImplicitDefine);
19056   }
19057
19058   if (!Is64Bit)
19059     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19060       .addImm(16);
19061
19062   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19063     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19064   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19065
19066   // Set up the CFG correctly.
19067   BB->addSuccessor(bumpMBB);
19068   BB->addSuccessor(mallocMBB);
19069   mallocMBB->addSuccessor(continueMBB);
19070   bumpMBB->addSuccessor(continueMBB);
19071
19072   // Take care of the PHI nodes.
19073   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19074           MI->getOperand(0).getReg())
19075     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19076     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19077
19078   // Delete the original pseudo instruction.
19079   MI->eraseFromParent();
19080
19081   // And we're done.
19082   return continueMBB;
19083 }
19084
19085 MachineBasicBlock *
19086 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19087                                         MachineBasicBlock *BB) const {
19088   DebugLoc DL = MI->getDebugLoc();
19089
19090   assert(!Subtarget->isTargetMachO());
19091
19092   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19093
19094   MI->eraseFromParent();   // The pseudo instruction is gone now.
19095   return BB;
19096 }
19097
19098 MachineBasicBlock *
19099 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19100                                       MachineBasicBlock *BB) const {
19101   // This is pretty easy.  We're taking the value that we received from
19102   // our load from the relocation, sticking it in either RDI (x86-64)
19103   // or EAX and doing an indirect call.  The return value will then
19104   // be in the normal return register.
19105   MachineFunction *F = BB->getParent();
19106   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19107   DebugLoc DL = MI->getDebugLoc();
19108
19109   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19110   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19111
19112   // Get a register mask for the lowered call.
19113   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19114   // proper register mask.
19115   const uint32_t *RegMask =
19116       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19117   if (Subtarget->is64Bit()) {
19118     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19119                                       TII->get(X86::MOV64rm), X86::RDI)
19120     .addReg(X86::RIP)
19121     .addImm(0).addReg(0)
19122     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19123                       MI->getOperand(3).getTargetFlags())
19124     .addReg(0);
19125     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19126     addDirectMem(MIB, X86::RDI);
19127     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19128   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19129     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19130                                       TII->get(X86::MOV32rm), X86::EAX)
19131     .addReg(0)
19132     .addImm(0).addReg(0)
19133     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19134                       MI->getOperand(3).getTargetFlags())
19135     .addReg(0);
19136     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19137     addDirectMem(MIB, X86::EAX);
19138     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19139   } else {
19140     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19141                                       TII->get(X86::MOV32rm), X86::EAX)
19142     .addReg(TII->getGlobalBaseReg(F))
19143     .addImm(0).addReg(0)
19144     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19145                       MI->getOperand(3).getTargetFlags())
19146     .addReg(0);
19147     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19148     addDirectMem(MIB, X86::EAX);
19149     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19150   }
19151
19152   MI->eraseFromParent(); // The pseudo instruction is gone now.
19153   return BB;
19154 }
19155
19156 MachineBasicBlock *
19157 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19158                                     MachineBasicBlock *MBB) const {
19159   DebugLoc DL = MI->getDebugLoc();
19160   MachineFunction *MF = MBB->getParent();
19161   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19162   MachineRegisterInfo &MRI = MF->getRegInfo();
19163
19164   const BasicBlock *BB = MBB->getBasicBlock();
19165   MachineFunction::iterator I = MBB;
19166   ++I;
19167
19168   // Memory Reference
19169   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19170   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19171
19172   unsigned DstReg;
19173   unsigned MemOpndSlot = 0;
19174
19175   unsigned CurOp = 0;
19176
19177   DstReg = MI->getOperand(CurOp++).getReg();
19178   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19179   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19180   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19181   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19182
19183   MemOpndSlot = CurOp;
19184
19185   MVT PVT = getPointerTy();
19186   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19187          "Invalid Pointer Size!");
19188
19189   // For v = setjmp(buf), we generate
19190   //
19191   // thisMBB:
19192   //  buf[LabelOffset] = restoreMBB
19193   //  SjLjSetup restoreMBB
19194   //
19195   // mainMBB:
19196   //  v_main = 0
19197   //
19198   // sinkMBB:
19199   //  v = phi(main, restore)
19200   //
19201   // restoreMBB:
19202   //  if base pointer being used, load it from frame
19203   //  v_restore = 1
19204
19205   MachineBasicBlock *thisMBB = MBB;
19206   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19207   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19208   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19209   MF->insert(I, mainMBB);
19210   MF->insert(I, sinkMBB);
19211   MF->push_back(restoreMBB);
19212
19213   MachineInstrBuilder MIB;
19214
19215   // Transfer the remainder of BB and its successor edges to sinkMBB.
19216   sinkMBB->splice(sinkMBB->begin(), MBB,
19217                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19218   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19219
19220   // thisMBB:
19221   unsigned PtrStoreOpc = 0;
19222   unsigned LabelReg = 0;
19223   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19224   Reloc::Model RM = MF->getTarget().getRelocationModel();
19225   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19226                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19227
19228   // Prepare IP either in reg or imm.
19229   if (!UseImmLabel) {
19230     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19231     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19232     LabelReg = MRI.createVirtualRegister(PtrRC);
19233     if (Subtarget->is64Bit()) {
19234       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19235               .addReg(X86::RIP)
19236               .addImm(0)
19237               .addReg(0)
19238               .addMBB(restoreMBB)
19239               .addReg(0);
19240     } else {
19241       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19242       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19243               .addReg(XII->getGlobalBaseReg(MF))
19244               .addImm(0)
19245               .addReg(0)
19246               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19247               .addReg(0);
19248     }
19249   } else
19250     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19251   // Store IP
19252   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19253   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19254     if (i == X86::AddrDisp)
19255       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19256     else
19257       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19258   }
19259   if (!UseImmLabel)
19260     MIB.addReg(LabelReg);
19261   else
19262     MIB.addMBB(restoreMBB);
19263   MIB.setMemRefs(MMOBegin, MMOEnd);
19264   // Setup
19265   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19266           .addMBB(restoreMBB);
19267
19268   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19269   MIB.addRegMask(RegInfo->getNoPreservedMask());
19270   thisMBB->addSuccessor(mainMBB);
19271   thisMBB->addSuccessor(restoreMBB);
19272
19273   // mainMBB:
19274   //  EAX = 0
19275   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19276   mainMBB->addSuccessor(sinkMBB);
19277
19278   // sinkMBB:
19279   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19280           TII->get(X86::PHI), DstReg)
19281     .addReg(mainDstReg).addMBB(mainMBB)
19282     .addReg(restoreDstReg).addMBB(restoreMBB);
19283
19284   // restoreMBB:
19285   if (RegInfo->hasBasePointer(*MF)) {
19286     const bool Uses64BitFramePtr =
19287         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19288     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19289     X86FI->setRestoreBasePointer(MF);
19290     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19291     unsigned BasePtr = RegInfo->getBaseRegister();
19292     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19293     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19294                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19295       .setMIFlag(MachineInstr::FrameSetup);
19296   }
19297   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19298   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19299   restoreMBB->addSuccessor(sinkMBB);
19300
19301   MI->eraseFromParent();
19302   return sinkMBB;
19303 }
19304
19305 MachineBasicBlock *
19306 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19307                                      MachineBasicBlock *MBB) const {
19308   DebugLoc DL = MI->getDebugLoc();
19309   MachineFunction *MF = MBB->getParent();
19310   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19311   MachineRegisterInfo &MRI = MF->getRegInfo();
19312
19313   // Memory Reference
19314   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19315   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19316
19317   MVT PVT = getPointerTy();
19318   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19319          "Invalid Pointer Size!");
19320
19321   const TargetRegisterClass *RC =
19322     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19323   unsigned Tmp = MRI.createVirtualRegister(RC);
19324   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19325   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19326   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19327   unsigned SP = RegInfo->getStackRegister();
19328
19329   MachineInstrBuilder MIB;
19330
19331   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19332   const int64_t SPOffset = 2 * PVT.getStoreSize();
19333
19334   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19335   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19336
19337   // Reload FP
19338   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19339   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19340     MIB.addOperand(MI->getOperand(i));
19341   MIB.setMemRefs(MMOBegin, MMOEnd);
19342   // Reload IP
19343   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19344   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19345     if (i == X86::AddrDisp)
19346       MIB.addDisp(MI->getOperand(i), LabelOffset);
19347     else
19348       MIB.addOperand(MI->getOperand(i));
19349   }
19350   MIB.setMemRefs(MMOBegin, MMOEnd);
19351   // Reload SP
19352   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19353   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19354     if (i == X86::AddrDisp)
19355       MIB.addDisp(MI->getOperand(i), SPOffset);
19356     else
19357       MIB.addOperand(MI->getOperand(i));
19358   }
19359   MIB.setMemRefs(MMOBegin, MMOEnd);
19360   // Jump
19361   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19362
19363   MI->eraseFromParent();
19364   return MBB;
19365 }
19366
19367 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19368 // accumulator loops. Writing back to the accumulator allows the coalescer
19369 // to remove extra copies in the loop.
19370 MachineBasicBlock *
19371 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19372                                  MachineBasicBlock *MBB) const {
19373   MachineOperand &AddendOp = MI->getOperand(3);
19374
19375   // Bail out early if the addend isn't a register - we can't switch these.
19376   if (!AddendOp.isReg())
19377     return MBB;
19378
19379   MachineFunction &MF = *MBB->getParent();
19380   MachineRegisterInfo &MRI = MF.getRegInfo();
19381
19382   // Check whether the addend is defined by a PHI:
19383   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19384   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19385   if (!AddendDef.isPHI())
19386     return MBB;
19387
19388   // Look for the following pattern:
19389   // loop:
19390   //   %addend = phi [%entry, 0], [%loop, %result]
19391   //   ...
19392   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19393
19394   // Replace with:
19395   //   loop:
19396   //   %addend = phi [%entry, 0], [%loop, %result]
19397   //   ...
19398   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19399
19400   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19401     assert(AddendDef.getOperand(i).isReg());
19402     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19403     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19404     if (&PHISrcInst == MI) {
19405       // Found a matching instruction.
19406       unsigned NewFMAOpc = 0;
19407       switch (MI->getOpcode()) {
19408         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19409         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19410         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19411         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19412         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19413         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19414         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19415         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19416         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19417         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19418         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19419         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19420         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19421         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19422         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19423         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19424         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19425         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19426         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19427         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19428
19429         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19430         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19431         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19432         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19433         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19434         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19435         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19436         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19437         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19438         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19439         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19440         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19441         default: llvm_unreachable("Unrecognized FMA variant.");
19442       }
19443
19444       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19445       MachineInstrBuilder MIB =
19446         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19447         .addOperand(MI->getOperand(0))
19448         .addOperand(MI->getOperand(3))
19449         .addOperand(MI->getOperand(2))
19450         .addOperand(MI->getOperand(1));
19451       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19452       MI->eraseFromParent();
19453     }
19454   }
19455
19456   return MBB;
19457 }
19458
19459 MachineBasicBlock *
19460 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19461                                                MachineBasicBlock *BB) const {
19462   switch (MI->getOpcode()) {
19463   default: llvm_unreachable("Unexpected instr type to insert");
19464   case X86::TAILJMPd64:
19465   case X86::TAILJMPr64:
19466   case X86::TAILJMPm64:
19467   case X86::TAILJMPd64_REX:
19468   case X86::TAILJMPr64_REX:
19469   case X86::TAILJMPm64_REX:
19470     llvm_unreachable("TAILJMP64 would not be touched here.");
19471   case X86::TCRETURNdi64:
19472   case X86::TCRETURNri64:
19473   case X86::TCRETURNmi64:
19474     return BB;
19475   case X86::WIN_ALLOCA:
19476     return EmitLoweredWinAlloca(MI, BB);
19477   case X86::SEG_ALLOCA_32:
19478   case X86::SEG_ALLOCA_64:
19479     return EmitLoweredSegAlloca(MI, BB);
19480   case X86::TLSCall_32:
19481   case X86::TLSCall_64:
19482     return EmitLoweredTLSCall(MI, BB);
19483   case X86::CMOV_GR8:
19484   case X86::CMOV_FR32:
19485   case X86::CMOV_FR64:
19486   case X86::CMOV_V4F32:
19487   case X86::CMOV_V2F64:
19488   case X86::CMOV_V2I64:
19489   case X86::CMOV_V8F32:
19490   case X86::CMOV_V4F64:
19491   case X86::CMOV_V4I64:
19492   case X86::CMOV_V16F32:
19493   case X86::CMOV_V8F64:
19494   case X86::CMOV_V8I64:
19495   case X86::CMOV_GR16:
19496   case X86::CMOV_GR32:
19497   case X86::CMOV_RFP32:
19498   case X86::CMOV_RFP64:
19499   case X86::CMOV_RFP80:
19500   case X86::CMOV_V8I1:
19501   case X86::CMOV_V16I1:
19502   case X86::CMOV_V32I1:
19503   case X86::CMOV_V64I1:
19504     return EmitLoweredSelect(MI, BB);
19505
19506   case X86::FP32_TO_INT16_IN_MEM:
19507   case X86::FP32_TO_INT32_IN_MEM:
19508   case X86::FP32_TO_INT64_IN_MEM:
19509   case X86::FP64_TO_INT16_IN_MEM:
19510   case X86::FP64_TO_INT32_IN_MEM:
19511   case X86::FP64_TO_INT64_IN_MEM:
19512   case X86::FP80_TO_INT16_IN_MEM:
19513   case X86::FP80_TO_INT32_IN_MEM:
19514   case X86::FP80_TO_INT64_IN_MEM: {
19515     MachineFunction *F = BB->getParent();
19516     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19517     DebugLoc DL = MI->getDebugLoc();
19518
19519     // Change the floating point control register to use "round towards zero"
19520     // mode when truncating to an integer value.
19521     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19522     addFrameReference(BuildMI(*BB, MI, DL,
19523                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19524
19525     // Load the old value of the high byte of the control word...
19526     unsigned OldCW =
19527       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19528     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19529                       CWFrameIdx);
19530
19531     // Set the high part to be round to zero...
19532     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19533       .addImm(0xC7F);
19534
19535     // Reload the modified control word now...
19536     addFrameReference(BuildMI(*BB, MI, DL,
19537                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19538
19539     // Restore the memory image of control word to original value
19540     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19541       .addReg(OldCW);
19542
19543     // Get the X86 opcode to use.
19544     unsigned Opc;
19545     switch (MI->getOpcode()) {
19546     default: llvm_unreachable("illegal opcode!");
19547     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19548     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19549     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19550     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19551     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19552     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19553     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19554     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19555     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19556     }
19557
19558     X86AddressMode AM;
19559     MachineOperand &Op = MI->getOperand(0);
19560     if (Op.isReg()) {
19561       AM.BaseType = X86AddressMode::RegBase;
19562       AM.Base.Reg = Op.getReg();
19563     } else {
19564       AM.BaseType = X86AddressMode::FrameIndexBase;
19565       AM.Base.FrameIndex = Op.getIndex();
19566     }
19567     Op = MI->getOperand(1);
19568     if (Op.isImm())
19569       AM.Scale = Op.getImm();
19570     Op = MI->getOperand(2);
19571     if (Op.isImm())
19572       AM.IndexReg = Op.getImm();
19573     Op = MI->getOperand(3);
19574     if (Op.isGlobal()) {
19575       AM.GV = Op.getGlobal();
19576     } else {
19577       AM.Disp = Op.getImm();
19578     }
19579     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19580                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19581
19582     // Reload the original control word now.
19583     addFrameReference(BuildMI(*BB, MI, DL,
19584                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19585
19586     MI->eraseFromParent();   // The pseudo instruction is gone now.
19587     return BB;
19588   }
19589     // String/text processing lowering.
19590   case X86::PCMPISTRM128REG:
19591   case X86::VPCMPISTRM128REG:
19592   case X86::PCMPISTRM128MEM:
19593   case X86::VPCMPISTRM128MEM:
19594   case X86::PCMPESTRM128REG:
19595   case X86::VPCMPESTRM128REG:
19596   case X86::PCMPESTRM128MEM:
19597   case X86::VPCMPESTRM128MEM:
19598     assert(Subtarget->hasSSE42() &&
19599            "Target must have SSE4.2 or AVX features enabled");
19600     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19601
19602   // String/text processing lowering.
19603   case X86::PCMPISTRIREG:
19604   case X86::VPCMPISTRIREG:
19605   case X86::PCMPISTRIMEM:
19606   case X86::VPCMPISTRIMEM:
19607   case X86::PCMPESTRIREG:
19608   case X86::VPCMPESTRIREG:
19609   case X86::PCMPESTRIMEM:
19610   case X86::VPCMPESTRIMEM:
19611     assert(Subtarget->hasSSE42() &&
19612            "Target must have SSE4.2 or AVX features enabled");
19613     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19614
19615   // Thread synchronization.
19616   case X86::MONITOR:
19617     return EmitMonitor(MI, BB, Subtarget);
19618
19619   // xbegin
19620   case X86::XBEGIN:
19621     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19622
19623   case X86::VASTART_SAVE_XMM_REGS:
19624     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19625
19626   case X86::VAARG_64:
19627     return EmitVAARG64WithCustomInserter(MI, BB);
19628
19629   case X86::EH_SjLj_SetJmp32:
19630   case X86::EH_SjLj_SetJmp64:
19631     return emitEHSjLjSetJmp(MI, BB);
19632
19633   case X86::EH_SjLj_LongJmp32:
19634   case X86::EH_SjLj_LongJmp64:
19635     return emitEHSjLjLongJmp(MI, BB);
19636
19637   case TargetOpcode::STATEPOINT:
19638     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19639     // this point in the process.  We diverge later.
19640     return emitPatchPoint(MI, BB);
19641
19642   case TargetOpcode::STACKMAP:
19643   case TargetOpcode::PATCHPOINT:
19644     return emitPatchPoint(MI, BB);
19645
19646   case X86::VFMADDPDr213r:
19647   case X86::VFMADDPSr213r:
19648   case X86::VFMADDSDr213r:
19649   case X86::VFMADDSSr213r:
19650   case X86::VFMSUBPDr213r:
19651   case X86::VFMSUBPSr213r:
19652   case X86::VFMSUBSDr213r:
19653   case X86::VFMSUBSSr213r:
19654   case X86::VFNMADDPDr213r:
19655   case X86::VFNMADDPSr213r:
19656   case X86::VFNMADDSDr213r:
19657   case X86::VFNMADDSSr213r:
19658   case X86::VFNMSUBPDr213r:
19659   case X86::VFNMSUBPSr213r:
19660   case X86::VFNMSUBSDr213r:
19661   case X86::VFNMSUBSSr213r:
19662   case X86::VFMADDSUBPDr213r:
19663   case X86::VFMADDSUBPSr213r:
19664   case X86::VFMSUBADDPDr213r:
19665   case X86::VFMSUBADDPSr213r:
19666   case X86::VFMADDPDr213rY:
19667   case X86::VFMADDPSr213rY:
19668   case X86::VFMSUBPDr213rY:
19669   case X86::VFMSUBPSr213rY:
19670   case X86::VFNMADDPDr213rY:
19671   case X86::VFNMADDPSr213rY:
19672   case X86::VFNMSUBPDr213rY:
19673   case X86::VFNMSUBPSr213rY:
19674   case X86::VFMADDSUBPDr213rY:
19675   case X86::VFMADDSUBPSr213rY:
19676   case X86::VFMSUBADDPDr213rY:
19677   case X86::VFMSUBADDPSr213rY:
19678     return emitFMA3Instr(MI, BB);
19679   }
19680 }
19681
19682 //===----------------------------------------------------------------------===//
19683 //                           X86 Optimization Hooks
19684 //===----------------------------------------------------------------------===//
19685
19686 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19687                                                       APInt &KnownZero,
19688                                                       APInt &KnownOne,
19689                                                       const SelectionDAG &DAG,
19690                                                       unsigned Depth) const {
19691   unsigned BitWidth = KnownZero.getBitWidth();
19692   unsigned Opc = Op.getOpcode();
19693   assert((Opc >= ISD::BUILTIN_OP_END ||
19694           Opc == ISD::INTRINSIC_WO_CHAIN ||
19695           Opc == ISD::INTRINSIC_W_CHAIN ||
19696           Opc == ISD::INTRINSIC_VOID) &&
19697          "Should use MaskedValueIsZero if you don't know whether Op"
19698          " is a target node!");
19699
19700   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19701   switch (Opc) {
19702   default: break;
19703   case X86ISD::ADD:
19704   case X86ISD::SUB:
19705   case X86ISD::ADC:
19706   case X86ISD::SBB:
19707   case X86ISD::SMUL:
19708   case X86ISD::UMUL:
19709   case X86ISD::INC:
19710   case X86ISD::DEC:
19711   case X86ISD::OR:
19712   case X86ISD::XOR:
19713   case X86ISD::AND:
19714     // These nodes' second result is a boolean.
19715     if (Op.getResNo() == 0)
19716       break;
19717     // Fallthrough
19718   case X86ISD::SETCC:
19719     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19720     break;
19721   case ISD::INTRINSIC_WO_CHAIN: {
19722     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19723     unsigned NumLoBits = 0;
19724     switch (IntId) {
19725     default: break;
19726     case Intrinsic::x86_sse_movmsk_ps:
19727     case Intrinsic::x86_avx_movmsk_ps_256:
19728     case Intrinsic::x86_sse2_movmsk_pd:
19729     case Intrinsic::x86_avx_movmsk_pd_256:
19730     case Intrinsic::x86_mmx_pmovmskb:
19731     case Intrinsic::x86_sse2_pmovmskb_128:
19732     case Intrinsic::x86_avx2_pmovmskb: {
19733       // High bits of movmskp{s|d}, pmovmskb are known zero.
19734       switch (IntId) {
19735         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19736         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19737         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19738         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19739         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19740         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19741         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19742         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19743       }
19744       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19745       break;
19746     }
19747     }
19748     break;
19749   }
19750   }
19751 }
19752
19753 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19754   SDValue Op,
19755   const SelectionDAG &,
19756   unsigned Depth) const {
19757   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19758   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19759     return Op.getValueType().getScalarType().getSizeInBits();
19760
19761   // Fallback case.
19762   return 1;
19763 }
19764
19765 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19766 /// node is a GlobalAddress + offset.
19767 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19768                                        const GlobalValue* &GA,
19769                                        int64_t &Offset) const {
19770   if (N->getOpcode() == X86ISD::Wrapper) {
19771     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19772       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19773       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19774       return true;
19775     }
19776   }
19777   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19778 }
19779
19780 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19781 /// same as extracting the high 128-bit part of 256-bit vector and then
19782 /// inserting the result into the low part of a new 256-bit vector
19783 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19784   EVT VT = SVOp->getValueType(0);
19785   unsigned NumElems = VT.getVectorNumElements();
19786
19787   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19788   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19789     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19790         SVOp->getMaskElt(j) >= 0)
19791       return false;
19792
19793   return true;
19794 }
19795
19796 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19797 /// same as extracting the low 128-bit part of 256-bit vector and then
19798 /// inserting the result into the high part of a new 256-bit vector
19799 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19800   EVT VT = SVOp->getValueType(0);
19801   unsigned NumElems = VT.getVectorNumElements();
19802
19803   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19804   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19805     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19806         SVOp->getMaskElt(j) >= 0)
19807       return false;
19808
19809   return true;
19810 }
19811
19812 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19813 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19814                                         TargetLowering::DAGCombinerInfo &DCI,
19815                                         const X86Subtarget* Subtarget) {
19816   SDLoc dl(N);
19817   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19818   SDValue V1 = SVOp->getOperand(0);
19819   SDValue V2 = SVOp->getOperand(1);
19820   EVT VT = SVOp->getValueType(0);
19821   unsigned NumElems = VT.getVectorNumElements();
19822
19823   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19824       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19825     //
19826     //                   0,0,0,...
19827     //                      |
19828     //    V      UNDEF    BUILD_VECTOR    UNDEF
19829     //     \      /           \           /
19830     //  CONCAT_VECTOR         CONCAT_VECTOR
19831     //         \                  /
19832     //          \                /
19833     //          RESULT: V + zero extended
19834     //
19835     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19836         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19837         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19838       return SDValue();
19839
19840     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19841       return SDValue();
19842
19843     // To match the shuffle mask, the first half of the mask should
19844     // be exactly the first vector, and all the rest a splat with the
19845     // first element of the second one.
19846     for (unsigned i = 0; i != NumElems/2; ++i)
19847       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19848           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19849         return SDValue();
19850
19851     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19852     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19853       if (Ld->hasNUsesOfValue(1, 0)) {
19854         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19855         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19856         SDValue ResNode =
19857           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19858                                   Ld->getMemoryVT(),
19859                                   Ld->getPointerInfo(),
19860                                   Ld->getAlignment(),
19861                                   false/*isVolatile*/, true/*ReadMem*/,
19862                                   false/*WriteMem*/);
19863
19864         // Make sure the newly-created LOAD is in the same position as Ld in
19865         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19866         // and update uses of Ld's output chain to use the TokenFactor.
19867         if (Ld->hasAnyUseOfValue(1)) {
19868           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19869                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19870           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19871           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19872                                  SDValue(ResNode.getNode(), 1));
19873         }
19874
19875         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19876       }
19877     }
19878
19879     // Emit a zeroed vector and insert the desired subvector on its
19880     // first half.
19881     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19882     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19883     return DCI.CombineTo(N, InsV);
19884   }
19885
19886   //===--------------------------------------------------------------------===//
19887   // Combine some shuffles into subvector extracts and inserts:
19888   //
19889
19890   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19891   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19892     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19893     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19894     return DCI.CombineTo(N, InsV);
19895   }
19896
19897   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19898   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19899     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19900     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19901     return DCI.CombineTo(N, InsV);
19902   }
19903
19904   return SDValue();
19905 }
19906
19907 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19908 /// possible.
19909 ///
19910 /// This is the leaf of the recursive combinine below. When we have found some
19911 /// chain of single-use x86 shuffle instructions and accumulated the combined
19912 /// shuffle mask represented by them, this will try to pattern match that mask
19913 /// into either a single instruction if there is a special purpose instruction
19914 /// for this operation, or into a PSHUFB instruction which is a fully general
19915 /// instruction but should only be used to replace chains over a certain depth.
19916 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19917                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19918                                    TargetLowering::DAGCombinerInfo &DCI,
19919                                    const X86Subtarget *Subtarget) {
19920   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19921
19922   // Find the operand that enters the chain. Note that multiple uses are OK
19923   // here, we're not going to remove the operand we find.
19924   SDValue Input = Op.getOperand(0);
19925   while (Input.getOpcode() == ISD::BITCAST)
19926     Input = Input.getOperand(0);
19927
19928   MVT VT = Input.getSimpleValueType();
19929   MVT RootVT = Root.getSimpleValueType();
19930   SDLoc DL(Root);
19931
19932   // Just remove no-op shuffle masks.
19933   if (Mask.size() == 1) {
19934     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19935                   /*AddTo*/ true);
19936     return true;
19937   }
19938
19939   // Use the float domain if the operand type is a floating point type.
19940   bool FloatDomain = VT.isFloatingPoint();
19941
19942   // For floating point shuffles, we don't have free copies in the shuffle
19943   // instructions or the ability to load as part of the instruction, so
19944   // canonicalize their shuffles to UNPCK or MOV variants.
19945   //
19946   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19947   // vectors because it can have a load folded into it that UNPCK cannot. This
19948   // doesn't preclude something switching to the shorter encoding post-RA.
19949   //
19950   // FIXME: Should teach these routines about AVX vector widths.
19951   if (FloatDomain && VT.getSizeInBits() == 128) {
19952     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19953       bool Lo = Mask.equals({0, 0});
19954       unsigned Shuffle;
19955       MVT ShuffleVT;
19956       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19957       // is no slower than UNPCKLPD but has the option to fold the input operand
19958       // into even an unaligned memory load.
19959       if (Lo && Subtarget->hasSSE3()) {
19960         Shuffle = X86ISD::MOVDDUP;
19961         ShuffleVT = MVT::v2f64;
19962       } else {
19963         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19964         // than the UNPCK variants.
19965         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19966         ShuffleVT = MVT::v4f32;
19967       }
19968       if (Depth == 1 && Root->getOpcode() == Shuffle)
19969         return false; // Nothing to do!
19970       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19971       DCI.AddToWorklist(Op.getNode());
19972       if (Shuffle == X86ISD::MOVDDUP)
19973         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19974       else
19975         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19976       DCI.AddToWorklist(Op.getNode());
19977       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19978                     /*AddTo*/ true);
19979       return true;
19980     }
19981     if (Subtarget->hasSSE3() &&
19982         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19983       bool Lo = Mask.equals({0, 0, 2, 2});
19984       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19985       MVT ShuffleVT = MVT::v4f32;
19986       if (Depth == 1 && Root->getOpcode() == Shuffle)
19987         return false; // Nothing to do!
19988       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19989       DCI.AddToWorklist(Op.getNode());
19990       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19991       DCI.AddToWorklist(Op.getNode());
19992       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19993                     /*AddTo*/ true);
19994       return true;
19995     }
19996     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19997       bool Lo = Mask.equals({0, 0, 1, 1});
19998       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19999       MVT ShuffleVT = MVT::v4f32;
20000       if (Depth == 1 && Root->getOpcode() == Shuffle)
20001         return false; // Nothing to do!
20002       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20003       DCI.AddToWorklist(Op.getNode());
20004       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20005       DCI.AddToWorklist(Op.getNode());
20006       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20007                     /*AddTo*/ true);
20008       return true;
20009     }
20010   }
20011
20012   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20013   // variants as none of these have single-instruction variants that are
20014   // superior to the UNPCK formulation.
20015   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20016       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20017        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20018        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20019        Mask.equals(
20020            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20021     bool Lo = Mask[0] == 0;
20022     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20023     if (Depth == 1 && Root->getOpcode() == Shuffle)
20024       return false; // Nothing to do!
20025     MVT ShuffleVT;
20026     switch (Mask.size()) {
20027     case 8:
20028       ShuffleVT = MVT::v8i16;
20029       break;
20030     case 16:
20031       ShuffleVT = MVT::v16i8;
20032       break;
20033     default:
20034       llvm_unreachable("Impossible mask size!");
20035     };
20036     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20037     DCI.AddToWorklist(Op.getNode());
20038     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20039     DCI.AddToWorklist(Op.getNode());
20040     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20041                   /*AddTo*/ true);
20042     return true;
20043   }
20044
20045   // Don't try to re-form single instruction chains under any circumstances now
20046   // that we've done encoding canonicalization for them.
20047   if (Depth < 2)
20048     return false;
20049
20050   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20051   // can replace them with a single PSHUFB instruction profitably. Intel's
20052   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20053   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20054   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20055     SmallVector<SDValue, 16> PSHUFBMask;
20056     int NumBytes = VT.getSizeInBits() / 8;
20057     int Ratio = NumBytes / Mask.size();
20058     for (int i = 0; i < NumBytes; ++i) {
20059       if (Mask[i / Ratio] == SM_SentinelUndef) {
20060         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20061         continue;
20062       }
20063       int M = Mask[i / Ratio] != SM_SentinelZero
20064                   ? Ratio * Mask[i / Ratio] + i % Ratio
20065                   : 255;
20066       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20067     }
20068     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20069     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20070     DCI.AddToWorklist(Op.getNode());
20071     SDValue PSHUFBMaskOp =
20072         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20073     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20074     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20075     DCI.AddToWorklist(Op.getNode());
20076     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20077                   /*AddTo*/ true);
20078     return true;
20079   }
20080
20081   // Failed to find any combines.
20082   return false;
20083 }
20084
20085 /// \brief Fully generic combining of x86 shuffle instructions.
20086 ///
20087 /// This should be the last combine run over the x86 shuffle instructions. Once
20088 /// they have been fully optimized, this will recursively consider all chains
20089 /// of single-use shuffle instructions, build a generic model of the cumulative
20090 /// shuffle operation, and check for simpler instructions which implement this
20091 /// operation. We use this primarily for two purposes:
20092 ///
20093 /// 1) Collapse generic shuffles to specialized single instructions when
20094 ///    equivalent. In most cases, this is just an encoding size win, but
20095 ///    sometimes we will collapse multiple generic shuffles into a single
20096 ///    special-purpose shuffle.
20097 /// 2) Look for sequences of shuffle instructions with 3 or more total
20098 ///    instructions, and replace them with the slightly more expensive SSSE3
20099 ///    PSHUFB instruction if available. We do this as the last combining step
20100 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20101 ///    a suitable short sequence of other instructions. The PHUFB will either
20102 ///    use a register or have to read from memory and so is slightly (but only
20103 ///    slightly) more expensive than the other shuffle instructions.
20104 ///
20105 /// Because this is inherently a quadratic operation (for each shuffle in
20106 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20107 /// This should never be an issue in practice as the shuffle lowering doesn't
20108 /// produce sequences of more than 8 instructions.
20109 ///
20110 /// FIXME: We will currently miss some cases where the redundant shuffling
20111 /// would simplify under the threshold for PSHUFB formation because of
20112 /// combine-ordering. To fix this, we should do the redundant instruction
20113 /// combining in this recursive walk.
20114 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20115                                           ArrayRef<int> RootMask,
20116                                           int Depth, bool HasPSHUFB,
20117                                           SelectionDAG &DAG,
20118                                           TargetLowering::DAGCombinerInfo &DCI,
20119                                           const X86Subtarget *Subtarget) {
20120   // Bound the depth of our recursive combine because this is ultimately
20121   // quadratic in nature.
20122   if (Depth > 8)
20123     return false;
20124
20125   // Directly rip through bitcasts to find the underlying operand.
20126   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20127     Op = Op.getOperand(0);
20128
20129   MVT VT = Op.getSimpleValueType();
20130   if (!VT.isVector())
20131     return false; // Bail if we hit a non-vector.
20132
20133   assert(Root.getSimpleValueType().isVector() &&
20134          "Shuffles operate on vector types!");
20135   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20136          "Can only combine shuffles of the same vector register size.");
20137
20138   if (!isTargetShuffle(Op.getOpcode()))
20139     return false;
20140   SmallVector<int, 16> OpMask;
20141   bool IsUnary;
20142   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20143   // We only can combine unary shuffles which we can decode the mask for.
20144   if (!HaveMask || !IsUnary)
20145     return false;
20146
20147   assert(VT.getVectorNumElements() == OpMask.size() &&
20148          "Different mask size from vector size!");
20149   assert(((RootMask.size() > OpMask.size() &&
20150            RootMask.size() % OpMask.size() == 0) ||
20151           (OpMask.size() > RootMask.size() &&
20152            OpMask.size() % RootMask.size() == 0) ||
20153           OpMask.size() == RootMask.size()) &&
20154          "The smaller number of elements must divide the larger.");
20155   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20156   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20157   assert(((RootRatio == 1 && OpRatio == 1) ||
20158           (RootRatio == 1) != (OpRatio == 1)) &&
20159          "Must not have a ratio for both incoming and op masks!");
20160
20161   SmallVector<int, 16> Mask;
20162   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20163
20164   // Merge this shuffle operation's mask into our accumulated mask. Note that
20165   // this shuffle's mask will be the first applied to the input, followed by the
20166   // root mask to get us all the way to the root value arrangement. The reason
20167   // for this order is that we are recursing up the operation chain.
20168   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20169     int RootIdx = i / RootRatio;
20170     if (RootMask[RootIdx] < 0) {
20171       // This is a zero or undef lane, we're done.
20172       Mask.push_back(RootMask[RootIdx]);
20173       continue;
20174     }
20175
20176     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20177     int OpIdx = RootMaskedIdx / OpRatio;
20178     if (OpMask[OpIdx] < 0) {
20179       // The incoming lanes are zero or undef, it doesn't matter which ones we
20180       // are using.
20181       Mask.push_back(OpMask[OpIdx]);
20182       continue;
20183     }
20184
20185     // Ok, we have non-zero lanes, map them through.
20186     Mask.push_back(OpMask[OpIdx] * OpRatio +
20187                    RootMaskedIdx % OpRatio);
20188   }
20189
20190   // See if we can recurse into the operand to combine more things.
20191   switch (Op.getOpcode()) {
20192     case X86ISD::PSHUFB:
20193       HasPSHUFB = true;
20194     case X86ISD::PSHUFD:
20195     case X86ISD::PSHUFHW:
20196     case X86ISD::PSHUFLW:
20197       if (Op.getOperand(0).hasOneUse() &&
20198           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20199                                         HasPSHUFB, DAG, DCI, Subtarget))
20200         return true;
20201       break;
20202
20203     case X86ISD::UNPCKL:
20204     case X86ISD::UNPCKH:
20205       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20206       // We can't check for single use, we have to check that this shuffle is the only user.
20207       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20208           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20209                                         HasPSHUFB, DAG, DCI, Subtarget))
20210           return true;
20211       break;
20212   }
20213
20214   // Minor canonicalization of the accumulated shuffle mask to make it easier
20215   // to match below. All this does is detect masks with squential pairs of
20216   // elements, and shrink them to the half-width mask. It does this in a loop
20217   // so it will reduce the size of the mask to the minimal width mask which
20218   // performs an equivalent shuffle.
20219   SmallVector<int, 16> WidenedMask;
20220   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20221     Mask = std::move(WidenedMask);
20222     WidenedMask.clear();
20223   }
20224
20225   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20226                                 Subtarget);
20227 }
20228
20229 /// \brief Get the PSHUF-style mask from PSHUF node.
20230 ///
20231 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20232 /// PSHUF-style masks that can be reused with such instructions.
20233 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20234   MVT VT = N.getSimpleValueType();
20235   SmallVector<int, 4> Mask;
20236   bool IsUnary;
20237   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20238   (void)HaveMask;
20239   assert(HaveMask);
20240
20241   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20242   // matter. Check that the upper masks are repeats and remove them.
20243   if (VT.getSizeInBits() > 128) {
20244     int LaneElts = 128 / VT.getScalarSizeInBits();
20245 #ifndef NDEBUG
20246     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20247       for (int j = 0; j < LaneElts; ++j)
20248         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20249                "Mask doesn't repeat in high 128-bit lanes!");
20250 #endif
20251     Mask.resize(LaneElts);
20252   }
20253
20254   switch (N.getOpcode()) {
20255   case X86ISD::PSHUFD:
20256     return Mask;
20257   case X86ISD::PSHUFLW:
20258     Mask.resize(4);
20259     return Mask;
20260   case X86ISD::PSHUFHW:
20261     Mask.erase(Mask.begin(), Mask.begin() + 4);
20262     for (int &M : Mask)
20263       M -= 4;
20264     return Mask;
20265   default:
20266     llvm_unreachable("No valid shuffle instruction found!");
20267   }
20268 }
20269
20270 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20271 ///
20272 /// We walk up the chain and look for a combinable shuffle, skipping over
20273 /// shuffles that we could hoist this shuffle's transformation past without
20274 /// altering anything.
20275 static SDValue
20276 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20277                              SelectionDAG &DAG,
20278                              TargetLowering::DAGCombinerInfo &DCI) {
20279   assert(N.getOpcode() == X86ISD::PSHUFD &&
20280          "Called with something other than an x86 128-bit half shuffle!");
20281   SDLoc DL(N);
20282
20283   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20284   // of the shuffles in the chain so that we can form a fresh chain to replace
20285   // this one.
20286   SmallVector<SDValue, 8> Chain;
20287   SDValue V = N.getOperand(0);
20288   for (; V.hasOneUse(); V = V.getOperand(0)) {
20289     switch (V.getOpcode()) {
20290     default:
20291       return SDValue(); // Nothing combined!
20292
20293     case ISD::BITCAST:
20294       // Skip bitcasts as we always know the type for the target specific
20295       // instructions.
20296       continue;
20297
20298     case X86ISD::PSHUFD:
20299       // Found another dword shuffle.
20300       break;
20301
20302     case X86ISD::PSHUFLW:
20303       // Check that the low words (being shuffled) are the identity in the
20304       // dword shuffle, and the high words are self-contained.
20305       if (Mask[0] != 0 || Mask[1] != 1 ||
20306           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20307         return SDValue();
20308
20309       Chain.push_back(V);
20310       continue;
20311
20312     case X86ISD::PSHUFHW:
20313       // Check that the high words (being shuffled) are the identity in the
20314       // dword shuffle, and the low words are self-contained.
20315       if (Mask[2] != 2 || Mask[3] != 3 ||
20316           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20317         return SDValue();
20318
20319       Chain.push_back(V);
20320       continue;
20321
20322     case X86ISD::UNPCKL:
20323     case X86ISD::UNPCKH:
20324       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20325       // shuffle into a preceding word shuffle.
20326       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20327           V.getSimpleValueType().getScalarType() != MVT::i16)
20328         return SDValue();
20329
20330       // Search for a half-shuffle which we can combine with.
20331       unsigned CombineOp =
20332           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20333       if (V.getOperand(0) != V.getOperand(1) ||
20334           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20335         return SDValue();
20336       Chain.push_back(V);
20337       V = V.getOperand(0);
20338       do {
20339         switch (V.getOpcode()) {
20340         default:
20341           return SDValue(); // Nothing to combine.
20342
20343         case X86ISD::PSHUFLW:
20344         case X86ISD::PSHUFHW:
20345           if (V.getOpcode() == CombineOp)
20346             break;
20347
20348           Chain.push_back(V);
20349
20350           // Fallthrough!
20351         case ISD::BITCAST:
20352           V = V.getOperand(0);
20353           continue;
20354         }
20355         break;
20356       } while (V.hasOneUse());
20357       break;
20358     }
20359     // Break out of the loop if we break out of the switch.
20360     break;
20361   }
20362
20363   if (!V.hasOneUse())
20364     // We fell out of the loop without finding a viable combining instruction.
20365     return SDValue();
20366
20367   // Merge this node's mask and our incoming mask.
20368   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20369   for (int &M : Mask)
20370     M = VMask[M];
20371   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20372                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20373
20374   // Rebuild the chain around this new shuffle.
20375   while (!Chain.empty()) {
20376     SDValue W = Chain.pop_back_val();
20377
20378     if (V.getValueType() != W.getOperand(0).getValueType())
20379       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20380
20381     switch (W.getOpcode()) {
20382     default:
20383       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20384
20385     case X86ISD::UNPCKL:
20386     case X86ISD::UNPCKH:
20387       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20388       break;
20389
20390     case X86ISD::PSHUFD:
20391     case X86ISD::PSHUFLW:
20392     case X86ISD::PSHUFHW:
20393       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20394       break;
20395     }
20396   }
20397   if (V.getValueType() != N.getValueType())
20398     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20399
20400   // Return the new chain to replace N.
20401   return V;
20402 }
20403
20404 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20405 ///
20406 /// We walk up the chain, skipping shuffles of the other half and looking
20407 /// through shuffles which switch halves trying to find a shuffle of the same
20408 /// pair of dwords.
20409 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20410                                         SelectionDAG &DAG,
20411                                         TargetLowering::DAGCombinerInfo &DCI) {
20412   assert(
20413       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20414       "Called with something other than an x86 128-bit half shuffle!");
20415   SDLoc DL(N);
20416   unsigned CombineOpcode = N.getOpcode();
20417
20418   // Walk up a single-use chain looking for a combinable shuffle.
20419   SDValue V = N.getOperand(0);
20420   for (; V.hasOneUse(); V = V.getOperand(0)) {
20421     switch (V.getOpcode()) {
20422     default:
20423       return false; // Nothing combined!
20424
20425     case ISD::BITCAST:
20426       // Skip bitcasts as we always know the type for the target specific
20427       // instructions.
20428       continue;
20429
20430     case X86ISD::PSHUFLW:
20431     case X86ISD::PSHUFHW:
20432       if (V.getOpcode() == CombineOpcode)
20433         break;
20434
20435       // Other-half shuffles are no-ops.
20436       continue;
20437     }
20438     // Break out of the loop if we break out of the switch.
20439     break;
20440   }
20441
20442   if (!V.hasOneUse())
20443     // We fell out of the loop without finding a viable combining instruction.
20444     return false;
20445
20446   // Combine away the bottom node as its shuffle will be accumulated into
20447   // a preceding shuffle.
20448   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20449
20450   // Record the old value.
20451   SDValue Old = V;
20452
20453   // Merge this node's mask and our incoming mask (adjusted to account for all
20454   // the pshufd instructions encountered).
20455   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20456   for (int &M : Mask)
20457     M = VMask[M];
20458   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20459                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20460
20461   // Check that the shuffles didn't cancel each other out. If not, we need to
20462   // combine to the new one.
20463   if (Old != V)
20464     // Replace the combinable shuffle with the combined one, updating all users
20465     // so that we re-evaluate the chain here.
20466     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20467
20468   return true;
20469 }
20470
20471 /// \brief Try to combine x86 target specific shuffles.
20472 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20473                                            TargetLowering::DAGCombinerInfo &DCI,
20474                                            const X86Subtarget *Subtarget) {
20475   SDLoc DL(N);
20476   MVT VT = N.getSimpleValueType();
20477   SmallVector<int, 4> Mask;
20478
20479   switch (N.getOpcode()) {
20480   case X86ISD::PSHUFD:
20481   case X86ISD::PSHUFLW:
20482   case X86ISD::PSHUFHW:
20483     Mask = getPSHUFShuffleMask(N);
20484     assert(Mask.size() == 4);
20485     break;
20486   default:
20487     return SDValue();
20488   }
20489
20490   // Nuke no-op shuffles that show up after combining.
20491   if (isNoopShuffleMask(Mask))
20492     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20493
20494   // Look for simplifications involving one or two shuffle instructions.
20495   SDValue V = N.getOperand(0);
20496   switch (N.getOpcode()) {
20497   default:
20498     break;
20499   case X86ISD::PSHUFLW:
20500   case X86ISD::PSHUFHW:
20501     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20502
20503     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20504       return SDValue(); // We combined away this shuffle, so we're done.
20505
20506     // See if this reduces to a PSHUFD which is no more expensive and can
20507     // combine with more operations. Note that it has to at least flip the
20508     // dwords as otherwise it would have been removed as a no-op.
20509     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20510       int DMask[] = {0, 1, 2, 3};
20511       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20512       DMask[DOffset + 0] = DOffset + 1;
20513       DMask[DOffset + 1] = DOffset + 0;
20514       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20515       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20516       DCI.AddToWorklist(V.getNode());
20517       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20518                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20519       DCI.AddToWorklist(V.getNode());
20520       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20521     }
20522
20523     // Look for shuffle patterns which can be implemented as a single unpack.
20524     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20525     // only works when we have a PSHUFD followed by two half-shuffles.
20526     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20527         (V.getOpcode() == X86ISD::PSHUFLW ||
20528          V.getOpcode() == X86ISD::PSHUFHW) &&
20529         V.getOpcode() != N.getOpcode() &&
20530         V.hasOneUse()) {
20531       SDValue D = V.getOperand(0);
20532       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20533         D = D.getOperand(0);
20534       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20535         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20536         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20537         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20538         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20539         int WordMask[8];
20540         for (int i = 0; i < 4; ++i) {
20541           WordMask[i + NOffset] = Mask[i] + NOffset;
20542           WordMask[i + VOffset] = VMask[i] + VOffset;
20543         }
20544         // Map the word mask through the DWord mask.
20545         int MappedMask[8];
20546         for (int i = 0; i < 8; ++i)
20547           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20548         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20549             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20550           // We can replace all three shuffles with an unpack.
20551           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20552           DCI.AddToWorklist(V.getNode());
20553           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20554                                                 : X86ISD::UNPCKH,
20555                              DL, VT, V, V);
20556         }
20557       }
20558     }
20559
20560     break;
20561
20562   case X86ISD::PSHUFD:
20563     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20564       return NewN;
20565
20566     break;
20567   }
20568
20569   return SDValue();
20570 }
20571
20572 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20573 ///
20574 /// We combine this directly on the abstract vector shuffle nodes so it is
20575 /// easier to generically match. We also insert dummy vector shuffle nodes for
20576 /// the operands which explicitly discard the lanes which are unused by this
20577 /// operation to try to flow through the rest of the combiner the fact that
20578 /// they're unused.
20579 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20580   SDLoc DL(N);
20581   EVT VT = N->getValueType(0);
20582
20583   // We only handle target-independent shuffles.
20584   // FIXME: It would be easy and harmless to use the target shuffle mask
20585   // extraction tool to support more.
20586   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20587     return SDValue();
20588
20589   auto *SVN = cast<ShuffleVectorSDNode>(N);
20590   ArrayRef<int> Mask = SVN->getMask();
20591   SDValue V1 = N->getOperand(0);
20592   SDValue V2 = N->getOperand(1);
20593
20594   // We require the first shuffle operand to be the SUB node, and the second to
20595   // be the ADD node.
20596   // FIXME: We should support the commuted patterns.
20597   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20598     return SDValue();
20599
20600   // If there are other uses of these operations we can't fold them.
20601   if (!V1->hasOneUse() || !V2->hasOneUse())
20602     return SDValue();
20603
20604   // Ensure that both operations have the same operands. Note that we can
20605   // commute the FADD operands.
20606   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20607   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20608       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20609     return SDValue();
20610
20611   // We're looking for blends between FADD and FSUB nodes. We insist on these
20612   // nodes being lined up in a specific expected pattern.
20613   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20614         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20615         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20616     return SDValue();
20617
20618   // Only specific types are legal at this point, assert so we notice if and
20619   // when these change.
20620   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20621           VT == MVT::v4f64) &&
20622          "Unknown vector type encountered!");
20623
20624   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20625 }
20626
20627 /// PerformShuffleCombine - Performs several different shuffle combines.
20628 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20629                                      TargetLowering::DAGCombinerInfo &DCI,
20630                                      const X86Subtarget *Subtarget) {
20631   SDLoc dl(N);
20632   SDValue N0 = N->getOperand(0);
20633   SDValue N1 = N->getOperand(1);
20634   EVT VT = N->getValueType(0);
20635
20636   // Don't create instructions with illegal types after legalize types has run.
20637   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20638   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20639     return SDValue();
20640
20641   // If we have legalized the vector types, look for blends of FADD and FSUB
20642   // nodes that we can fuse into an ADDSUB node.
20643   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20644     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20645       return AddSub;
20646
20647   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20648   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20649       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20650     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20651
20652   // During Type Legalization, when promoting illegal vector types,
20653   // the backend might introduce new shuffle dag nodes and bitcasts.
20654   //
20655   // This code performs the following transformation:
20656   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20657   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20658   //
20659   // We do this only if both the bitcast and the BINOP dag nodes have
20660   // one use. Also, perform this transformation only if the new binary
20661   // operation is legal. This is to avoid introducing dag nodes that
20662   // potentially need to be further expanded (or custom lowered) into a
20663   // less optimal sequence of dag nodes.
20664   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20665       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20666       N0.getOpcode() == ISD::BITCAST) {
20667     SDValue BC0 = N0.getOperand(0);
20668     EVT SVT = BC0.getValueType();
20669     unsigned Opcode = BC0.getOpcode();
20670     unsigned NumElts = VT.getVectorNumElements();
20671
20672     if (BC0.hasOneUse() && SVT.isVector() &&
20673         SVT.getVectorNumElements() * 2 == NumElts &&
20674         TLI.isOperationLegal(Opcode, VT)) {
20675       bool CanFold = false;
20676       switch (Opcode) {
20677       default : break;
20678       case ISD::ADD :
20679       case ISD::FADD :
20680       case ISD::SUB :
20681       case ISD::FSUB :
20682       case ISD::MUL :
20683       case ISD::FMUL :
20684         CanFold = true;
20685       }
20686
20687       unsigned SVTNumElts = SVT.getVectorNumElements();
20688       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20689       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20690         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20691       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20692         CanFold = SVOp->getMaskElt(i) < 0;
20693
20694       if (CanFold) {
20695         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20696         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20697         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20698         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20699       }
20700     }
20701   }
20702
20703   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20704   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20705   // consecutive, non-overlapping, and in the right order.
20706   SmallVector<SDValue, 16> Elts;
20707   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20708     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20709
20710   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20711   if (LD.getNode())
20712     return LD;
20713
20714   if (isTargetShuffle(N->getOpcode())) {
20715     SDValue Shuffle =
20716         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20717     if (Shuffle.getNode())
20718       return Shuffle;
20719
20720     // Try recursively combining arbitrary sequences of x86 shuffle
20721     // instructions into higher-order shuffles. We do this after combining
20722     // specific PSHUF instruction sequences into their minimal form so that we
20723     // can evaluate how many specialized shuffle instructions are involved in
20724     // a particular chain.
20725     SmallVector<int, 1> NonceMask; // Just a placeholder.
20726     NonceMask.push_back(0);
20727     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20728                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20729                                       DCI, Subtarget))
20730       return SDValue(); // This routine will use CombineTo to replace N.
20731   }
20732
20733   return SDValue();
20734 }
20735
20736 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20737 /// specific shuffle of a load can be folded into a single element load.
20738 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20739 /// shuffles have been custom lowered so we need to handle those here.
20740 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20741                                          TargetLowering::DAGCombinerInfo &DCI) {
20742   if (DCI.isBeforeLegalizeOps())
20743     return SDValue();
20744
20745   SDValue InVec = N->getOperand(0);
20746   SDValue EltNo = N->getOperand(1);
20747
20748   if (!isa<ConstantSDNode>(EltNo))
20749     return SDValue();
20750
20751   EVT OriginalVT = InVec.getValueType();
20752
20753   if (InVec.getOpcode() == ISD::BITCAST) {
20754     // Don't duplicate a load with other uses.
20755     if (!InVec.hasOneUse())
20756       return SDValue();
20757     EVT BCVT = InVec.getOperand(0).getValueType();
20758     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20759       return SDValue();
20760     InVec = InVec.getOperand(0);
20761   }
20762
20763   EVT CurrentVT = InVec.getValueType();
20764
20765   if (!isTargetShuffle(InVec.getOpcode()))
20766     return SDValue();
20767
20768   // Don't duplicate a load with other uses.
20769   if (!InVec.hasOneUse())
20770     return SDValue();
20771
20772   SmallVector<int, 16> ShuffleMask;
20773   bool UnaryShuffle;
20774   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20775                             ShuffleMask, UnaryShuffle))
20776     return SDValue();
20777
20778   // Select the input vector, guarding against out of range extract vector.
20779   unsigned NumElems = CurrentVT.getVectorNumElements();
20780   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20781   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20782   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20783                                          : InVec.getOperand(1);
20784
20785   // If inputs to shuffle are the same for both ops, then allow 2 uses
20786   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20787                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20788
20789   if (LdNode.getOpcode() == ISD::BITCAST) {
20790     // Don't duplicate a load with other uses.
20791     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20792       return SDValue();
20793
20794     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20795     LdNode = LdNode.getOperand(0);
20796   }
20797
20798   if (!ISD::isNormalLoad(LdNode.getNode()))
20799     return SDValue();
20800
20801   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20802
20803   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20804     return SDValue();
20805
20806   EVT EltVT = N->getValueType(0);
20807   // If there's a bitcast before the shuffle, check if the load type and
20808   // alignment is valid.
20809   unsigned Align = LN0->getAlignment();
20810   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20811   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20812       EltVT.getTypeForEVT(*DAG.getContext()));
20813
20814   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20815     return SDValue();
20816
20817   // All checks match so transform back to vector_shuffle so that DAG combiner
20818   // can finish the job
20819   SDLoc dl(N);
20820
20821   // Create shuffle node taking into account the case that its a unary shuffle
20822   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20823                                    : InVec.getOperand(1);
20824   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20825                                  InVec.getOperand(0), Shuffle,
20826                                  &ShuffleMask[0]);
20827   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20828   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20829                      EltNo);
20830 }
20831
20832 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20833 /// special and don't usually play with other vector types, it's better to
20834 /// handle them early to be sure we emit efficient code by avoiding
20835 /// store-load conversions.
20836 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20837   if (N->getValueType(0) != MVT::x86mmx ||
20838       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20839       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20840     return SDValue();
20841
20842   SDValue V = N->getOperand(0);
20843   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20844   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20845     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20846                        N->getValueType(0), V.getOperand(0));
20847
20848   return SDValue();
20849 }
20850
20851 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20852 /// generation and convert it from being a bunch of shuffles and extracts
20853 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20854 /// storing the value and loading scalars back, while for x64 we should
20855 /// use 64-bit extracts and shifts.
20856 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20857                                          TargetLowering::DAGCombinerInfo &DCI) {
20858   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20859   if (NewOp.getNode())
20860     return NewOp;
20861
20862   SDValue InputVector = N->getOperand(0);
20863
20864   // Detect mmx to i32 conversion through a v2i32 elt extract.
20865   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20866       N->getValueType(0) == MVT::i32 &&
20867       InputVector.getValueType() == MVT::v2i32) {
20868
20869     // The bitcast source is a direct mmx result.
20870     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20871     if (MMXSrc.getValueType() == MVT::x86mmx)
20872       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20873                          N->getValueType(0),
20874                          InputVector.getNode()->getOperand(0));
20875
20876     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20877     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20878     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20879         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20880         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20881         MMXSrcOp.getValueType() == MVT::v1i64 &&
20882         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20883       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20884                          N->getValueType(0),
20885                          MMXSrcOp.getOperand(0));
20886   }
20887
20888   // Only operate on vectors of 4 elements, where the alternative shuffling
20889   // gets to be more expensive.
20890   if (InputVector.getValueType() != MVT::v4i32)
20891     return SDValue();
20892
20893   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20894   // single use which is a sign-extend or zero-extend, and all elements are
20895   // used.
20896   SmallVector<SDNode *, 4> Uses;
20897   unsigned ExtractedElements = 0;
20898   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20899        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20900     if (UI.getUse().getResNo() != InputVector.getResNo())
20901       return SDValue();
20902
20903     SDNode *Extract = *UI;
20904     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20905       return SDValue();
20906
20907     if (Extract->getValueType(0) != MVT::i32)
20908       return SDValue();
20909     if (!Extract->hasOneUse())
20910       return SDValue();
20911     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20912         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20913       return SDValue();
20914     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20915       return SDValue();
20916
20917     // Record which element was extracted.
20918     ExtractedElements |=
20919       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20920
20921     Uses.push_back(Extract);
20922   }
20923
20924   // If not all the elements were used, this may not be worthwhile.
20925   if (ExtractedElements != 15)
20926     return SDValue();
20927
20928   // Ok, we've now decided to do the transformation.
20929   // If 64-bit shifts are legal, use the extract-shift sequence,
20930   // otherwise bounce the vector off the cache.
20931   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20932   SDValue Vals[4];
20933   SDLoc dl(InputVector);
20934
20935   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20936     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20937     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20938     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20939       DAG.getConstant(0, dl, VecIdxTy));
20940     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20941       DAG.getConstant(1, dl, VecIdxTy));
20942
20943     SDValue ShAmt = DAG.getConstant(32, dl,
20944       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20945     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20946     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20947       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20948     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20949     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20950       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20951   } else {
20952     // Store the value to a temporary stack slot.
20953     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20954     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20955       MachinePointerInfo(), false, false, 0);
20956
20957     EVT ElementType = InputVector.getValueType().getVectorElementType();
20958     unsigned EltSize = ElementType.getSizeInBits() / 8;
20959
20960     // Replace each use (extract) with a load of the appropriate element.
20961     for (unsigned i = 0; i < 4; ++i) {
20962       uint64_t Offset = EltSize * i;
20963       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
20964
20965       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20966                                        StackPtr, OffsetVal);
20967
20968       // Load the scalar.
20969       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20970                             ScalarAddr, MachinePointerInfo(),
20971                             false, false, false, 0);
20972
20973     }
20974   }
20975
20976   // Replace the extracts
20977   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20978     UE = Uses.end(); UI != UE; ++UI) {
20979     SDNode *Extract = *UI;
20980
20981     SDValue Idx = Extract->getOperand(1);
20982     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20983     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20984   }
20985
20986   // The replacement was made in place; don't return anything.
20987   return SDValue();
20988 }
20989
20990 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20991 static std::pair<unsigned, bool>
20992 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20993                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20994   if (!VT.isVector())
20995     return std::make_pair(0, false);
20996
20997   bool NeedSplit = false;
20998   switch (VT.getSimpleVT().SimpleTy) {
20999   default: return std::make_pair(0, false);
21000   case MVT::v4i64:
21001   case MVT::v2i64:
21002     if (!Subtarget->hasVLX())
21003       return std::make_pair(0, false);
21004     break;
21005   case MVT::v64i8:
21006   case MVT::v32i16:
21007     if (!Subtarget->hasBWI())
21008       return std::make_pair(0, false);
21009     break;
21010   case MVT::v16i32:
21011   case MVT::v8i64:
21012     if (!Subtarget->hasAVX512())
21013       return std::make_pair(0, false);
21014     break;
21015   case MVT::v32i8:
21016   case MVT::v16i16:
21017   case MVT::v8i32:
21018     if (!Subtarget->hasAVX2())
21019       NeedSplit = true;
21020     if (!Subtarget->hasAVX())
21021       return std::make_pair(0, false);
21022     break;
21023   case MVT::v16i8:
21024   case MVT::v8i16:
21025   case MVT::v4i32:
21026     if (!Subtarget->hasSSE2())
21027       return std::make_pair(0, false);
21028   }
21029
21030   // SSE2 has only a small subset of the operations.
21031   bool hasUnsigned = Subtarget->hasSSE41() ||
21032                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21033   bool hasSigned = Subtarget->hasSSE41() ||
21034                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21035
21036   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21037
21038   unsigned Opc = 0;
21039   // Check for x CC y ? x : y.
21040   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21041       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21042     switch (CC) {
21043     default: break;
21044     case ISD::SETULT:
21045     case ISD::SETULE:
21046       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21047     case ISD::SETUGT:
21048     case ISD::SETUGE:
21049       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21050     case ISD::SETLT:
21051     case ISD::SETLE:
21052       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21053     case ISD::SETGT:
21054     case ISD::SETGE:
21055       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21056     }
21057   // Check for x CC y ? y : x -- a min/max with reversed arms.
21058   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21059              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21060     switch (CC) {
21061     default: break;
21062     case ISD::SETULT:
21063     case ISD::SETULE:
21064       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21065     case ISD::SETUGT:
21066     case ISD::SETUGE:
21067       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21068     case ISD::SETLT:
21069     case ISD::SETLE:
21070       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21071     case ISD::SETGT:
21072     case ISD::SETGE:
21073       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21074     }
21075   }
21076
21077   return std::make_pair(Opc, NeedSplit);
21078 }
21079
21080 static SDValue
21081 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21082                                       const X86Subtarget *Subtarget) {
21083   SDLoc dl(N);
21084   SDValue Cond = N->getOperand(0);
21085   SDValue LHS = N->getOperand(1);
21086   SDValue RHS = N->getOperand(2);
21087
21088   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21089     SDValue CondSrc = Cond->getOperand(0);
21090     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21091       Cond = CondSrc->getOperand(0);
21092   }
21093
21094   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21095     return SDValue();
21096
21097   // A vselect where all conditions and data are constants can be optimized into
21098   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21099   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21100       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21101     return SDValue();
21102
21103   unsigned MaskValue = 0;
21104   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21105     return SDValue();
21106
21107   MVT VT = N->getSimpleValueType(0);
21108   unsigned NumElems = VT.getVectorNumElements();
21109   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21110   for (unsigned i = 0; i < NumElems; ++i) {
21111     // Be sure we emit undef where we can.
21112     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21113       ShuffleMask[i] = -1;
21114     else
21115       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21116   }
21117
21118   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21119   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21120     return SDValue();
21121   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21122 }
21123
21124 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21125 /// nodes.
21126 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21127                                     TargetLowering::DAGCombinerInfo &DCI,
21128                                     const X86Subtarget *Subtarget) {
21129   SDLoc DL(N);
21130   SDValue Cond = N->getOperand(0);
21131   // Get the LHS/RHS of the select.
21132   SDValue LHS = N->getOperand(1);
21133   SDValue RHS = N->getOperand(2);
21134   EVT VT = LHS.getValueType();
21135   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21136
21137   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21138   // instructions match the semantics of the common C idiom x<y?x:y but not
21139   // x<=y?x:y, because of how they handle negative zero (which can be
21140   // ignored in unsafe-math mode).
21141   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21142   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21143       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21144       (Subtarget->hasSSE2() ||
21145        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21146     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21147
21148     unsigned Opcode = 0;
21149     // Check for x CC y ? x : y.
21150     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21151         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21152       switch (CC) {
21153       default: break;
21154       case ISD::SETULT:
21155         // Converting this to a min would handle NaNs incorrectly, and swapping
21156         // the operands would cause it to handle comparisons between positive
21157         // and negative zero incorrectly.
21158         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21159           if (!DAG.getTarget().Options.UnsafeFPMath &&
21160               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21161             break;
21162           std::swap(LHS, RHS);
21163         }
21164         Opcode = X86ISD::FMIN;
21165         break;
21166       case ISD::SETOLE:
21167         // Converting this to a min would handle comparisons between positive
21168         // and negative zero incorrectly.
21169         if (!DAG.getTarget().Options.UnsafeFPMath &&
21170             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21171           break;
21172         Opcode = X86ISD::FMIN;
21173         break;
21174       case ISD::SETULE:
21175         // Converting this to a min would handle both negative zeros and NaNs
21176         // incorrectly, but we can swap the operands to fix both.
21177         std::swap(LHS, RHS);
21178       case ISD::SETOLT:
21179       case ISD::SETLT:
21180       case ISD::SETLE:
21181         Opcode = X86ISD::FMIN;
21182         break;
21183
21184       case ISD::SETOGE:
21185         // Converting this to a max would handle comparisons between positive
21186         // and negative zero incorrectly.
21187         if (!DAG.getTarget().Options.UnsafeFPMath &&
21188             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21189           break;
21190         Opcode = X86ISD::FMAX;
21191         break;
21192       case ISD::SETUGT:
21193         // Converting this to a max would handle NaNs incorrectly, and swapping
21194         // the operands would cause it to handle comparisons between positive
21195         // and negative zero incorrectly.
21196         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21197           if (!DAG.getTarget().Options.UnsafeFPMath &&
21198               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21199             break;
21200           std::swap(LHS, RHS);
21201         }
21202         Opcode = X86ISD::FMAX;
21203         break;
21204       case ISD::SETUGE:
21205         // Converting this to a max would handle both negative zeros and NaNs
21206         // incorrectly, but we can swap the operands to fix both.
21207         std::swap(LHS, RHS);
21208       case ISD::SETOGT:
21209       case ISD::SETGT:
21210       case ISD::SETGE:
21211         Opcode = X86ISD::FMAX;
21212         break;
21213       }
21214     // Check for x CC y ? y : x -- a min/max with reversed arms.
21215     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21216                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21217       switch (CC) {
21218       default: break;
21219       case ISD::SETOGE:
21220         // Converting this to a min would handle comparisons between positive
21221         // and negative zero incorrectly, and swapping the operands would
21222         // cause it to handle NaNs incorrectly.
21223         if (!DAG.getTarget().Options.UnsafeFPMath &&
21224             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21225           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21226             break;
21227           std::swap(LHS, RHS);
21228         }
21229         Opcode = X86ISD::FMIN;
21230         break;
21231       case ISD::SETUGT:
21232         // Converting this to a min would handle NaNs incorrectly.
21233         if (!DAG.getTarget().Options.UnsafeFPMath &&
21234             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21235           break;
21236         Opcode = X86ISD::FMIN;
21237         break;
21238       case ISD::SETUGE:
21239         // Converting this to a min would handle both negative zeros and NaNs
21240         // incorrectly, but we can swap the operands to fix both.
21241         std::swap(LHS, RHS);
21242       case ISD::SETOGT:
21243       case ISD::SETGT:
21244       case ISD::SETGE:
21245         Opcode = X86ISD::FMIN;
21246         break;
21247
21248       case ISD::SETULT:
21249         // Converting this to a max would handle NaNs incorrectly.
21250         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21251           break;
21252         Opcode = X86ISD::FMAX;
21253         break;
21254       case ISD::SETOLE:
21255         // Converting this to a max would handle comparisons between positive
21256         // and negative zero incorrectly, and swapping the operands would
21257         // cause it to handle NaNs incorrectly.
21258         if (!DAG.getTarget().Options.UnsafeFPMath &&
21259             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21260           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21261             break;
21262           std::swap(LHS, RHS);
21263         }
21264         Opcode = X86ISD::FMAX;
21265         break;
21266       case ISD::SETULE:
21267         // Converting this to a max would handle both negative zeros and NaNs
21268         // incorrectly, but we can swap the operands to fix both.
21269         std::swap(LHS, RHS);
21270       case ISD::SETOLT:
21271       case ISD::SETLT:
21272       case ISD::SETLE:
21273         Opcode = X86ISD::FMAX;
21274         break;
21275       }
21276     }
21277
21278     if (Opcode)
21279       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21280   }
21281
21282   EVT CondVT = Cond.getValueType();
21283   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21284       CondVT.getVectorElementType() == MVT::i1) {
21285     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21286     // lowering on KNL. In this case we convert it to
21287     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21288     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21289     // Since SKX these selects have a proper lowering.
21290     EVT OpVT = LHS.getValueType();
21291     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21292         (OpVT.getVectorElementType() == MVT::i8 ||
21293          OpVT.getVectorElementType() == MVT::i16) &&
21294         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21295       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21296       DCI.AddToWorklist(Cond.getNode());
21297       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21298     }
21299   }
21300   // If this is a select between two integer constants, try to do some
21301   // optimizations.
21302   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21303     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21304       // Don't do this for crazy integer types.
21305       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21306         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21307         // so that TrueC (the true value) is larger than FalseC.
21308         bool NeedsCondInvert = false;
21309
21310         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21311             // Efficiently invertible.
21312             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21313              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21314               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21315           NeedsCondInvert = true;
21316           std::swap(TrueC, FalseC);
21317         }
21318
21319         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21320         if (FalseC->getAPIntValue() == 0 &&
21321             TrueC->getAPIntValue().isPowerOf2()) {
21322           if (NeedsCondInvert) // Invert the condition if needed.
21323             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21324                                DAG.getConstant(1, DL, Cond.getValueType()));
21325
21326           // Zero extend the condition if needed.
21327           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21328
21329           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21330           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21331                              DAG.getConstant(ShAmt, DL, MVT::i8));
21332         }
21333
21334         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21335         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21336           if (NeedsCondInvert) // Invert the condition if needed.
21337             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21338                                DAG.getConstant(1, DL, Cond.getValueType()));
21339
21340           // Zero extend the condition if needed.
21341           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21342                              FalseC->getValueType(0), Cond);
21343           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21344                              SDValue(FalseC, 0));
21345         }
21346
21347         // Optimize cases that will turn into an LEA instruction.  This requires
21348         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21349         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21350           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21351           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21352
21353           bool isFastMultiplier = false;
21354           if (Diff < 10) {
21355             switch ((unsigned char)Diff) {
21356               default: break;
21357               case 1:  // result = add base, cond
21358               case 2:  // result = lea base(    , cond*2)
21359               case 3:  // result = lea base(cond, cond*2)
21360               case 4:  // result = lea base(    , cond*4)
21361               case 5:  // result = lea base(cond, cond*4)
21362               case 8:  // result = lea base(    , cond*8)
21363               case 9:  // result = lea base(cond, cond*8)
21364                 isFastMultiplier = true;
21365                 break;
21366             }
21367           }
21368
21369           if (isFastMultiplier) {
21370             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21371             if (NeedsCondInvert) // Invert the condition if needed.
21372               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21373                                  DAG.getConstant(1, DL, Cond.getValueType()));
21374
21375             // Zero extend the condition if needed.
21376             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21377                                Cond);
21378             // Scale the condition by the difference.
21379             if (Diff != 1)
21380               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21381                                  DAG.getConstant(Diff, DL,
21382                                                  Cond.getValueType()));
21383
21384             // Add the base if non-zero.
21385             if (FalseC->getAPIntValue() != 0)
21386               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21387                                  SDValue(FalseC, 0));
21388             return Cond;
21389           }
21390         }
21391       }
21392   }
21393
21394   // Canonicalize max and min:
21395   // (x > y) ? x : y -> (x >= y) ? x : y
21396   // (x < y) ? x : y -> (x <= y) ? x : y
21397   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21398   // the need for an extra compare
21399   // against zero. e.g.
21400   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21401   // subl   %esi, %edi
21402   // testl  %edi, %edi
21403   // movl   $0, %eax
21404   // cmovgl %edi, %eax
21405   // =>
21406   // xorl   %eax, %eax
21407   // subl   %esi, $edi
21408   // cmovsl %eax, %edi
21409   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21410       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21411       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21412     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21413     switch (CC) {
21414     default: break;
21415     case ISD::SETLT:
21416     case ISD::SETGT: {
21417       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21418       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21419                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21420       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21421     }
21422     }
21423   }
21424
21425   // Early exit check
21426   if (!TLI.isTypeLegal(VT))
21427     return SDValue();
21428
21429   // Match VSELECTs into subs with unsigned saturation.
21430   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21431       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21432       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21433        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21434     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21435
21436     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21437     // left side invert the predicate to simplify logic below.
21438     SDValue Other;
21439     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21440       Other = RHS;
21441       CC = ISD::getSetCCInverse(CC, true);
21442     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21443       Other = LHS;
21444     }
21445
21446     if (Other.getNode() && Other->getNumOperands() == 2 &&
21447         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21448       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21449       SDValue CondRHS = Cond->getOperand(1);
21450
21451       // Look for a general sub with unsigned saturation first.
21452       // x >= y ? x-y : 0 --> subus x, y
21453       // x >  y ? x-y : 0 --> subus x, y
21454       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21455           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21456         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21457
21458       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21459         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21460           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21461             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21462               // If the RHS is a constant we have to reverse the const
21463               // canonicalization.
21464               // x > C-1 ? x+-C : 0 --> subus x, C
21465               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21466                   CondRHSConst->getAPIntValue() ==
21467                       (-OpRHSConst->getAPIntValue() - 1))
21468                 return DAG.getNode(
21469                     X86ISD::SUBUS, DL, VT, OpLHS,
21470                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21471
21472           // Another special case: If C was a sign bit, the sub has been
21473           // canonicalized into a xor.
21474           // FIXME: Would it be better to use computeKnownBits to determine
21475           //        whether it's safe to decanonicalize the xor?
21476           // x s< 0 ? x^C : 0 --> subus x, C
21477           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21478               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21479               OpRHSConst->getAPIntValue().isSignBit())
21480             // Note that we have to rebuild the RHS constant here to ensure we
21481             // don't rely on particular values of undef lanes.
21482             return DAG.getNode(
21483                 X86ISD::SUBUS, DL, VT, OpLHS,
21484                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21485         }
21486     }
21487   }
21488
21489   // Try to match a min/max vector operation.
21490   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21491     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21492     unsigned Opc = ret.first;
21493     bool NeedSplit = ret.second;
21494
21495     if (Opc && NeedSplit) {
21496       unsigned NumElems = VT.getVectorNumElements();
21497       // Extract the LHS vectors
21498       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21499       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21500
21501       // Extract the RHS vectors
21502       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21503       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21504
21505       // Create min/max for each subvector
21506       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21507       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21508
21509       // Merge the result
21510       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21511     } else if (Opc)
21512       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21513   }
21514
21515   // Simplify vector selection if condition value type matches vselect
21516   // operand type
21517   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21518     assert(Cond.getValueType().isVector() &&
21519            "vector select expects a vector selector!");
21520
21521     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21522     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21523
21524     // Try invert the condition if true value is not all 1s and false value
21525     // is not all 0s.
21526     if (!TValIsAllOnes && !FValIsAllZeros &&
21527         // Check if the selector will be produced by CMPP*/PCMP*
21528         Cond.getOpcode() == ISD::SETCC &&
21529         // Check if SETCC has already been promoted
21530         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21531       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21532       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21533
21534       if (TValIsAllZeros || FValIsAllOnes) {
21535         SDValue CC = Cond.getOperand(2);
21536         ISD::CondCode NewCC =
21537           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21538                                Cond.getOperand(0).getValueType().isInteger());
21539         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21540         std::swap(LHS, RHS);
21541         TValIsAllOnes = FValIsAllOnes;
21542         FValIsAllZeros = TValIsAllZeros;
21543       }
21544     }
21545
21546     if (TValIsAllOnes || FValIsAllZeros) {
21547       SDValue Ret;
21548
21549       if (TValIsAllOnes && FValIsAllZeros)
21550         Ret = Cond;
21551       else if (TValIsAllOnes)
21552         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21553                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21554       else if (FValIsAllZeros)
21555         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21556                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21557
21558       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21559     }
21560   }
21561
21562   // We should generate an X86ISD::BLENDI from a vselect if its argument
21563   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21564   // constants. This specific pattern gets generated when we split a
21565   // selector for a 512 bit vector in a machine without AVX512 (but with
21566   // 256-bit vectors), during legalization:
21567   //
21568   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21569   //
21570   // Iff we find this pattern and the build_vectors are built from
21571   // constants, we translate the vselect into a shuffle_vector that we
21572   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21573   if ((N->getOpcode() == ISD::VSELECT ||
21574        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21575       !DCI.isBeforeLegalize()) {
21576     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21577     if (Shuffle.getNode())
21578       return Shuffle;
21579   }
21580
21581   // If this is a *dynamic* select (non-constant condition) and we can match
21582   // this node with one of the variable blend instructions, restructure the
21583   // condition so that the blends can use the high bit of each element and use
21584   // SimplifyDemandedBits to simplify the condition operand.
21585   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21586       !DCI.isBeforeLegalize() &&
21587       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21588     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21589
21590     // Don't optimize vector selects that map to mask-registers.
21591     if (BitWidth == 1)
21592       return SDValue();
21593
21594     // We can only handle the cases where VSELECT is directly legal on the
21595     // subtarget. We custom lower VSELECT nodes with constant conditions and
21596     // this makes it hard to see whether a dynamic VSELECT will correctly
21597     // lower, so we both check the operation's status and explicitly handle the
21598     // cases where a *dynamic* blend will fail even though a constant-condition
21599     // blend could be custom lowered.
21600     // FIXME: We should find a better way to handle this class of problems.
21601     // Potentially, we should combine constant-condition vselect nodes
21602     // pre-legalization into shuffles and not mark as many types as custom
21603     // lowered.
21604     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21605       return SDValue();
21606     // FIXME: We don't support i16-element blends currently. We could and
21607     // should support them by making *all* the bits in the condition be set
21608     // rather than just the high bit and using an i8-element blend.
21609     if (VT.getScalarType() == MVT::i16)
21610       return SDValue();
21611     // Dynamic blending was only available from SSE4.1 onward.
21612     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21613       return SDValue();
21614     // Byte blends are only available in AVX2
21615     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21616         !Subtarget->hasAVX2())
21617       return SDValue();
21618
21619     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21620     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21621
21622     APInt KnownZero, KnownOne;
21623     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21624                                           DCI.isBeforeLegalizeOps());
21625     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21626         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21627                                  TLO)) {
21628       // If we changed the computation somewhere in the DAG, this change
21629       // will affect all users of Cond.
21630       // Make sure it is fine and update all the nodes so that we do not
21631       // use the generic VSELECT anymore. Otherwise, we may perform
21632       // wrong optimizations as we messed up with the actual expectation
21633       // for the vector boolean values.
21634       if (Cond != TLO.Old) {
21635         // Check all uses of that condition operand to check whether it will be
21636         // consumed by non-BLEND instructions, which may depend on all bits are
21637         // set properly.
21638         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21639              I != E; ++I)
21640           if (I->getOpcode() != ISD::VSELECT)
21641             // TODO: Add other opcodes eventually lowered into BLEND.
21642             return SDValue();
21643
21644         // Update all the users of the condition, before committing the change,
21645         // so that the VSELECT optimizations that expect the correct vector
21646         // boolean value will not be triggered.
21647         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21648              I != E; ++I)
21649           DAG.ReplaceAllUsesOfValueWith(
21650               SDValue(*I, 0),
21651               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21652                           Cond, I->getOperand(1), I->getOperand(2)));
21653         DCI.CommitTargetLoweringOpt(TLO);
21654         return SDValue();
21655       }
21656       // At this point, only Cond is changed. Change the condition
21657       // just for N to keep the opportunity to optimize all other
21658       // users their own way.
21659       DAG.ReplaceAllUsesOfValueWith(
21660           SDValue(N, 0),
21661           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21662                       TLO.New, N->getOperand(1), N->getOperand(2)));
21663       return SDValue();
21664     }
21665   }
21666
21667   return SDValue();
21668 }
21669
21670 // Check whether a boolean test is testing a boolean value generated by
21671 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21672 // code.
21673 //
21674 // Simplify the following patterns:
21675 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21676 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21677 // to (Op EFLAGS Cond)
21678 //
21679 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21680 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21681 // to (Op EFLAGS !Cond)
21682 //
21683 // where Op could be BRCOND or CMOV.
21684 //
21685 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21686   // Quit if not CMP and SUB with its value result used.
21687   if (Cmp.getOpcode() != X86ISD::CMP &&
21688       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21689       return SDValue();
21690
21691   // Quit if not used as a boolean value.
21692   if (CC != X86::COND_E && CC != X86::COND_NE)
21693     return SDValue();
21694
21695   // Check CMP operands. One of them should be 0 or 1 and the other should be
21696   // an SetCC or extended from it.
21697   SDValue Op1 = Cmp.getOperand(0);
21698   SDValue Op2 = Cmp.getOperand(1);
21699
21700   SDValue SetCC;
21701   const ConstantSDNode* C = nullptr;
21702   bool needOppositeCond = (CC == X86::COND_E);
21703   bool checkAgainstTrue = false; // Is it a comparison against 1?
21704
21705   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21706     SetCC = Op2;
21707   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21708     SetCC = Op1;
21709   else // Quit if all operands are not constants.
21710     return SDValue();
21711
21712   if (C->getZExtValue() == 1) {
21713     needOppositeCond = !needOppositeCond;
21714     checkAgainstTrue = true;
21715   } else if (C->getZExtValue() != 0)
21716     // Quit if the constant is neither 0 or 1.
21717     return SDValue();
21718
21719   bool truncatedToBoolWithAnd = false;
21720   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21721   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21722          SetCC.getOpcode() == ISD::TRUNCATE ||
21723          SetCC.getOpcode() == ISD::AND) {
21724     if (SetCC.getOpcode() == ISD::AND) {
21725       int OpIdx = -1;
21726       ConstantSDNode *CS;
21727       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21728           CS->getZExtValue() == 1)
21729         OpIdx = 1;
21730       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21731           CS->getZExtValue() == 1)
21732         OpIdx = 0;
21733       if (OpIdx == -1)
21734         break;
21735       SetCC = SetCC.getOperand(OpIdx);
21736       truncatedToBoolWithAnd = true;
21737     } else
21738       SetCC = SetCC.getOperand(0);
21739   }
21740
21741   switch (SetCC.getOpcode()) {
21742   case X86ISD::SETCC_CARRY:
21743     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21744     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21745     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21746     // truncated to i1 using 'and'.
21747     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21748       break;
21749     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21750            "Invalid use of SETCC_CARRY!");
21751     // FALL THROUGH
21752   case X86ISD::SETCC:
21753     // Set the condition code or opposite one if necessary.
21754     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21755     if (needOppositeCond)
21756       CC = X86::GetOppositeBranchCondition(CC);
21757     return SetCC.getOperand(1);
21758   case X86ISD::CMOV: {
21759     // Check whether false/true value has canonical one, i.e. 0 or 1.
21760     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21761     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21762     // Quit if true value is not a constant.
21763     if (!TVal)
21764       return SDValue();
21765     // Quit if false value is not a constant.
21766     if (!FVal) {
21767       SDValue Op = SetCC.getOperand(0);
21768       // Skip 'zext' or 'trunc' node.
21769       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21770           Op.getOpcode() == ISD::TRUNCATE)
21771         Op = Op.getOperand(0);
21772       // A special case for rdrand/rdseed, where 0 is set if false cond is
21773       // found.
21774       if ((Op.getOpcode() != X86ISD::RDRAND &&
21775            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21776         return SDValue();
21777     }
21778     // Quit if false value is not the constant 0 or 1.
21779     bool FValIsFalse = true;
21780     if (FVal && FVal->getZExtValue() != 0) {
21781       if (FVal->getZExtValue() != 1)
21782         return SDValue();
21783       // If FVal is 1, opposite cond is needed.
21784       needOppositeCond = !needOppositeCond;
21785       FValIsFalse = false;
21786     }
21787     // Quit if TVal is not the constant opposite of FVal.
21788     if (FValIsFalse && TVal->getZExtValue() != 1)
21789       return SDValue();
21790     if (!FValIsFalse && TVal->getZExtValue() != 0)
21791       return SDValue();
21792     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21793     if (needOppositeCond)
21794       CC = X86::GetOppositeBranchCondition(CC);
21795     return SetCC.getOperand(3);
21796   }
21797   }
21798
21799   return SDValue();
21800 }
21801
21802 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21803 /// Match:
21804 ///   (X86or (X86setcc) (X86setcc))
21805 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21806 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21807                                            X86::CondCode &CC1, SDValue &Flags,
21808                                            bool &isAnd) {
21809   if (Cond->getOpcode() == X86ISD::CMP) {
21810     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21811     if (!CondOp1C || !CondOp1C->isNullValue())
21812       return false;
21813
21814     Cond = Cond->getOperand(0);
21815   }
21816
21817   isAnd = false;
21818
21819   SDValue SetCC0, SetCC1;
21820   switch (Cond->getOpcode()) {
21821   default: return false;
21822   case ISD::AND:
21823   case X86ISD::AND:
21824     isAnd = true;
21825     // fallthru
21826   case ISD::OR:
21827   case X86ISD::OR:
21828     SetCC0 = Cond->getOperand(0);
21829     SetCC1 = Cond->getOperand(1);
21830     break;
21831   };
21832
21833   // Make sure we have SETCC nodes, using the same flags value.
21834   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21835       SetCC1.getOpcode() != X86ISD::SETCC ||
21836       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21837     return false;
21838
21839   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21840   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21841   Flags = SetCC0->getOperand(1);
21842   return true;
21843 }
21844
21845 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21846 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21847                                   TargetLowering::DAGCombinerInfo &DCI,
21848                                   const X86Subtarget *Subtarget) {
21849   SDLoc DL(N);
21850
21851   // If the flag operand isn't dead, don't touch this CMOV.
21852   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21853     return SDValue();
21854
21855   SDValue FalseOp = N->getOperand(0);
21856   SDValue TrueOp = N->getOperand(1);
21857   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21858   SDValue Cond = N->getOperand(3);
21859
21860   if (CC == X86::COND_E || CC == X86::COND_NE) {
21861     switch (Cond.getOpcode()) {
21862     default: break;
21863     case X86ISD::BSR:
21864     case X86ISD::BSF:
21865       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21866       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21867         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21868     }
21869   }
21870
21871   SDValue Flags;
21872
21873   Flags = checkBoolTestSetCCCombine(Cond, CC);
21874   if (Flags.getNode() &&
21875       // Extra check as FCMOV only supports a subset of X86 cond.
21876       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21877     SDValue Ops[] = { FalseOp, TrueOp,
21878                       DAG.getConstant(CC, DL, MVT::i8), Flags };
21879     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21880   }
21881
21882   // If this is a select between two integer constants, try to do some
21883   // optimizations.  Note that the operands are ordered the opposite of SELECT
21884   // operands.
21885   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21886     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21887       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21888       // larger than FalseC (the false value).
21889       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21890         CC = X86::GetOppositeBranchCondition(CC);
21891         std::swap(TrueC, FalseC);
21892         std::swap(TrueOp, FalseOp);
21893       }
21894
21895       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21896       // This is efficient for any integer data type (including i8/i16) and
21897       // shift amount.
21898       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21899         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21900                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21901
21902         // Zero extend the condition if needed.
21903         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21904
21905         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21906         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21907                            DAG.getConstant(ShAmt, DL, MVT::i8));
21908         if (N->getNumValues() == 2)  // Dead flag value?
21909           return DCI.CombineTo(N, Cond, SDValue());
21910         return Cond;
21911       }
21912
21913       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21914       // for any integer data type, including i8/i16.
21915       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21916         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21917                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21918
21919         // Zero extend the condition if needed.
21920         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21921                            FalseC->getValueType(0), Cond);
21922         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21923                            SDValue(FalseC, 0));
21924
21925         if (N->getNumValues() == 2)  // Dead flag value?
21926           return DCI.CombineTo(N, Cond, SDValue());
21927         return Cond;
21928       }
21929
21930       // Optimize cases that will turn into an LEA instruction.  This requires
21931       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21932       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21933         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21934         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21935
21936         bool isFastMultiplier = false;
21937         if (Diff < 10) {
21938           switch ((unsigned char)Diff) {
21939           default: break;
21940           case 1:  // result = add base, cond
21941           case 2:  // result = lea base(    , cond*2)
21942           case 3:  // result = lea base(cond, cond*2)
21943           case 4:  // result = lea base(    , cond*4)
21944           case 5:  // result = lea base(cond, cond*4)
21945           case 8:  // result = lea base(    , cond*8)
21946           case 9:  // result = lea base(cond, cond*8)
21947             isFastMultiplier = true;
21948             break;
21949           }
21950         }
21951
21952         if (isFastMultiplier) {
21953           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21954           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21955                              DAG.getConstant(CC, DL, MVT::i8), Cond);
21956           // Zero extend the condition if needed.
21957           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21958                              Cond);
21959           // Scale the condition by the difference.
21960           if (Diff != 1)
21961             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21962                                DAG.getConstant(Diff, DL, Cond.getValueType()));
21963
21964           // Add the base if non-zero.
21965           if (FalseC->getAPIntValue() != 0)
21966             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21967                                SDValue(FalseC, 0));
21968           if (N->getNumValues() == 2)  // Dead flag value?
21969             return DCI.CombineTo(N, Cond, SDValue());
21970           return Cond;
21971         }
21972       }
21973     }
21974   }
21975
21976   // Handle these cases:
21977   //   (select (x != c), e, c) -> select (x != c), e, x),
21978   //   (select (x == c), c, e) -> select (x == c), x, e)
21979   // where the c is an integer constant, and the "select" is the combination
21980   // of CMOV and CMP.
21981   //
21982   // The rationale for this change is that the conditional-move from a constant
21983   // needs two instructions, however, conditional-move from a register needs
21984   // only one instruction.
21985   //
21986   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21987   //  some instruction-combining opportunities. This opt needs to be
21988   //  postponed as late as possible.
21989   //
21990   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21991     // the DCI.xxxx conditions are provided to postpone the optimization as
21992     // late as possible.
21993
21994     ConstantSDNode *CmpAgainst = nullptr;
21995     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21996         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21997         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21998
21999       if (CC == X86::COND_NE &&
22000           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22001         CC = X86::GetOppositeBranchCondition(CC);
22002         std::swap(TrueOp, FalseOp);
22003       }
22004
22005       if (CC == X86::COND_E &&
22006           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22007         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22008                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22009         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22010       }
22011     }
22012   }
22013
22014   // Fold and/or of setcc's to double CMOV:
22015   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22016   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22017   //
22018   // This combine lets us generate:
22019   //   cmovcc1 (jcc1 if we don't have CMOV)
22020   //   cmovcc2 (same)
22021   // instead of:
22022   //   setcc1
22023   //   setcc2
22024   //   and/or
22025   //   cmovne (jne if we don't have CMOV)
22026   // When we can't use the CMOV instruction, it might increase branch
22027   // mispredicts.
22028   // When we can use CMOV, or when there is no mispredict, this improves
22029   // throughput and reduces register pressure.
22030   //
22031   if (CC == X86::COND_NE) {
22032     SDValue Flags;
22033     X86::CondCode CC0, CC1;
22034     bool isAndSetCC;
22035     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22036       if (isAndSetCC) {
22037         std::swap(FalseOp, TrueOp);
22038         CC0 = X86::GetOppositeBranchCondition(CC0);
22039         CC1 = X86::GetOppositeBranchCondition(CC1);
22040       }
22041
22042       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22043         Flags};
22044       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22045       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22046       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22047       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22048       return CMOV;
22049     }
22050   }
22051
22052   return SDValue();
22053 }
22054
22055 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22056                                                 const X86Subtarget *Subtarget) {
22057   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22058   switch (IntNo) {
22059   default: return SDValue();
22060   // SSE/AVX/AVX2 blend intrinsics.
22061   case Intrinsic::x86_avx2_pblendvb:
22062     // Don't try to simplify this intrinsic if we don't have AVX2.
22063     if (!Subtarget->hasAVX2())
22064       return SDValue();
22065     // FALL-THROUGH
22066   case Intrinsic::x86_avx_blendv_pd_256:
22067   case Intrinsic::x86_avx_blendv_ps_256:
22068     // Don't try to simplify this intrinsic if we don't have AVX.
22069     if (!Subtarget->hasAVX())
22070       return SDValue();
22071     // FALL-THROUGH
22072   case Intrinsic::x86_sse41_blendvps:
22073   case Intrinsic::x86_sse41_blendvpd:
22074   case Intrinsic::x86_sse41_pblendvb: {
22075     SDValue Op0 = N->getOperand(1);
22076     SDValue Op1 = N->getOperand(2);
22077     SDValue Mask = N->getOperand(3);
22078
22079     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22080     if (!Subtarget->hasSSE41())
22081       return SDValue();
22082
22083     // fold (blend A, A, Mask) -> A
22084     if (Op0 == Op1)
22085       return Op0;
22086     // fold (blend A, B, allZeros) -> A
22087     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22088       return Op0;
22089     // fold (blend A, B, allOnes) -> B
22090     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22091       return Op1;
22092
22093     // Simplify the case where the mask is a constant i32 value.
22094     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22095       if (C->isNullValue())
22096         return Op0;
22097       if (C->isAllOnesValue())
22098         return Op1;
22099     }
22100
22101     return SDValue();
22102   }
22103
22104   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22105   case Intrinsic::x86_sse2_psrai_w:
22106   case Intrinsic::x86_sse2_psrai_d:
22107   case Intrinsic::x86_avx2_psrai_w:
22108   case Intrinsic::x86_avx2_psrai_d:
22109   case Intrinsic::x86_sse2_psra_w:
22110   case Intrinsic::x86_sse2_psra_d:
22111   case Intrinsic::x86_avx2_psra_w:
22112   case Intrinsic::x86_avx2_psra_d: {
22113     SDValue Op0 = N->getOperand(1);
22114     SDValue Op1 = N->getOperand(2);
22115     EVT VT = Op0.getValueType();
22116     assert(VT.isVector() && "Expected a vector type!");
22117
22118     if (isa<BuildVectorSDNode>(Op1))
22119       Op1 = Op1.getOperand(0);
22120
22121     if (!isa<ConstantSDNode>(Op1))
22122       return SDValue();
22123
22124     EVT SVT = VT.getVectorElementType();
22125     unsigned SVTBits = SVT.getSizeInBits();
22126
22127     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22128     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22129     uint64_t ShAmt = C.getZExtValue();
22130
22131     // Don't try to convert this shift into a ISD::SRA if the shift
22132     // count is bigger than or equal to the element size.
22133     if (ShAmt >= SVTBits)
22134       return SDValue();
22135
22136     // Trivial case: if the shift count is zero, then fold this
22137     // into the first operand.
22138     if (ShAmt == 0)
22139       return Op0;
22140
22141     // Replace this packed shift intrinsic with a target independent
22142     // shift dag node.
22143     SDLoc DL(N);
22144     SDValue Splat = DAG.getConstant(C, DL, VT);
22145     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22146   }
22147   }
22148 }
22149
22150 /// PerformMulCombine - Optimize a single multiply with constant into two
22151 /// in order to implement it with two cheaper instructions, e.g.
22152 /// LEA + SHL, LEA + LEA.
22153 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22154                                  TargetLowering::DAGCombinerInfo &DCI) {
22155   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22156     return SDValue();
22157
22158   EVT VT = N->getValueType(0);
22159   if (VT != MVT::i64 && VT != MVT::i32)
22160     return SDValue();
22161
22162   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22163   if (!C)
22164     return SDValue();
22165   uint64_t MulAmt = C->getZExtValue();
22166   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22167     return SDValue();
22168
22169   uint64_t MulAmt1 = 0;
22170   uint64_t MulAmt2 = 0;
22171   if ((MulAmt % 9) == 0) {
22172     MulAmt1 = 9;
22173     MulAmt2 = MulAmt / 9;
22174   } else if ((MulAmt % 5) == 0) {
22175     MulAmt1 = 5;
22176     MulAmt2 = MulAmt / 5;
22177   } else if ((MulAmt % 3) == 0) {
22178     MulAmt1 = 3;
22179     MulAmt2 = MulAmt / 3;
22180   }
22181   if (MulAmt2 &&
22182       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22183     SDLoc DL(N);
22184
22185     if (isPowerOf2_64(MulAmt2) &&
22186         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22187       // If second multiplifer is pow2, issue it first. We want the multiply by
22188       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22189       // is an add.
22190       std::swap(MulAmt1, MulAmt2);
22191
22192     SDValue NewMul;
22193     if (isPowerOf2_64(MulAmt1))
22194       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22195                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22196     else
22197       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22198                            DAG.getConstant(MulAmt1, DL, VT));
22199
22200     if (isPowerOf2_64(MulAmt2))
22201       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22202                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22203     else
22204       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22205                            DAG.getConstant(MulAmt2, DL, VT));
22206
22207     // Do not add new nodes to DAG combiner worklist.
22208     DCI.CombineTo(N, NewMul, false);
22209   }
22210   return SDValue();
22211 }
22212
22213 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22214   SDValue N0 = N->getOperand(0);
22215   SDValue N1 = N->getOperand(1);
22216   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22217   EVT VT = N0.getValueType();
22218
22219   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22220   // since the result of setcc_c is all zero's or all ones.
22221   if (VT.isInteger() && !VT.isVector() &&
22222       N1C && N0.getOpcode() == ISD::AND &&
22223       N0.getOperand(1).getOpcode() == ISD::Constant) {
22224     SDValue N00 = N0.getOperand(0);
22225     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22226         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22227           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22228          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22229       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22230       APInt ShAmt = N1C->getAPIntValue();
22231       Mask = Mask.shl(ShAmt);
22232       if (Mask != 0) {
22233         SDLoc DL(N);
22234         return DAG.getNode(ISD::AND, DL, VT,
22235                            N00, DAG.getConstant(Mask, DL, VT));
22236       }
22237     }
22238   }
22239
22240   // Hardware support for vector shifts is sparse which makes us scalarize the
22241   // vector operations in many cases. Also, on sandybridge ADD is faster than
22242   // shl.
22243   // (shl V, 1) -> add V,V
22244   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22245     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22246       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22247       // We shift all of the values by one. In many cases we do not have
22248       // hardware support for this operation. This is better expressed as an ADD
22249       // of two values.
22250       if (N1SplatC->getZExtValue() == 1)
22251         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22252     }
22253
22254   return SDValue();
22255 }
22256
22257 /// \brief Returns a vector of 0s if the node in input is a vector logical
22258 /// shift by a constant amount which is known to be bigger than or equal
22259 /// to the vector element size in bits.
22260 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22261                                       const X86Subtarget *Subtarget) {
22262   EVT VT = N->getValueType(0);
22263
22264   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22265       (!Subtarget->hasInt256() ||
22266        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22267     return SDValue();
22268
22269   SDValue Amt = N->getOperand(1);
22270   SDLoc DL(N);
22271   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22272     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22273       APInt ShiftAmt = AmtSplat->getAPIntValue();
22274       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22275
22276       // SSE2/AVX2 logical shifts always return a vector of 0s
22277       // if the shift amount is bigger than or equal to
22278       // the element size. The constant shift amount will be
22279       // encoded as a 8-bit immediate.
22280       if (ShiftAmt.trunc(8).uge(MaxAmount))
22281         return getZeroVector(VT, Subtarget, DAG, DL);
22282     }
22283
22284   return SDValue();
22285 }
22286
22287 /// PerformShiftCombine - Combine shifts.
22288 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22289                                    TargetLowering::DAGCombinerInfo &DCI,
22290                                    const X86Subtarget *Subtarget) {
22291   if (N->getOpcode() == ISD::SHL) {
22292     SDValue V = PerformSHLCombine(N, DAG);
22293     if (V.getNode()) return V;
22294   }
22295
22296   if (N->getOpcode() != ISD::SRA) {
22297     // Try to fold this logical shift into a zero vector.
22298     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22299     if (V.getNode()) return V;
22300   }
22301
22302   return SDValue();
22303 }
22304
22305 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22306 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22307 // and friends.  Likewise for OR -> CMPNEQSS.
22308 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22309                             TargetLowering::DAGCombinerInfo &DCI,
22310                             const X86Subtarget *Subtarget) {
22311   unsigned opcode;
22312
22313   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22314   // we're requiring SSE2 for both.
22315   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22316     SDValue N0 = N->getOperand(0);
22317     SDValue N1 = N->getOperand(1);
22318     SDValue CMP0 = N0->getOperand(1);
22319     SDValue CMP1 = N1->getOperand(1);
22320     SDLoc DL(N);
22321
22322     // The SETCCs should both refer to the same CMP.
22323     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22324       return SDValue();
22325
22326     SDValue CMP00 = CMP0->getOperand(0);
22327     SDValue CMP01 = CMP0->getOperand(1);
22328     EVT     VT    = CMP00.getValueType();
22329
22330     if (VT == MVT::f32 || VT == MVT::f64) {
22331       bool ExpectingFlags = false;
22332       // Check for any users that want flags:
22333       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22334            !ExpectingFlags && UI != UE; ++UI)
22335         switch (UI->getOpcode()) {
22336         default:
22337         case ISD::BR_CC:
22338         case ISD::BRCOND:
22339         case ISD::SELECT:
22340           ExpectingFlags = true;
22341           break;
22342         case ISD::CopyToReg:
22343         case ISD::SIGN_EXTEND:
22344         case ISD::ZERO_EXTEND:
22345         case ISD::ANY_EXTEND:
22346           break;
22347         }
22348
22349       if (!ExpectingFlags) {
22350         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22351         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22352
22353         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22354           X86::CondCode tmp = cc0;
22355           cc0 = cc1;
22356           cc1 = tmp;
22357         }
22358
22359         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22360             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22361           // FIXME: need symbolic constants for these magic numbers.
22362           // See X86ATTInstPrinter.cpp:printSSECC().
22363           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22364           if (Subtarget->hasAVX512()) {
22365             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22366                                          CMP01,
22367                                          DAG.getConstant(x86cc, DL, MVT::i8));
22368             if (N->getValueType(0) != MVT::i1)
22369               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22370                                  FSetCC);
22371             return FSetCC;
22372           }
22373           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22374                                               CMP00.getValueType(), CMP00, CMP01,
22375                                               DAG.getConstant(x86cc, DL,
22376                                                               MVT::i8));
22377
22378           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22379           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22380
22381           if (is64BitFP && !Subtarget->is64Bit()) {
22382             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22383             // 64-bit integer, since that's not a legal type. Since
22384             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22385             // bits, but can do this little dance to extract the lowest 32 bits
22386             // and work with those going forward.
22387             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22388                                            OnesOrZeroesF);
22389             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22390                                            Vector64);
22391             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22392                                         Vector32, DAG.getIntPtrConstant(0, DL));
22393             IntVT = MVT::i32;
22394           }
22395
22396           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22397                                               OnesOrZeroesF);
22398           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22399                                       DAG.getConstant(1, DL, IntVT));
22400           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22401                                               ANDed);
22402           return OneBitOfTruth;
22403         }
22404       }
22405     }
22406   }
22407   return SDValue();
22408 }
22409
22410 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22411 /// so it can be folded inside ANDNP.
22412 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22413   EVT VT = N->getValueType(0);
22414
22415   // Match direct AllOnes for 128 and 256-bit vectors
22416   if (ISD::isBuildVectorAllOnes(N))
22417     return true;
22418
22419   // Look through a bit convert.
22420   if (N->getOpcode() == ISD::BITCAST)
22421     N = N->getOperand(0).getNode();
22422
22423   // Sometimes the operand may come from a insert_subvector building a 256-bit
22424   // allones vector
22425   if (VT.is256BitVector() &&
22426       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22427     SDValue V1 = N->getOperand(0);
22428     SDValue V2 = N->getOperand(1);
22429
22430     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22431         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22432         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22433         ISD::isBuildVectorAllOnes(V2.getNode()))
22434       return true;
22435   }
22436
22437   return false;
22438 }
22439
22440 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22441 // register. In most cases we actually compare or select YMM-sized registers
22442 // and mixing the two types creates horrible code. This method optimizes
22443 // some of the transition sequences.
22444 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22445                                  TargetLowering::DAGCombinerInfo &DCI,
22446                                  const X86Subtarget *Subtarget) {
22447   EVT VT = N->getValueType(0);
22448   if (!VT.is256BitVector())
22449     return SDValue();
22450
22451   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22452           N->getOpcode() == ISD::ZERO_EXTEND ||
22453           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22454
22455   SDValue Narrow = N->getOperand(0);
22456   EVT NarrowVT = Narrow->getValueType(0);
22457   if (!NarrowVT.is128BitVector())
22458     return SDValue();
22459
22460   if (Narrow->getOpcode() != ISD::XOR &&
22461       Narrow->getOpcode() != ISD::AND &&
22462       Narrow->getOpcode() != ISD::OR)
22463     return SDValue();
22464
22465   SDValue N0  = Narrow->getOperand(0);
22466   SDValue N1  = Narrow->getOperand(1);
22467   SDLoc DL(Narrow);
22468
22469   // The Left side has to be a trunc.
22470   if (N0.getOpcode() != ISD::TRUNCATE)
22471     return SDValue();
22472
22473   // The type of the truncated inputs.
22474   EVT WideVT = N0->getOperand(0)->getValueType(0);
22475   if (WideVT != VT)
22476     return SDValue();
22477
22478   // The right side has to be a 'trunc' or a constant vector.
22479   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22480   ConstantSDNode *RHSConstSplat = nullptr;
22481   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22482     RHSConstSplat = RHSBV->getConstantSplatNode();
22483   if (!RHSTrunc && !RHSConstSplat)
22484     return SDValue();
22485
22486   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22487
22488   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22489     return SDValue();
22490
22491   // Set N0 and N1 to hold the inputs to the new wide operation.
22492   N0 = N0->getOperand(0);
22493   if (RHSConstSplat) {
22494     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22495                      SDValue(RHSConstSplat, 0));
22496     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22497     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22498   } else if (RHSTrunc) {
22499     N1 = N1->getOperand(0);
22500   }
22501
22502   // Generate the wide operation.
22503   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22504   unsigned Opcode = N->getOpcode();
22505   switch (Opcode) {
22506   case ISD::ANY_EXTEND:
22507     return Op;
22508   case ISD::ZERO_EXTEND: {
22509     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22510     APInt Mask = APInt::getAllOnesValue(InBits);
22511     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22512     return DAG.getNode(ISD::AND, DL, VT,
22513                        Op, DAG.getConstant(Mask, DL, VT));
22514   }
22515   case ISD::SIGN_EXTEND:
22516     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22517                        Op, DAG.getValueType(NarrowVT));
22518   default:
22519     llvm_unreachable("Unexpected opcode");
22520   }
22521 }
22522
22523 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22524                                  TargetLowering::DAGCombinerInfo &DCI,
22525                                  const X86Subtarget *Subtarget) {
22526   SDValue N0 = N->getOperand(0);
22527   SDValue N1 = N->getOperand(1);
22528   SDLoc DL(N);
22529
22530   // A vector zext_in_reg may be represented as a shuffle,
22531   // feeding into a bitcast (this represents anyext) feeding into
22532   // an and with a mask.
22533   // We'd like to try to combine that into a shuffle with zero
22534   // plus a bitcast, removing the and.
22535   if (N0.getOpcode() != ISD::BITCAST ||
22536       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22537     return SDValue();
22538
22539   // The other side of the AND should be a splat of 2^C, where C
22540   // is the number of bits in the source type.
22541   if (N1.getOpcode() == ISD::BITCAST)
22542     N1 = N1.getOperand(0);
22543   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22544     return SDValue();
22545   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22546
22547   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22548   EVT SrcType = Shuffle->getValueType(0);
22549
22550   // We expect a single-source shuffle
22551   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22552     return SDValue();
22553
22554   unsigned SrcSize = SrcType.getScalarSizeInBits();
22555
22556   APInt SplatValue, SplatUndef;
22557   unsigned SplatBitSize;
22558   bool HasAnyUndefs;
22559   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22560                                 SplatBitSize, HasAnyUndefs))
22561     return SDValue();
22562
22563   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22564   // Make sure the splat matches the mask we expect
22565   if (SplatBitSize > ResSize ||
22566       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22567     return SDValue();
22568
22569   // Make sure the input and output size make sense
22570   if (SrcSize >= ResSize || ResSize % SrcSize)
22571     return SDValue();
22572
22573   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22574   // The number of u's between each two values depends on the ratio between
22575   // the source and dest type.
22576   unsigned ZextRatio = ResSize / SrcSize;
22577   bool IsZext = true;
22578   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22579     if (i % ZextRatio) {
22580       if (Shuffle->getMaskElt(i) > 0) {
22581         // Expected undef
22582         IsZext = false;
22583         break;
22584       }
22585     } else {
22586       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22587         // Expected element number
22588         IsZext = false;
22589         break;
22590       }
22591     }
22592   }
22593
22594   if (!IsZext)
22595     return SDValue();
22596
22597   // Ok, perform the transformation - replace the shuffle with
22598   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22599   // (instead of undef) where the k elements come from the zero vector.
22600   SmallVector<int, 8> Mask;
22601   unsigned NumElems = SrcType.getVectorNumElements();
22602   for (unsigned i = 0; i < NumElems; ++i)
22603     if (i % ZextRatio)
22604       Mask.push_back(NumElems);
22605     else
22606       Mask.push_back(i / ZextRatio);
22607
22608   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22609     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22610   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22611 }
22612
22613 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22614                                  TargetLowering::DAGCombinerInfo &DCI,
22615                                  const X86Subtarget *Subtarget) {
22616   if (DCI.isBeforeLegalizeOps())
22617     return SDValue();
22618
22619   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22620     return Zext;
22621
22622   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22623     return R;
22624
22625   EVT VT = N->getValueType(0);
22626   SDValue N0 = N->getOperand(0);
22627   SDValue N1 = N->getOperand(1);
22628   SDLoc DL(N);
22629
22630   // Create BEXTR instructions
22631   // BEXTR is ((X >> imm) & (2**size-1))
22632   if (VT == MVT::i32 || VT == MVT::i64) {
22633     // Check for BEXTR.
22634     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22635         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22636       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22637       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22638       if (MaskNode && ShiftNode) {
22639         uint64_t Mask = MaskNode->getZExtValue();
22640         uint64_t Shift = ShiftNode->getZExtValue();
22641         if (isMask_64(Mask)) {
22642           uint64_t MaskSize = countPopulation(Mask);
22643           if (Shift + MaskSize <= VT.getSizeInBits())
22644             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22645                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22646                                                VT));
22647         }
22648       }
22649     } // BEXTR
22650
22651     return SDValue();
22652   }
22653
22654   // Want to form ANDNP nodes:
22655   // 1) In the hopes of then easily combining them with OR and AND nodes
22656   //    to form PBLEND/PSIGN.
22657   // 2) To match ANDN packed intrinsics
22658   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22659     return SDValue();
22660
22661   // Check LHS for vnot
22662   if (N0.getOpcode() == ISD::XOR &&
22663       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22664       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22665     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22666
22667   // Check RHS for vnot
22668   if (N1.getOpcode() == ISD::XOR &&
22669       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22670       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22671     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22672
22673   return SDValue();
22674 }
22675
22676 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22677                                 TargetLowering::DAGCombinerInfo &DCI,
22678                                 const X86Subtarget *Subtarget) {
22679   if (DCI.isBeforeLegalizeOps())
22680     return SDValue();
22681
22682   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22683   if (R.getNode())
22684     return R;
22685
22686   SDValue N0 = N->getOperand(0);
22687   SDValue N1 = N->getOperand(1);
22688   EVT VT = N->getValueType(0);
22689
22690   // look for psign/blend
22691   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22692     if (!Subtarget->hasSSSE3() ||
22693         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22694       return SDValue();
22695
22696     // Canonicalize pandn to RHS
22697     if (N0.getOpcode() == X86ISD::ANDNP)
22698       std::swap(N0, N1);
22699     // or (and (m, y), (pandn m, x))
22700     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22701       SDValue Mask = N1.getOperand(0);
22702       SDValue X    = N1.getOperand(1);
22703       SDValue Y;
22704       if (N0.getOperand(0) == Mask)
22705         Y = N0.getOperand(1);
22706       if (N0.getOperand(1) == Mask)
22707         Y = N0.getOperand(0);
22708
22709       // Check to see if the mask appeared in both the AND and ANDNP and
22710       if (!Y.getNode())
22711         return SDValue();
22712
22713       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22714       // Look through mask bitcast.
22715       if (Mask.getOpcode() == ISD::BITCAST)
22716         Mask = Mask.getOperand(0);
22717       if (X.getOpcode() == ISD::BITCAST)
22718         X = X.getOperand(0);
22719       if (Y.getOpcode() == ISD::BITCAST)
22720         Y = Y.getOperand(0);
22721
22722       EVT MaskVT = Mask.getValueType();
22723
22724       // Validate that the Mask operand is a vector sra node.
22725       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22726       // there is no psrai.b
22727       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22728       unsigned SraAmt = ~0;
22729       if (Mask.getOpcode() == ISD::SRA) {
22730         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22731           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22732             SraAmt = AmtConst->getZExtValue();
22733       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22734         SDValue SraC = Mask.getOperand(1);
22735         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22736       }
22737       if ((SraAmt + 1) != EltBits)
22738         return SDValue();
22739
22740       SDLoc DL(N);
22741
22742       // Now we know we at least have a plendvb with the mask val.  See if
22743       // we can form a psignb/w/d.
22744       // psign = x.type == y.type == mask.type && y = sub(0, x);
22745       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22746           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22747           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22748         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22749                "Unsupported VT for PSIGN");
22750         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22751         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22752       }
22753       // PBLENDVB only available on SSE 4.1
22754       if (!Subtarget->hasSSE41())
22755         return SDValue();
22756
22757       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22758
22759       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22760       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22761       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22762       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22763       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22764     }
22765   }
22766
22767   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22768     return SDValue();
22769
22770   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22771   MachineFunction &MF = DAG.getMachineFunction();
22772   bool OptForSize =
22773       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22774
22775   // SHLD/SHRD instructions have lower register pressure, but on some
22776   // platforms they have higher latency than the equivalent
22777   // series of shifts/or that would otherwise be generated.
22778   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22779   // have higher latencies and we are not optimizing for size.
22780   if (!OptForSize && Subtarget->isSHLDSlow())
22781     return SDValue();
22782
22783   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22784     std::swap(N0, N1);
22785   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22786     return SDValue();
22787   if (!N0.hasOneUse() || !N1.hasOneUse())
22788     return SDValue();
22789
22790   SDValue ShAmt0 = N0.getOperand(1);
22791   if (ShAmt0.getValueType() != MVT::i8)
22792     return SDValue();
22793   SDValue ShAmt1 = N1.getOperand(1);
22794   if (ShAmt1.getValueType() != MVT::i8)
22795     return SDValue();
22796   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22797     ShAmt0 = ShAmt0.getOperand(0);
22798   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22799     ShAmt1 = ShAmt1.getOperand(0);
22800
22801   SDLoc DL(N);
22802   unsigned Opc = X86ISD::SHLD;
22803   SDValue Op0 = N0.getOperand(0);
22804   SDValue Op1 = N1.getOperand(0);
22805   if (ShAmt0.getOpcode() == ISD::SUB) {
22806     Opc = X86ISD::SHRD;
22807     std::swap(Op0, Op1);
22808     std::swap(ShAmt0, ShAmt1);
22809   }
22810
22811   unsigned Bits = VT.getSizeInBits();
22812   if (ShAmt1.getOpcode() == ISD::SUB) {
22813     SDValue Sum = ShAmt1.getOperand(0);
22814     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22815       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22816       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22817         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22818       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22819         return DAG.getNode(Opc, DL, VT,
22820                            Op0, Op1,
22821                            DAG.getNode(ISD::TRUNCATE, DL,
22822                                        MVT::i8, ShAmt0));
22823     }
22824   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22825     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22826     if (ShAmt0C &&
22827         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22828       return DAG.getNode(Opc, DL, VT,
22829                          N0.getOperand(0), N1.getOperand(0),
22830                          DAG.getNode(ISD::TRUNCATE, DL,
22831                                        MVT::i8, ShAmt0));
22832   }
22833
22834   return SDValue();
22835 }
22836
22837 // Generate NEG and CMOV for integer abs.
22838 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22839   EVT VT = N->getValueType(0);
22840
22841   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22842   // 8-bit integer abs to NEG and CMOV.
22843   if (VT.isInteger() && VT.getSizeInBits() == 8)
22844     return SDValue();
22845
22846   SDValue N0 = N->getOperand(0);
22847   SDValue N1 = N->getOperand(1);
22848   SDLoc DL(N);
22849
22850   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22851   // and change it to SUB and CMOV.
22852   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22853       N0.getOpcode() == ISD::ADD &&
22854       N0.getOperand(1) == N1 &&
22855       N1.getOpcode() == ISD::SRA &&
22856       N1.getOperand(0) == N0.getOperand(0))
22857     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22858       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22859         // Generate SUB & CMOV.
22860         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22861                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
22862
22863         SDValue Ops[] = { N0.getOperand(0), Neg,
22864                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22865                           SDValue(Neg.getNode(), 1) };
22866         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22867       }
22868   return SDValue();
22869 }
22870
22871 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22872 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22873                                  TargetLowering::DAGCombinerInfo &DCI,
22874                                  const X86Subtarget *Subtarget) {
22875   if (DCI.isBeforeLegalizeOps())
22876     return SDValue();
22877
22878   if (Subtarget->hasCMov()) {
22879     SDValue RV = performIntegerAbsCombine(N, DAG);
22880     if (RV.getNode())
22881       return RV;
22882   }
22883
22884   return SDValue();
22885 }
22886
22887 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22888 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22889                                   TargetLowering::DAGCombinerInfo &DCI,
22890                                   const X86Subtarget *Subtarget) {
22891   LoadSDNode *Ld = cast<LoadSDNode>(N);
22892   EVT RegVT = Ld->getValueType(0);
22893   EVT MemVT = Ld->getMemoryVT();
22894   SDLoc dl(Ld);
22895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22896
22897   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22898   // into two 16-byte operations.
22899   ISD::LoadExtType Ext = Ld->getExtensionType();
22900   unsigned Alignment = Ld->getAlignment();
22901   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22902   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22903       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22904     unsigned NumElems = RegVT.getVectorNumElements();
22905     if (NumElems < 2)
22906       return SDValue();
22907
22908     SDValue Ptr = Ld->getBasePtr();
22909     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
22910
22911     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22912                                   NumElems/2);
22913     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22914                                 Ld->getPointerInfo(), Ld->isVolatile(),
22915                                 Ld->isNonTemporal(), Ld->isInvariant(),
22916                                 Alignment);
22917     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22918     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22919                                 Ld->getPointerInfo(), Ld->isVolatile(),
22920                                 Ld->isNonTemporal(), Ld->isInvariant(),
22921                                 std::min(16U, Alignment));
22922     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22923                              Load1.getValue(1),
22924                              Load2.getValue(1));
22925
22926     SDValue NewVec = DAG.getUNDEF(RegVT);
22927     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22928     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22929     return DCI.CombineTo(N, NewVec, TF, true);
22930   }
22931
22932   return SDValue();
22933 }
22934
22935 /// PerformMLOADCombine - Resolve extending loads
22936 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22937                                    TargetLowering::DAGCombinerInfo &DCI,
22938                                    const X86Subtarget *Subtarget) {
22939   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22940   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22941     return SDValue();
22942
22943   EVT VT = Mld->getValueType(0);
22944   unsigned NumElems = VT.getVectorNumElements();
22945   EVT LdVT = Mld->getMemoryVT();
22946   SDLoc dl(Mld);
22947
22948   assert(LdVT != VT && "Cannot extend to the same type");
22949   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22950   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22951   // From, To sizes and ElemCount must be pow of two
22952   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22953     "Unexpected size for extending masked load");
22954
22955   unsigned SizeRatio  = ToSz / FromSz;
22956   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22957
22958   // Create a type on which we perform the shuffle
22959   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22960           LdVT.getScalarType(), NumElems*SizeRatio);
22961   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22962
22963   // Convert Src0 value
22964   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22965   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22966     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22967     for (unsigned i = 0; i != NumElems; ++i)
22968       ShuffleVec[i] = i * SizeRatio;
22969
22970     // Can't shuffle using an illegal type.
22971     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22972             && "WideVecVT should be legal");
22973     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22974                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22975   }
22976   // Prepare the new mask
22977   SDValue NewMask;
22978   SDValue Mask = Mld->getMask();
22979   if (Mask.getValueType() == VT) {
22980     // Mask and original value have the same type
22981     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22982     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22983     for (unsigned i = 0; i != NumElems; ++i)
22984       ShuffleVec[i] = i * SizeRatio;
22985     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22986       ShuffleVec[i] = NumElems*SizeRatio;
22987     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22988                                    DAG.getConstant(0, dl, WideVecVT),
22989                                    &ShuffleVec[0]);
22990   }
22991   else {
22992     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22993     unsigned WidenNumElts = NumElems*SizeRatio;
22994     unsigned MaskNumElts = VT.getVectorNumElements();
22995     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22996                                      WidenNumElts);
22997
22998     unsigned NumConcat = WidenNumElts / MaskNumElts;
22999     SmallVector<SDValue, 16> Ops(NumConcat);
23000     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23001     Ops[0] = Mask;
23002     for (unsigned i = 1; i != NumConcat; ++i)
23003       Ops[i] = ZeroVal;
23004
23005     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23006   }
23007
23008   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23009                                      Mld->getBasePtr(), NewMask, WideSrc0,
23010                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23011                                      ISD::NON_EXTLOAD);
23012   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23013   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23014
23015 }
23016 /// PerformMSTORECombine - Resolve truncating stores
23017 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23018                                     const X86Subtarget *Subtarget) {
23019   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23020   if (!Mst->isTruncatingStore())
23021     return SDValue();
23022
23023   EVT VT = Mst->getValue().getValueType();
23024   unsigned NumElems = VT.getVectorNumElements();
23025   EVT StVT = Mst->getMemoryVT();
23026   SDLoc dl(Mst);
23027
23028   assert(StVT != VT && "Cannot truncate to the same type");
23029   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23030   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23031
23032   // From, To sizes and ElemCount must be pow of two
23033   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23034     "Unexpected size for truncating masked store");
23035   // We are going to use the original vector elt for storing.
23036   // Accumulated smaller vector elements must be a multiple of the store size.
23037   assert (((NumElems * FromSz) % ToSz) == 0 &&
23038           "Unexpected ratio for truncating masked store");
23039
23040   unsigned SizeRatio  = FromSz / ToSz;
23041   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23042
23043   // Create a type on which we perform the shuffle
23044   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23045           StVT.getScalarType(), NumElems*SizeRatio);
23046
23047   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23048
23049   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23050   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23051   for (unsigned i = 0; i != NumElems; ++i)
23052     ShuffleVec[i] = i * SizeRatio;
23053
23054   // Can't shuffle using an illegal type.
23055   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23056           && "WideVecVT should be legal");
23057
23058   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23059                                         DAG.getUNDEF(WideVecVT),
23060                                         &ShuffleVec[0]);
23061
23062   SDValue NewMask;
23063   SDValue Mask = Mst->getMask();
23064   if (Mask.getValueType() == VT) {
23065     // Mask and original value have the same type
23066     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23067     for (unsigned i = 0; i != NumElems; ++i)
23068       ShuffleVec[i] = i * SizeRatio;
23069     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23070       ShuffleVec[i] = NumElems*SizeRatio;
23071     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23072                                    DAG.getConstant(0, dl, WideVecVT),
23073                                    &ShuffleVec[0]);
23074   }
23075   else {
23076     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23077     unsigned WidenNumElts = NumElems*SizeRatio;
23078     unsigned MaskNumElts = VT.getVectorNumElements();
23079     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23080                                      WidenNumElts);
23081
23082     unsigned NumConcat = WidenNumElts / MaskNumElts;
23083     SmallVector<SDValue, 16> Ops(NumConcat);
23084     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23085     Ops[0] = Mask;
23086     for (unsigned i = 1; i != NumConcat; ++i)
23087       Ops[i] = ZeroVal;
23088
23089     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23090   }
23091
23092   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23093                             NewMask, StVT, Mst->getMemOperand(), false);
23094 }
23095 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23096 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23097                                    const X86Subtarget *Subtarget) {
23098   StoreSDNode *St = cast<StoreSDNode>(N);
23099   EVT VT = St->getValue().getValueType();
23100   EVT StVT = St->getMemoryVT();
23101   SDLoc dl(St);
23102   SDValue StoredVal = St->getOperand(1);
23103   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23104
23105   // If we are saving a concatenation of two XMM registers and 32-byte stores
23106   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23107   unsigned Alignment = St->getAlignment();
23108   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23109   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23110       StVT == VT && !IsAligned) {
23111     unsigned NumElems = VT.getVectorNumElements();
23112     if (NumElems < 2)
23113       return SDValue();
23114
23115     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23116     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23117
23118     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23119     SDValue Ptr0 = St->getBasePtr();
23120     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23121
23122     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23123                                 St->getPointerInfo(), St->isVolatile(),
23124                                 St->isNonTemporal(), Alignment);
23125     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23126                                 St->getPointerInfo(), St->isVolatile(),
23127                                 St->isNonTemporal(),
23128                                 std::min(16U, Alignment));
23129     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23130   }
23131
23132   // Optimize trunc store (of multiple scalars) to shuffle and store.
23133   // First, pack all of the elements in one place. Next, store to memory
23134   // in fewer chunks.
23135   if (St->isTruncatingStore() && VT.isVector()) {
23136     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23137     unsigned NumElems = VT.getVectorNumElements();
23138     assert(StVT != VT && "Cannot truncate to the same type");
23139     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23140     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23141
23142     // From, To sizes and ElemCount must be pow of two
23143     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23144     // We are going to use the original vector elt for storing.
23145     // Accumulated smaller vector elements must be a multiple of the store size.
23146     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23147
23148     unsigned SizeRatio  = FromSz / ToSz;
23149
23150     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23151
23152     // Create a type on which we perform the shuffle
23153     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23154             StVT.getScalarType(), NumElems*SizeRatio);
23155
23156     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23157
23158     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23159     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23160     for (unsigned i = 0; i != NumElems; ++i)
23161       ShuffleVec[i] = i * SizeRatio;
23162
23163     // Can't shuffle using an illegal type.
23164     if (!TLI.isTypeLegal(WideVecVT))
23165       return SDValue();
23166
23167     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23168                                          DAG.getUNDEF(WideVecVT),
23169                                          &ShuffleVec[0]);
23170     // At this point all of the data is stored at the bottom of the
23171     // register. We now need to save it to mem.
23172
23173     // Find the largest store unit
23174     MVT StoreType = MVT::i8;
23175     for (MVT Tp : MVT::integer_valuetypes()) {
23176       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23177         StoreType = Tp;
23178     }
23179
23180     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23181     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23182         (64 <= NumElems * ToSz))
23183       StoreType = MVT::f64;
23184
23185     // Bitcast the original vector into a vector of store-size units
23186     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23187             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23188     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23189     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23190     SmallVector<SDValue, 8> Chains;
23191     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23192                                         TLI.getPointerTy());
23193     SDValue Ptr = St->getBasePtr();
23194
23195     // Perform one or more big stores into memory.
23196     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23197       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23198                                    StoreType, ShuffWide,
23199                                    DAG.getIntPtrConstant(i, dl));
23200       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23201                                 St->getPointerInfo(), St->isVolatile(),
23202                                 St->isNonTemporal(), St->getAlignment());
23203       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23204       Chains.push_back(Ch);
23205     }
23206
23207     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23208   }
23209
23210   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23211   // the FP state in cases where an emms may be missing.
23212   // A preferable solution to the general problem is to figure out the right
23213   // places to insert EMMS.  This qualifies as a quick hack.
23214
23215   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23216   if (VT.getSizeInBits() != 64)
23217     return SDValue();
23218
23219   const Function *F = DAG.getMachineFunction().getFunction();
23220   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23221   bool F64IsLegal =
23222       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23223   if ((VT.isVector() ||
23224        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23225       isa<LoadSDNode>(St->getValue()) &&
23226       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23227       St->getChain().hasOneUse() && !St->isVolatile()) {
23228     SDNode* LdVal = St->getValue().getNode();
23229     LoadSDNode *Ld = nullptr;
23230     int TokenFactorIndex = -1;
23231     SmallVector<SDValue, 8> Ops;
23232     SDNode* ChainVal = St->getChain().getNode();
23233     // Must be a store of a load.  We currently handle two cases:  the load
23234     // is a direct child, and it's under an intervening TokenFactor.  It is
23235     // possible to dig deeper under nested TokenFactors.
23236     if (ChainVal == LdVal)
23237       Ld = cast<LoadSDNode>(St->getChain());
23238     else if (St->getValue().hasOneUse() &&
23239              ChainVal->getOpcode() == ISD::TokenFactor) {
23240       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23241         if (ChainVal->getOperand(i).getNode() == LdVal) {
23242           TokenFactorIndex = i;
23243           Ld = cast<LoadSDNode>(St->getValue());
23244         } else
23245           Ops.push_back(ChainVal->getOperand(i));
23246       }
23247     }
23248
23249     if (!Ld || !ISD::isNormalLoad(Ld))
23250       return SDValue();
23251
23252     // If this is not the MMX case, i.e. we are just turning i64 load/store
23253     // into f64 load/store, avoid the transformation if there are multiple
23254     // uses of the loaded value.
23255     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23256       return SDValue();
23257
23258     SDLoc LdDL(Ld);
23259     SDLoc StDL(N);
23260     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23261     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23262     // pair instead.
23263     if (Subtarget->is64Bit() || F64IsLegal) {
23264       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23265       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23266                                   Ld->getPointerInfo(), Ld->isVolatile(),
23267                                   Ld->isNonTemporal(), Ld->isInvariant(),
23268                                   Ld->getAlignment());
23269       SDValue NewChain = NewLd.getValue(1);
23270       if (TokenFactorIndex != -1) {
23271         Ops.push_back(NewChain);
23272         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23273       }
23274       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23275                           St->getPointerInfo(),
23276                           St->isVolatile(), St->isNonTemporal(),
23277                           St->getAlignment());
23278     }
23279
23280     // Otherwise, lower to two pairs of 32-bit loads / stores.
23281     SDValue LoAddr = Ld->getBasePtr();
23282     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23283                                  DAG.getConstant(4, LdDL, MVT::i32));
23284
23285     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23286                                Ld->getPointerInfo(),
23287                                Ld->isVolatile(), Ld->isNonTemporal(),
23288                                Ld->isInvariant(), Ld->getAlignment());
23289     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23290                                Ld->getPointerInfo().getWithOffset(4),
23291                                Ld->isVolatile(), Ld->isNonTemporal(),
23292                                Ld->isInvariant(),
23293                                MinAlign(Ld->getAlignment(), 4));
23294
23295     SDValue NewChain = LoLd.getValue(1);
23296     if (TokenFactorIndex != -1) {
23297       Ops.push_back(LoLd);
23298       Ops.push_back(HiLd);
23299       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23300     }
23301
23302     LoAddr = St->getBasePtr();
23303     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23304                          DAG.getConstant(4, StDL, MVT::i32));
23305
23306     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23307                                 St->getPointerInfo(),
23308                                 St->isVolatile(), St->isNonTemporal(),
23309                                 St->getAlignment());
23310     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23311                                 St->getPointerInfo().getWithOffset(4),
23312                                 St->isVolatile(),
23313                                 St->isNonTemporal(),
23314                                 MinAlign(St->getAlignment(), 4));
23315     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23316   }
23317
23318   // This is similar to the above case, but here we handle a scalar 64-bit
23319   // integer store that is extracted from a vector on a 32-bit target.
23320   // If we have SSE2, then we can treat it like a floating-point double
23321   // to get past legalization. The execution dependencies fixup pass will
23322   // choose the optimal machine instruction for the store if this really is
23323   // an integer or v2f32 rather than an f64.
23324   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23325       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23326     SDValue OldExtract = St->getOperand(1);
23327     SDValue ExtOp0 = OldExtract.getOperand(0);
23328     unsigned VecSize = ExtOp0.getValueSizeInBits();
23329     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23330     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23331     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23332                                      BitCast, OldExtract.getOperand(1));
23333     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23334                         St->getPointerInfo(), St->isVolatile(),
23335                         St->isNonTemporal(), St->getAlignment());
23336   }
23337
23338   return SDValue();
23339 }
23340
23341 /// Return 'true' if this vector operation is "horizontal"
23342 /// and return the operands for the horizontal operation in LHS and RHS.  A
23343 /// horizontal operation performs the binary operation on successive elements
23344 /// of its first operand, then on successive elements of its second operand,
23345 /// returning the resulting values in a vector.  For example, if
23346 ///   A = < float a0, float a1, float a2, float a3 >
23347 /// and
23348 ///   B = < float b0, float b1, float b2, float b3 >
23349 /// then the result of doing a horizontal operation on A and B is
23350 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23351 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23352 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23353 /// set to A, RHS to B, and the routine returns 'true'.
23354 /// Note that the binary operation should have the property that if one of the
23355 /// operands is UNDEF then the result is UNDEF.
23356 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23357   // Look for the following pattern: if
23358   //   A = < float a0, float a1, float a2, float a3 >
23359   //   B = < float b0, float b1, float b2, float b3 >
23360   // and
23361   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23362   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23363   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23364   // which is A horizontal-op B.
23365
23366   // At least one of the operands should be a vector shuffle.
23367   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23368       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23369     return false;
23370
23371   MVT VT = LHS.getSimpleValueType();
23372
23373   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23374          "Unsupported vector type for horizontal add/sub");
23375
23376   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23377   // operate independently on 128-bit lanes.
23378   unsigned NumElts = VT.getVectorNumElements();
23379   unsigned NumLanes = VT.getSizeInBits()/128;
23380   unsigned NumLaneElts = NumElts / NumLanes;
23381   assert((NumLaneElts % 2 == 0) &&
23382          "Vector type should have an even number of elements in each lane");
23383   unsigned HalfLaneElts = NumLaneElts/2;
23384
23385   // View LHS in the form
23386   //   LHS = VECTOR_SHUFFLE A, B, LMask
23387   // If LHS is not a shuffle then pretend it is the shuffle
23388   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23389   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23390   // type VT.
23391   SDValue A, B;
23392   SmallVector<int, 16> LMask(NumElts);
23393   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23394     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23395       A = LHS.getOperand(0);
23396     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23397       B = LHS.getOperand(1);
23398     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23399     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23400   } else {
23401     if (LHS.getOpcode() != ISD::UNDEF)
23402       A = LHS;
23403     for (unsigned i = 0; i != NumElts; ++i)
23404       LMask[i] = i;
23405   }
23406
23407   // Likewise, view RHS in the form
23408   //   RHS = VECTOR_SHUFFLE C, D, RMask
23409   SDValue C, D;
23410   SmallVector<int, 16> RMask(NumElts);
23411   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23412     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23413       C = RHS.getOperand(0);
23414     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23415       D = RHS.getOperand(1);
23416     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23417     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23418   } else {
23419     if (RHS.getOpcode() != ISD::UNDEF)
23420       C = RHS;
23421     for (unsigned i = 0; i != NumElts; ++i)
23422       RMask[i] = i;
23423   }
23424
23425   // Check that the shuffles are both shuffling the same vectors.
23426   if (!(A == C && B == D) && !(A == D && B == C))
23427     return false;
23428
23429   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23430   if (!A.getNode() && !B.getNode())
23431     return false;
23432
23433   // If A and B occur in reverse order in RHS, then "swap" them (which means
23434   // rewriting the mask).
23435   if (A != C)
23436     ShuffleVectorSDNode::commuteMask(RMask);
23437
23438   // At this point LHS and RHS are equivalent to
23439   //   LHS = VECTOR_SHUFFLE A, B, LMask
23440   //   RHS = VECTOR_SHUFFLE A, B, RMask
23441   // Check that the masks correspond to performing a horizontal operation.
23442   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23443     for (unsigned i = 0; i != NumLaneElts; ++i) {
23444       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23445
23446       // Ignore any UNDEF components.
23447       if (LIdx < 0 || RIdx < 0 ||
23448           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23449           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23450         continue;
23451
23452       // Check that successive elements are being operated on.  If not, this is
23453       // not a horizontal operation.
23454       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23455       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23456       if (!(LIdx == Index && RIdx == Index + 1) &&
23457           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23458         return false;
23459     }
23460   }
23461
23462   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23463   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23464   return true;
23465 }
23466
23467 /// Do target-specific dag combines on floating point adds.
23468 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23469                                   const X86Subtarget *Subtarget) {
23470   EVT VT = N->getValueType(0);
23471   SDValue LHS = N->getOperand(0);
23472   SDValue RHS = N->getOperand(1);
23473
23474   // Try to synthesize horizontal adds from adds of shuffles.
23475   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23476        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23477       isHorizontalBinOp(LHS, RHS, true))
23478     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23479   return SDValue();
23480 }
23481
23482 /// Do target-specific dag combines on floating point subs.
23483 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23484                                   const X86Subtarget *Subtarget) {
23485   EVT VT = N->getValueType(0);
23486   SDValue LHS = N->getOperand(0);
23487   SDValue RHS = N->getOperand(1);
23488
23489   // Try to synthesize horizontal subs from subs of shuffles.
23490   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23491        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23492       isHorizontalBinOp(LHS, RHS, false))
23493     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23494   return SDValue();
23495 }
23496
23497 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23498 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23499   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23500
23501   // F[X]OR(0.0, x) -> x
23502   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23503     if (C->getValueAPF().isPosZero())
23504       return N->getOperand(1);
23505
23506   // F[X]OR(x, 0.0) -> x
23507   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23508     if (C->getValueAPF().isPosZero())
23509       return N->getOperand(0);
23510   return SDValue();
23511 }
23512
23513 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23514 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23515   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23516
23517   // Only perform optimizations if UnsafeMath is used.
23518   if (!DAG.getTarget().Options.UnsafeFPMath)
23519     return SDValue();
23520
23521   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23522   // into FMINC and FMAXC, which are Commutative operations.
23523   unsigned NewOp = 0;
23524   switch (N->getOpcode()) {
23525     default: llvm_unreachable("unknown opcode");
23526     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23527     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23528   }
23529
23530   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23531                      N->getOperand(0), N->getOperand(1));
23532 }
23533
23534 /// Do target-specific dag combines on X86ISD::FAND nodes.
23535 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23536   // FAND(0.0, x) -> 0.0
23537   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23538     if (C->getValueAPF().isPosZero())
23539       return N->getOperand(0);
23540
23541   // FAND(x, 0.0) -> 0.0
23542   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23543     if (C->getValueAPF().isPosZero())
23544       return N->getOperand(1);
23545
23546   return SDValue();
23547 }
23548
23549 /// Do target-specific dag combines on X86ISD::FANDN nodes
23550 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23551   // FANDN(0.0, x) -> x
23552   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23553     if (C->getValueAPF().isPosZero())
23554       return N->getOperand(1);
23555
23556   // FANDN(x, 0.0) -> 0.0
23557   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23558     if (C->getValueAPF().isPosZero())
23559       return N->getOperand(1);
23560
23561   return SDValue();
23562 }
23563
23564 static SDValue PerformBTCombine(SDNode *N,
23565                                 SelectionDAG &DAG,
23566                                 TargetLowering::DAGCombinerInfo &DCI) {
23567   // BT ignores high bits in the bit index operand.
23568   SDValue Op1 = N->getOperand(1);
23569   if (Op1.hasOneUse()) {
23570     unsigned BitWidth = Op1.getValueSizeInBits();
23571     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23572     APInt KnownZero, KnownOne;
23573     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23574                                           !DCI.isBeforeLegalizeOps());
23575     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23576     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23577         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23578       DCI.CommitTargetLoweringOpt(TLO);
23579   }
23580   return SDValue();
23581 }
23582
23583 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23584   SDValue Op = N->getOperand(0);
23585   if (Op.getOpcode() == ISD::BITCAST)
23586     Op = Op.getOperand(0);
23587   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23588   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23589       VT.getVectorElementType().getSizeInBits() ==
23590       OpVT.getVectorElementType().getSizeInBits()) {
23591     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23592   }
23593   return SDValue();
23594 }
23595
23596 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23597                                                const X86Subtarget *Subtarget) {
23598   EVT VT = N->getValueType(0);
23599   if (!VT.isVector())
23600     return SDValue();
23601
23602   SDValue N0 = N->getOperand(0);
23603   SDValue N1 = N->getOperand(1);
23604   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23605   SDLoc dl(N);
23606
23607   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23608   // both SSE and AVX2 since there is no sign-extended shift right
23609   // operation on a vector with 64-bit elements.
23610   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23611   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23612   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23613       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23614     SDValue N00 = N0.getOperand(0);
23615
23616     // EXTLOAD has a better solution on AVX2,
23617     // it may be replaced with X86ISD::VSEXT node.
23618     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23619       if (!ISD::isNormalLoad(N00.getNode()))
23620         return SDValue();
23621
23622     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23623         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23624                                   N00, N1);
23625       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23626     }
23627   }
23628   return SDValue();
23629 }
23630
23631 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23632                                   TargetLowering::DAGCombinerInfo &DCI,
23633                                   const X86Subtarget *Subtarget) {
23634   SDValue N0 = N->getOperand(0);
23635   EVT VT = N->getValueType(0);
23636
23637   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23638   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23639   // This exposes the sext to the sdivrem lowering, so that it directly extends
23640   // from AH (which we otherwise need to do contortions to access).
23641   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23642       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23643     SDLoc dl(N);
23644     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23645     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23646                             N0.getOperand(0), N0.getOperand(1));
23647     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23648     return R.getValue(1);
23649   }
23650
23651   if (!DCI.isBeforeLegalizeOps())
23652     return SDValue();
23653
23654   if (!Subtarget->hasFp256())
23655     return SDValue();
23656
23657   if (VT.isVector() && VT.getSizeInBits() == 256) {
23658     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23659     if (R.getNode())
23660       return R;
23661   }
23662
23663   return SDValue();
23664 }
23665
23666 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23667                                  const X86Subtarget* Subtarget) {
23668   SDLoc dl(N);
23669   EVT VT = N->getValueType(0);
23670
23671   // Let legalize expand this if it isn't a legal type yet.
23672   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23673     return SDValue();
23674
23675   EVT ScalarVT = VT.getScalarType();
23676   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23677       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23678     return SDValue();
23679
23680   SDValue A = N->getOperand(0);
23681   SDValue B = N->getOperand(1);
23682   SDValue C = N->getOperand(2);
23683
23684   bool NegA = (A.getOpcode() == ISD::FNEG);
23685   bool NegB = (B.getOpcode() == ISD::FNEG);
23686   bool NegC = (C.getOpcode() == ISD::FNEG);
23687
23688   // Negative multiplication when NegA xor NegB
23689   bool NegMul = (NegA != NegB);
23690   if (NegA)
23691     A = A.getOperand(0);
23692   if (NegB)
23693     B = B.getOperand(0);
23694   if (NegC)
23695     C = C.getOperand(0);
23696
23697   unsigned Opcode;
23698   if (!NegMul)
23699     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23700   else
23701     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23702
23703   return DAG.getNode(Opcode, dl, VT, A, B, C);
23704 }
23705
23706 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23707                                   TargetLowering::DAGCombinerInfo &DCI,
23708                                   const X86Subtarget *Subtarget) {
23709   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23710   //           (and (i32 x86isd::setcc_carry), 1)
23711   // This eliminates the zext. This transformation is necessary because
23712   // ISD::SETCC is always legalized to i8.
23713   SDLoc dl(N);
23714   SDValue N0 = N->getOperand(0);
23715   EVT VT = N->getValueType(0);
23716
23717   if (N0.getOpcode() == ISD::AND &&
23718       N0.hasOneUse() &&
23719       N0.getOperand(0).hasOneUse()) {
23720     SDValue N00 = N0.getOperand(0);
23721     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23722       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23723       if (!C || C->getZExtValue() != 1)
23724         return SDValue();
23725       return DAG.getNode(ISD::AND, dl, VT,
23726                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23727                                      N00.getOperand(0), N00.getOperand(1)),
23728                          DAG.getConstant(1, dl, VT));
23729     }
23730   }
23731
23732   if (N0.getOpcode() == ISD::TRUNCATE &&
23733       N0.hasOneUse() &&
23734       N0.getOperand(0).hasOneUse()) {
23735     SDValue N00 = N0.getOperand(0);
23736     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23737       return DAG.getNode(ISD::AND, dl, VT,
23738                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23739                                      N00.getOperand(0), N00.getOperand(1)),
23740                          DAG.getConstant(1, dl, VT));
23741     }
23742   }
23743   if (VT.is256BitVector()) {
23744     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23745     if (R.getNode())
23746       return R;
23747   }
23748
23749   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23750   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23751   // This exposes the zext to the udivrem lowering, so that it directly extends
23752   // from AH (which we otherwise need to do contortions to access).
23753   if (N0.getOpcode() == ISD::UDIVREM &&
23754       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23755       (VT == MVT::i32 || VT == MVT::i64)) {
23756     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23757     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23758                             N0.getOperand(0), N0.getOperand(1));
23759     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23760     return R.getValue(1);
23761   }
23762
23763   return SDValue();
23764 }
23765
23766 // Optimize x == -y --> x+y == 0
23767 //          x != -y --> x+y != 0
23768 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23769                                       const X86Subtarget* Subtarget) {
23770   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23771   SDValue LHS = N->getOperand(0);
23772   SDValue RHS = N->getOperand(1);
23773   EVT VT = N->getValueType(0);
23774   SDLoc DL(N);
23775
23776   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23777     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23778       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23779         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23780                                    LHS.getOperand(1));
23781         return DAG.getSetCC(DL, N->getValueType(0), addV,
23782                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23783       }
23784   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23785     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23786       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23787         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23788                                    RHS.getOperand(1));
23789         return DAG.getSetCC(DL, N->getValueType(0), addV,
23790                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23791       }
23792
23793   if (VT.getScalarType() == MVT::i1 &&
23794       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23795     bool IsSEXT0 =
23796         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23797         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23798     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23799
23800     if (!IsSEXT0 || !IsVZero1) {
23801       // Swap the operands and update the condition code.
23802       std::swap(LHS, RHS);
23803       CC = ISD::getSetCCSwappedOperands(CC);
23804
23805       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23806                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23807       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23808     }
23809
23810     if (IsSEXT0 && IsVZero1) {
23811       assert(VT == LHS.getOperand(0).getValueType() &&
23812              "Uexpected operand type");
23813       if (CC == ISD::SETGT)
23814         return DAG.getConstant(0, DL, VT);
23815       if (CC == ISD::SETLE)
23816         return DAG.getConstant(1, DL, VT);
23817       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23818         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23819
23820       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23821              "Unexpected condition code!");
23822       return LHS.getOperand(0);
23823     }
23824   }
23825
23826   return SDValue();
23827 }
23828
23829 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23830                                          SelectionDAG &DAG) {
23831   SDLoc dl(Load);
23832   MVT VT = Load->getSimpleValueType(0);
23833   MVT EVT = VT.getVectorElementType();
23834   SDValue Addr = Load->getOperand(1);
23835   SDValue NewAddr = DAG.getNode(
23836       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23837       DAG.getConstant(Index * EVT.getStoreSize(), dl,
23838                       Addr.getSimpleValueType()));
23839
23840   SDValue NewLoad =
23841       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23842                   DAG.getMachineFunction().getMachineMemOperand(
23843                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23844   return NewLoad;
23845 }
23846
23847 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23848                                       const X86Subtarget *Subtarget) {
23849   SDLoc dl(N);
23850   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23851   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23852          "X86insertps is only defined for v4x32");
23853
23854   SDValue Ld = N->getOperand(1);
23855   if (MayFoldLoad(Ld)) {
23856     // Extract the countS bits from the immediate so we can get the proper
23857     // address when narrowing the vector load to a specific element.
23858     // When the second source op is a memory address, insertps doesn't use
23859     // countS and just gets an f32 from that address.
23860     unsigned DestIndex =
23861         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23862
23863     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23864
23865     // Create this as a scalar to vector to match the instruction pattern.
23866     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23867     // countS bits are ignored when loading from memory on insertps, which
23868     // means we don't need to explicitly set them to 0.
23869     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23870                        LoadScalarToVector, N->getOperand(2));
23871   }
23872   return SDValue();
23873 }
23874
23875 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23876   SDValue V0 = N->getOperand(0);
23877   SDValue V1 = N->getOperand(1);
23878   SDLoc DL(N);
23879   EVT VT = N->getValueType(0);
23880
23881   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23882   // operands and changing the mask to 1. This saves us a bunch of
23883   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23884   // x86InstrInfo knows how to commute this back after instruction selection
23885   // if it would help register allocation.
23886
23887   // TODO: If optimizing for size or a processor that doesn't suffer from
23888   // partial register update stalls, this should be transformed into a MOVSD
23889   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23890
23891   if (VT == MVT::v2f64)
23892     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23893       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23894         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23895         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23896       }
23897
23898   return SDValue();
23899 }
23900
23901 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23902 // as "sbb reg,reg", since it can be extended without zext and produces
23903 // an all-ones bit which is more useful than 0/1 in some cases.
23904 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23905                                MVT VT) {
23906   if (VT == MVT::i8)
23907     return DAG.getNode(ISD::AND, DL, VT,
23908                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23909                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
23910                                    EFLAGS),
23911                        DAG.getConstant(1, DL, VT));
23912   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23913   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23914                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23915                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
23916                                  EFLAGS));
23917 }
23918
23919 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23920 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23921                                    TargetLowering::DAGCombinerInfo &DCI,
23922                                    const X86Subtarget *Subtarget) {
23923   SDLoc DL(N);
23924   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23925   SDValue EFLAGS = N->getOperand(1);
23926
23927   if (CC == X86::COND_A) {
23928     // Try to convert COND_A into COND_B in an attempt to facilitate
23929     // materializing "setb reg".
23930     //
23931     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23932     // cannot take an immediate as its first operand.
23933     //
23934     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23935         EFLAGS.getValueType().isInteger() &&
23936         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23937       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23938                                    EFLAGS.getNode()->getVTList(),
23939                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23940       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23941       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23942     }
23943   }
23944
23945   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23946   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23947   // cases.
23948   if (CC == X86::COND_B)
23949     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23950
23951   SDValue Flags;
23952
23953   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23954   if (Flags.getNode()) {
23955     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23956     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23957   }
23958
23959   return SDValue();
23960 }
23961
23962 // Optimize branch condition evaluation.
23963 //
23964 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23965                                     TargetLowering::DAGCombinerInfo &DCI,
23966                                     const X86Subtarget *Subtarget) {
23967   SDLoc DL(N);
23968   SDValue Chain = N->getOperand(0);
23969   SDValue Dest = N->getOperand(1);
23970   SDValue EFLAGS = N->getOperand(3);
23971   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23972
23973   SDValue Flags;
23974
23975   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23976   if (Flags.getNode()) {
23977     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23978     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23979                        Flags);
23980   }
23981
23982   return SDValue();
23983 }
23984
23985 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23986                                                          SelectionDAG &DAG) {
23987   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23988   // optimize away operation when it's from a constant.
23989   //
23990   // The general transformation is:
23991   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23992   //       AND(VECTOR_CMP(x,y), constant2)
23993   //    constant2 = UNARYOP(constant)
23994
23995   // Early exit if this isn't a vector operation, the operand of the
23996   // unary operation isn't a bitwise AND, or if the sizes of the operations
23997   // aren't the same.
23998   EVT VT = N->getValueType(0);
23999   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24000       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24001       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24002     return SDValue();
24003
24004   // Now check that the other operand of the AND is a constant. We could
24005   // make the transformation for non-constant splats as well, but it's unclear
24006   // that would be a benefit as it would not eliminate any operations, just
24007   // perform one more step in scalar code before moving to the vector unit.
24008   if (BuildVectorSDNode *BV =
24009           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24010     // Bail out if the vector isn't a constant.
24011     if (!BV->isConstant())
24012       return SDValue();
24013
24014     // Everything checks out. Build up the new and improved node.
24015     SDLoc DL(N);
24016     EVT IntVT = BV->getValueType(0);
24017     // Create a new constant of the appropriate type for the transformed
24018     // DAG.
24019     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24020     // The AND node needs bitcasts to/from an integer vector type around it.
24021     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24022     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24023                                  N->getOperand(0)->getOperand(0), MaskConst);
24024     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24025     return Res;
24026   }
24027
24028   return SDValue();
24029 }
24030
24031 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24032                                         const X86Subtarget *Subtarget) {
24033   // First try to optimize away the conversion entirely when it's
24034   // conditionally from a constant. Vectors only.
24035   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24036   if (Res != SDValue())
24037     return Res;
24038
24039   // Now move on to more general possibilities.
24040   SDValue Op0 = N->getOperand(0);
24041   EVT InVT = Op0->getValueType(0);
24042
24043   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24044   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24045     SDLoc dl(N);
24046     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24047     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24048     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24049   }
24050
24051   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24052   // a 32-bit target where SSE doesn't support i64->FP operations.
24053   if (Op0.getOpcode() == ISD::LOAD) {
24054     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24055     EVT VT = Ld->getValueType(0);
24056
24057     // This transformation is not supported if the result type is f16
24058     if (N->getValueType(0) == MVT::f16)
24059       return SDValue();
24060
24061     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24062         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24063         !Subtarget->is64Bit() && VT == MVT::i64) {
24064       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24065           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24066       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24067       return FILDChain;
24068     }
24069   }
24070   return SDValue();
24071 }
24072
24073 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24074 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24075                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24076   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24077   // the result is either zero or one (depending on the input carry bit).
24078   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24079   if (X86::isZeroNode(N->getOperand(0)) &&
24080       X86::isZeroNode(N->getOperand(1)) &&
24081       // We don't have a good way to replace an EFLAGS use, so only do this when
24082       // dead right now.
24083       SDValue(N, 1).use_empty()) {
24084     SDLoc DL(N);
24085     EVT VT = N->getValueType(0);
24086     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24087     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24088                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24089                                            DAG.getConstant(X86::COND_B, DL,
24090                                                            MVT::i8),
24091                                            N->getOperand(2)),
24092                                DAG.getConstant(1, DL, VT));
24093     return DCI.CombineTo(N, Res1, CarryOut);
24094   }
24095
24096   return SDValue();
24097 }
24098
24099 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24100 //      (add Y, (setne X, 0)) -> sbb -1, Y
24101 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24102 //      (sub (setne X, 0), Y) -> adc -1, Y
24103 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24104   SDLoc DL(N);
24105
24106   // Look through ZExts.
24107   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24108   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24109     return SDValue();
24110
24111   SDValue SetCC = Ext.getOperand(0);
24112   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24113     return SDValue();
24114
24115   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24116   if (CC != X86::COND_E && CC != X86::COND_NE)
24117     return SDValue();
24118
24119   SDValue Cmp = SetCC.getOperand(1);
24120   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24121       !X86::isZeroNode(Cmp.getOperand(1)) ||
24122       !Cmp.getOperand(0).getValueType().isInteger())
24123     return SDValue();
24124
24125   SDValue CmpOp0 = Cmp.getOperand(0);
24126   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24127                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24128
24129   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24130   if (CC == X86::COND_NE)
24131     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24132                        DL, OtherVal.getValueType(), OtherVal,
24133                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24134                        NewCmp);
24135   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24136                      DL, OtherVal.getValueType(), OtherVal,
24137                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24138 }
24139
24140 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24141 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24142                                  const X86Subtarget *Subtarget) {
24143   EVT VT = N->getValueType(0);
24144   SDValue Op0 = N->getOperand(0);
24145   SDValue Op1 = N->getOperand(1);
24146
24147   // Try to synthesize horizontal adds from adds of shuffles.
24148   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24149        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24150       isHorizontalBinOp(Op0, Op1, true))
24151     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24152
24153   return OptimizeConditionalInDecrement(N, DAG);
24154 }
24155
24156 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24157                                  const X86Subtarget *Subtarget) {
24158   SDValue Op0 = N->getOperand(0);
24159   SDValue Op1 = N->getOperand(1);
24160
24161   // X86 can't encode an immediate LHS of a sub. See if we can push the
24162   // negation into a preceding instruction.
24163   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24164     // If the RHS of the sub is a XOR with one use and a constant, invert the
24165     // immediate. Then add one to the LHS of the sub so we can turn
24166     // X-Y -> X+~Y+1, saving one register.
24167     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24168         isa<ConstantSDNode>(Op1.getOperand(1))) {
24169       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24170       EVT VT = Op0.getValueType();
24171       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24172                                    Op1.getOperand(0),
24173                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24174       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24175                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24176     }
24177   }
24178
24179   // Try to synthesize horizontal adds from adds of shuffles.
24180   EVT VT = N->getValueType(0);
24181   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24182        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24183       isHorizontalBinOp(Op0, Op1, true))
24184     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24185
24186   return OptimizeConditionalInDecrement(N, DAG);
24187 }
24188
24189 /// performVZEXTCombine - Performs build vector combines
24190 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24191                                    TargetLowering::DAGCombinerInfo &DCI,
24192                                    const X86Subtarget *Subtarget) {
24193   SDLoc DL(N);
24194   MVT VT = N->getSimpleValueType(0);
24195   SDValue Op = N->getOperand(0);
24196   MVT OpVT = Op.getSimpleValueType();
24197   MVT OpEltVT = OpVT.getVectorElementType();
24198   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24199
24200   // (vzext (bitcast (vzext (x)) -> (vzext x)
24201   SDValue V = Op;
24202   while (V.getOpcode() == ISD::BITCAST)
24203     V = V.getOperand(0);
24204
24205   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24206     MVT InnerVT = V.getSimpleValueType();
24207     MVT InnerEltVT = InnerVT.getVectorElementType();
24208
24209     // If the element sizes match exactly, we can just do one larger vzext. This
24210     // is always an exact type match as vzext operates on integer types.
24211     if (OpEltVT == InnerEltVT) {
24212       assert(OpVT == InnerVT && "Types must match for vzext!");
24213       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24214     }
24215
24216     // The only other way we can combine them is if only a single element of the
24217     // inner vzext is used in the input to the outer vzext.
24218     if (InnerEltVT.getSizeInBits() < InputBits)
24219       return SDValue();
24220
24221     // In this case, the inner vzext is completely dead because we're going to
24222     // only look at bits inside of the low element. Just do the outer vzext on
24223     // a bitcast of the input to the inner.
24224     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24225                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24226   }
24227
24228   // Check if we can bypass extracting and re-inserting an element of an input
24229   // vector. Essentialy:
24230   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24231   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24232       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24233       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24234     SDValue ExtractedV = V.getOperand(0);
24235     SDValue OrigV = ExtractedV.getOperand(0);
24236     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24237       if (ExtractIdx->getZExtValue() == 0) {
24238         MVT OrigVT = OrigV.getSimpleValueType();
24239         // Extract a subvector if necessary...
24240         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24241           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24242           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24243                                     OrigVT.getVectorNumElements() / Ratio);
24244           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24245                               DAG.getIntPtrConstant(0, DL));
24246         }
24247         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24248         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24249       }
24250   }
24251
24252   return SDValue();
24253 }
24254
24255 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24256                                              DAGCombinerInfo &DCI) const {
24257   SelectionDAG &DAG = DCI.DAG;
24258   switch (N->getOpcode()) {
24259   default: break;
24260   case ISD::EXTRACT_VECTOR_ELT:
24261     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24262   case ISD::VSELECT:
24263   case ISD::SELECT:
24264   case X86ISD::SHRUNKBLEND:
24265     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24266   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24267   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24268   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24269   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24270   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24271   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24272   case ISD::SHL:
24273   case ISD::SRA:
24274   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24275   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24276   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24277   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24278   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24279   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24280   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24281   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24282   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24283   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24284   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24285   case X86ISD::FXOR:
24286   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24287   case X86ISD::FMIN:
24288   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24289   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24290   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24291   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24292   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24293   case ISD::ANY_EXTEND:
24294   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24295   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24296   case ISD::SIGN_EXTEND_INREG:
24297     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24298   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24299   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24300   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24301   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24302   case X86ISD::SHUFP:       // Handle all target specific shuffles
24303   case X86ISD::PALIGNR:
24304   case X86ISD::UNPCKH:
24305   case X86ISD::UNPCKL:
24306   case X86ISD::MOVHLPS:
24307   case X86ISD::MOVLHPS:
24308   case X86ISD::PSHUFB:
24309   case X86ISD::PSHUFD:
24310   case X86ISD::PSHUFHW:
24311   case X86ISD::PSHUFLW:
24312   case X86ISD::MOVSS:
24313   case X86ISD::MOVSD:
24314   case X86ISD::VPERMILPI:
24315   case X86ISD::VPERM2X128:
24316   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24317   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24318   case ISD::INTRINSIC_WO_CHAIN:
24319     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24320   case X86ISD::INSERTPS: {
24321     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24322       return PerformINSERTPSCombine(N, DAG, Subtarget);
24323     break;
24324   }
24325   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24326   }
24327
24328   return SDValue();
24329 }
24330
24331 /// isTypeDesirableForOp - Return true if the target has native support for
24332 /// the specified value type and it is 'desirable' to use the type for the
24333 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24334 /// instruction encodings are longer and some i16 instructions are slow.
24335 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24336   if (!isTypeLegal(VT))
24337     return false;
24338   if (VT != MVT::i16)
24339     return true;
24340
24341   switch (Opc) {
24342   default:
24343     return true;
24344   case ISD::LOAD:
24345   case ISD::SIGN_EXTEND:
24346   case ISD::ZERO_EXTEND:
24347   case ISD::ANY_EXTEND:
24348   case ISD::SHL:
24349   case ISD::SRL:
24350   case ISD::SUB:
24351   case ISD::ADD:
24352   case ISD::MUL:
24353   case ISD::AND:
24354   case ISD::OR:
24355   case ISD::XOR:
24356     return false;
24357   }
24358 }
24359
24360 /// IsDesirableToPromoteOp - This method query the target whether it is
24361 /// beneficial for dag combiner to promote the specified node. If true, it
24362 /// should return the desired promotion type by reference.
24363 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24364   EVT VT = Op.getValueType();
24365   if (VT != MVT::i16)
24366     return false;
24367
24368   bool Promote = false;
24369   bool Commute = false;
24370   switch (Op.getOpcode()) {
24371   default: break;
24372   case ISD::LOAD: {
24373     LoadSDNode *LD = cast<LoadSDNode>(Op);
24374     // If the non-extending load has a single use and it's not live out, then it
24375     // might be folded.
24376     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24377                                                      Op.hasOneUse()*/) {
24378       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24379              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24380         // The only case where we'd want to promote LOAD (rather then it being
24381         // promoted as an operand is when it's only use is liveout.
24382         if (UI->getOpcode() != ISD::CopyToReg)
24383           return false;
24384       }
24385     }
24386     Promote = true;
24387     break;
24388   }
24389   case ISD::SIGN_EXTEND:
24390   case ISD::ZERO_EXTEND:
24391   case ISD::ANY_EXTEND:
24392     Promote = true;
24393     break;
24394   case ISD::SHL:
24395   case ISD::SRL: {
24396     SDValue N0 = Op.getOperand(0);
24397     // Look out for (store (shl (load), x)).
24398     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24399       return false;
24400     Promote = true;
24401     break;
24402   }
24403   case ISD::ADD:
24404   case ISD::MUL:
24405   case ISD::AND:
24406   case ISD::OR:
24407   case ISD::XOR:
24408     Commute = true;
24409     // fallthrough
24410   case ISD::SUB: {
24411     SDValue N0 = Op.getOperand(0);
24412     SDValue N1 = Op.getOperand(1);
24413     if (!Commute && MayFoldLoad(N1))
24414       return false;
24415     // Avoid disabling potential load folding opportunities.
24416     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24417       return false;
24418     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24419       return false;
24420     Promote = true;
24421   }
24422   }
24423
24424   PVT = MVT::i32;
24425   return Promote;
24426 }
24427
24428 //===----------------------------------------------------------------------===//
24429 //                           X86 Inline Assembly Support
24430 //===----------------------------------------------------------------------===//
24431
24432 // Helper to match a string separated by whitespace.
24433 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24434   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24435
24436   for (StringRef Piece : Pieces) {
24437     if (!S.startswith(Piece)) // Check if the piece matches.
24438       return false;
24439
24440     S = S.substr(Piece.size());
24441     StringRef::size_type Pos = S.find_first_not_of(" \t");
24442     if (Pos == 0) // We matched a prefix.
24443       return false;
24444
24445     S = S.substr(Pos);
24446   }
24447
24448   return S.empty();
24449 }
24450
24451 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24452
24453   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24454     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24455         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24456         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24457
24458       if (AsmPieces.size() == 3)
24459         return true;
24460       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24461         return true;
24462     }
24463   }
24464   return false;
24465 }
24466
24467 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24468   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24469
24470   std::string AsmStr = IA->getAsmString();
24471
24472   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24473   if (!Ty || Ty->getBitWidth() % 16 != 0)
24474     return false;
24475
24476   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24477   SmallVector<StringRef, 4> AsmPieces;
24478   SplitString(AsmStr, AsmPieces, ";\n");
24479
24480   switch (AsmPieces.size()) {
24481   default: return false;
24482   case 1:
24483     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24484     // we will turn this bswap into something that will be lowered to logical
24485     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24486     // lower so don't worry about this.
24487     // bswap $0
24488     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24489         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24490         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24491         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24492         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24493         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24494       // No need to check constraints, nothing other than the equivalent of
24495       // "=r,0" would be valid here.
24496       return IntrinsicLowering::LowerToByteSwap(CI);
24497     }
24498
24499     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24500     if (CI->getType()->isIntegerTy(16) &&
24501         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24502         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24503          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24504       AsmPieces.clear();
24505       const std::string &ConstraintsStr = IA->getConstraintString();
24506       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24507       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24508       if (clobbersFlagRegisters(AsmPieces))
24509         return IntrinsicLowering::LowerToByteSwap(CI);
24510     }
24511     break;
24512   case 3:
24513     if (CI->getType()->isIntegerTy(32) &&
24514         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24515         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24516         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24517         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24518       AsmPieces.clear();
24519       const std::string &ConstraintsStr = IA->getConstraintString();
24520       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24521       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24522       if (clobbersFlagRegisters(AsmPieces))
24523         return IntrinsicLowering::LowerToByteSwap(CI);
24524     }
24525
24526     if (CI->getType()->isIntegerTy(64)) {
24527       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24528       if (Constraints.size() >= 2 &&
24529           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24530           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24531         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24532         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24533             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24534             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24535           return IntrinsicLowering::LowerToByteSwap(CI);
24536       }
24537     }
24538     break;
24539   }
24540   return false;
24541 }
24542
24543 /// getConstraintType - Given a constraint letter, return the type of
24544 /// constraint it is for this target.
24545 X86TargetLowering::ConstraintType
24546 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24547   if (Constraint.size() == 1) {
24548     switch (Constraint[0]) {
24549     case 'R':
24550     case 'q':
24551     case 'Q':
24552     case 'f':
24553     case 't':
24554     case 'u':
24555     case 'y':
24556     case 'x':
24557     case 'Y':
24558     case 'l':
24559       return C_RegisterClass;
24560     case 'a':
24561     case 'b':
24562     case 'c':
24563     case 'd':
24564     case 'S':
24565     case 'D':
24566     case 'A':
24567       return C_Register;
24568     case 'I':
24569     case 'J':
24570     case 'K':
24571     case 'L':
24572     case 'M':
24573     case 'N':
24574     case 'G':
24575     case 'C':
24576     case 'e':
24577     case 'Z':
24578       return C_Other;
24579     default:
24580       break;
24581     }
24582   }
24583   return TargetLowering::getConstraintType(Constraint);
24584 }
24585
24586 /// Examine constraint type and operand type and determine a weight value.
24587 /// This object must already have been set up with the operand type
24588 /// and the current alternative constraint selected.
24589 TargetLowering::ConstraintWeight
24590   X86TargetLowering::getSingleConstraintMatchWeight(
24591     AsmOperandInfo &info, const char *constraint) const {
24592   ConstraintWeight weight = CW_Invalid;
24593   Value *CallOperandVal = info.CallOperandVal;
24594     // If we don't have a value, we can't do a match,
24595     // but allow it at the lowest weight.
24596   if (!CallOperandVal)
24597     return CW_Default;
24598   Type *type = CallOperandVal->getType();
24599   // Look at the constraint type.
24600   switch (*constraint) {
24601   default:
24602     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24603   case 'R':
24604   case 'q':
24605   case 'Q':
24606   case 'a':
24607   case 'b':
24608   case 'c':
24609   case 'd':
24610   case 'S':
24611   case 'D':
24612   case 'A':
24613     if (CallOperandVal->getType()->isIntegerTy())
24614       weight = CW_SpecificReg;
24615     break;
24616   case 'f':
24617   case 't':
24618   case 'u':
24619     if (type->isFloatingPointTy())
24620       weight = CW_SpecificReg;
24621     break;
24622   case 'y':
24623     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24624       weight = CW_SpecificReg;
24625     break;
24626   case 'x':
24627   case 'Y':
24628     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24629         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24630       weight = CW_Register;
24631     break;
24632   case 'I':
24633     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24634       if (C->getZExtValue() <= 31)
24635         weight = CW_Constant;
24636     }
24637     break;
24638   case 'J':
24639     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24640       if (C->getZExtValue() <= 63)
24641         weight = CW_Constant;
24642     }
24643     break;
24644   case 'K':
24645     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24646       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24647         weight = CW_Constant;
24648     }
24649     break;
24650   case 'L':
24651     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24652       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24653         weight = CW_Constant;
24654     }
24655     break;
24656   case 'M':
24657     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24658       if (C->getZExtValue() <= 3)
24659         weight = CW_Constant;
24660     }
24661     break;
24662   case 'N':
24663     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24664       if (C->getZExtValue() <= 0xff)
24665         weight = CW_Constant;
24666     }
24667     break;
24668   case 'G':
24669   case 'C':
24670     if (isa<ConstantFP>(CallOperandVal)) {
24671       weight = CW_Constant;
24672     }
24673     break;
24674   case 'e':
24675     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24676       if ((C->getSExtValue() >= -0x80000000LL) &&
24677           (C->getSExtValue() <= 0x7fffffffLL))
24678         weight = CW_Constant;
24679     }
24680     break;
24681   case 'Z':
24682     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24683       if (C->getZExtValue() <= 0xffffffff)
24684         weight = CW_Constant;
24685     }
24686     break;
24687   }
24688   return weight;
24689 }
24690
24691 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24692 /// with another that has more specific requirements based on the type of the
24693 /// corresponding operand.
24694 const char *X86TargetLowering::
24695 LowerXConstraint(EVT ConstraintVT) const {
24696   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24697   // 'f' like normal targets.
24698   if (ConstraintVT.isFloatingPoint()) {
24699     if (Subtarget->hasSSE2())
24700       return "Y";
24701     if (Subtarget->hasSSE1())
24702       return "x";
24703   }
24704
24705   return TargetLowering::LowerXConstraint(ConstraintVT);
24706 }
24707
24708 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24709 /// vector.  If it is invalid, don't add anything to Ops.
24710 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24711                                                      std::string &Constraint,
24712                                                      std::vector<SDValue>&Ops,
24713                                                      SelectionDAG &DAG) const {
24714   SDValue Result;
24715
24716   // Only support length 1 constraints for now.
24717   if (Constraint.length() > 1) return;
24718
24719   char ConstraintLetter = Constraint[0];
24720   switch (ConstraintLetter) {
24721   default: break;
24722   case 'I':
24723     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24724       if (C->getZExtValue() <= 31) {
24725         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24726                                        Op.getValueType());
24727         break;
24728       }
24729     }
24730     return;
24731   case 'J':
24732     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24733       if (C->getZExtValue() <= 63) {
24734         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24735                                        Op.getValueType());
24736         break;
24737       }
24738     }
24739     return;
24740   case 'K':
24741     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24742       if (isInt<8>(C->getSExtValue())) {
24743         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24744                                        Op.getValueType());
24745         break;
24746       }
24747     }
24748     return;
24749   case 'L':
24750     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24751       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24752           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24753         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24754                                        Op.getValueType());
24755         break;
24756       }
24757     }
24758     return;
24759   case 'M':
24760     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24761       if (C->getZExtValue() <= 3) {
24762         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24763                                        Op.getValueType());
24764         break;
24765       }
24766     }
24767     return;
24768   case 'N':
24769     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24770       if (C->getZExtValue() <= 255) {
24771         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24772                                        Op.getValueType());
24773         break;
24774       }
24775     }
24776     return;
24777   case 'O':
24778     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24779       if (C->getZExtValue() <= 127) {
24780         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24781                                        Op.getValueType());
24782         break;
24783       }
24784     }
24785     return;
24786   case 'e': {
24787     // 32-bit signed value
24788     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24789       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24790                                            C->getSExtValue())) {
24791         // Widen to 64 bits here to get it sign extended.
24792         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24793         break;
24794       }
24795     // FIXME gcc accepts some relocatable values here too, but only in certain
24796     // memory models; it's complicated.
24797     }
24798     return;
24799   }
24800   case 'Z': {
24801     // 32-bit unsigned value
24802     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24803       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24804                                            C->getZExtValue())) {
24805         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24806                                        Op.getValueType());
24807         break;
24808       }
24809     }
24810     // FIXME gcc accepts some relocatable values here too, but only in certain
24811     // memory models; it's complicated.
24812     return;
24813   }
24814   case 'i': {
24815     // Literal immediates are always ok.
24816     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24817       // Widen to 64 bits here to get it sign extended.
24818       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24819       break;
24820     }
24821
24822     // In any sort of PIC mode addresses need to be computed at runtime by
24823     // adding in a register or some sort of table lookup.  These can't
24824     // be used as immediates.
24825     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24826       return;
24827
24828     // If we are in non-pic codegen mode, we allow the address of a global (with
24829     // an optional displacement) to be used with 'i'.
24830     GlobalAddressSDNode *GA = nullptr;
24831     int64_t Offset = 0;
24832
24833     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24834     while (1) {
24835       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24836         Offset += GA->getOffset();
24837         break;
24838       } else if (Op.getOpcode() == ISD::ADD) {
24839         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24840           Offset += C->getZExtValue();
24841           Op = Op.getOperand(0);
24842           continue;
24843         }
24844       } else if (Op.getOpcode() == ISD::SUB) {
24845         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24846           Offset += -C->getZExtValue();
24847           Op = Op.getOperand(0);
24848           continue;
24849         }
24850       }
24851
24852       // Otherwise, this isn't something we can handle, reject it.
24853       return;
24854     }
24855
24856     const GlobalValue *GV = GA->getGlobal();
24857     // If we require an extra load to get this address, as in PIC mode, we
24858     // can't accept it.
24859     if (isGlobalStubReference(
24860             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24861       return;
24862
24863     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24864                                         GA->getValueType(0), Offset);
24865     break;
24866   }
24867   }
24868
24869   if (Result.getNode()) {
24870     Ops.push_back(Result);
24871     return;
24872   }
24873   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24874 }
24875
24876 std::pair<unsigned, const TargetRegisterClass *>
24877 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24878                                                 const std::string &Constraint,
24879                                                 MVT VT) const {
24880   // First, see if this is a constraint that directly corresponds to an LLVM
24881   // register class.
24882   if (Constraint.size() == 1) {
24883     // GCC Constraint Letters
24884     switch (Constraint[0]) {
24885     default: break;
24886       // TODO: Slight differences here in allocation order and leaving
24887       // RIP in the class. Do they matter any more here than they do
24888       // in the normal allocation?
24889     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24890       if (Subtarget->is64Bit()) {
24891         if (VT == MVT::i32 || VT == MVT::f32)
24892           return std::make_pair(0U, &X86::GR32RegClass);
24893         if (VT == MVT::i16)
24894           return std::make_pair(0U, &X86::GR16RegClass);
24895         if (VT == MVT::i8 || VT == MVT::i1)
24896           return std::make_pair(0U, &X86::GR8RegClass);
24897         if (VT == MVT::i64 || VT == MVT::f64)
24898           return std::make_pair(0U, &X86::GR64RegClass);
24899         break;
24900       }
24901       // 32-bit fallthrough
24902     case 'Q':   // Q_REGS
24903       if (VT == MVT::i32 || VT == MVT::f32)
24904         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24905       if (VT == MVT::i16)
24906         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24907       if (VT == MVT::i8 || VT == MVT::i1)
24908         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24909       if (VT == MVT::i64)
24910         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24911       break;
24912     case 'r':   // GENERAL_REGS
24913     case 'l':   // INDEX_REGS
24914       if (VT == MVT::i8 || VT == MVT::i1)
24915         return std::make_pair(0U, &X86::GR8RegClass);
24916       if (VT == MVT::i16)
24917         return std::make_pair(0U, &X86::GR16RegClass);
24918       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24919         return std::make_pair(0U, &X86::GR32RegClass);
24920       return std::make_pair(0U, &X86::GR64RegClass);
24921     case 'R':   // LEGACY_REGS
24922       if (VT == MVT::i8 || VT == MVT::i1)
24923         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24924       if (VT == MVT::i16)
24925         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24926       if (VT == MVT::i32 || !Subtarget->is64Bit())
24927         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24928       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24929     case 'f':  // FP Stack registers.
24930       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24931       // value to the correct fpstack register class.
24932       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24933         return std::make_pair(0U, &X86::RFP32RegClass);
24934       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24935         return std::make_pair(0U, &X86::RFP64RegClass);
24936       return std::make_pair(0U, &X86::RFP80RegClass);
24937     case 'y':   // MMX_REGS if MMX allowed.
24938       if (!Subtarget->hasMMX()) break;
24939       return std::make_pair(0U, &X86::VR64RegClass);
24940     case 'Y':   // SSE_REGS if SSE2 allowed
24941       if (!Subtarget->hasSSE2()) break;
24942       // FALL THROUGH.
24943     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24944       if (!Subtarget->hasSSE1()) break;
24945
24946       switch (VT.SimpleTy) {
24947       default: break;
24948       // Scalar SSE types.
24949       case MVT::f32:
24950       case MVT::i32:
24951         return std::make_pair(0U, &X86::FR32RegClass);
24952       case MVT::f64:
24953       case MVT::i64:
24954         return std::make_pair(0U, &X86::FR64RegClass);
24955       // Vector types.
24956       case MVT::v16i8:
24957       case MVT::v8i16:
24958       case MVT::v4i32:
24959       case MVT::v2i64:
24960       case MVT::v4f32:
24961       case MVT::v2f64:
24962         return std::make_pair(0U, &X86::VR128RegClass);
24963       // AVX types.
24964       case MVT::v32i8:
24965       case MVT::v16i16:
24966       case MVT::v8i32:
24967       case MVT::v4i64:
24968       case MVT::v8f32:
24969       case MVT::v4f64:
24970         return std::make_pair(0U, &X86::VR256RegClass);
24971       case MVT::v8f64:
24972       case MVT::v16f32:
24973       case MVT::v16i32:
24974       case MVT::v8i64:
24975         return std::make_pair(0U, &X86::VR512RegClass);
24976       }
24977       break;
24978     }
24979   }
24980
24981   // Use the default implementation in TargetLowering to convert the register
24982   // constraint into a member of a register class.
24983   std::pair<unsigned, const TargetRegisterClass*> Res;
24984   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24985
24986   // Not found as a standard register?
24987   if (!Res.second) {
24988     // Map st(0) -> st(7) -> ST0
24989     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24990         tolower(Constraint[1]) == 's' &&
24991         tolower(Constraint[2]) == 't' &&
24992         Constraint[3] == '(' &&
24993         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24994         Constraint[5] == ')' &&
24995         Constraint[6] == '}') {
24996
24997       Res.first = X86::FP0+Constraint[4]-'0';
24998       Res.second = &X86::RFP80RegClass;
24999       return Res;
25000     }
25001
25002     // GCC allows "st(0)" to be called just plain "st".
25003     if (StringRef("{st}").equals_lower(Constraint)) {
25004       Res.first = X86::FP0;
25005       Res.second = &X86::RFP80RegClass;
25006       return Res;
25007     }
25008
25009     // flags -> EFLAGS
25010     if (StringRef("{flags}").equals_lower(Constraint)) {
25011       Res.first = X86::EFLAGS;
25012       Res.second = &X86::CCRRegClass;
25013       return Res;
25014     }
25015
25016     // 'A' means EAX + EDX.
25017     if (Constraint == "A") {
25018       Res.first = X86::EAX;
25019       Res.second = &X86::GR32_ADRegClass;
25020       return Res;
25021     }
25022     return Res;
25023   }
25024
25025   // Otherwise, check to see if this is a register class of the wrong value
25026   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25027   // turn into {ax},{dx}.
25028   if (Res.second->hasType(VT))
25029     return Res;   // Correct type already, nothing to do.
25030
25031   // All of the single-register GCC register classes map their values onto
25032   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25033   // really want an 8-bit or 32-bit register, map to the appropriate register
25034   // class and return the appropriate register.
25035   if (Res.second == &X86::GR16RegClass) {
25036     if (VT == MVT::i8 || VT == MVT::i1) {
25037       unsigned DestReg = 0;
25038       switch (Res.first) {
25039       default: break;
25040       case X86::AX: DestReg = X86::AL; break;
25041       case X86::DX: DestReg = X86::DL; break;
25042       case X86::CX: DestReg = X86::CL; break;
25043       case X86::BX: DestReg = X86::BL; break;
25044       }
25045       if (DestReg) {
25046         Res.first = DestReg;
25047         Res.second = &X86::GR8RegClass;
25048       }
25049     } else if (VT == MVT::i32 || VT == MVT::f32) {
25050       unsigned DestReg = 0;
25051       switch (Res.first) {
25052       default: break;
25053       case X86::AX: DestReg = X86::EAX; break;
25054       case X86::DX: DestReg = X86::EDX; break;
25055       case X86::CX: DestReg = X86::ECX; break;
25056       case X86::BX: DestReg = X86::EBX; break;
25057       case X86::SI: DestReg = X86::ESI; break;
25058       case X86::DI: DestReg = X86::EDI; break;
25059       case X86::BP: DestReg = X86::EBP; break;
25060       case X86::SP: DestReg = X86::ESP; break;
25061       }
25062       if (DestReg) {
25063         Res.first = DestReg;
25064         Res.second = &X86::GR32RegClass;
25065       }
25066     } else if (VT == MVT::i64 || VT == MVT::f64) {
25067       unsigned DestReg = 0;
25068       switch (Res.first) {
25069       default: break;
25070       case X86::AX: DestReg = X86::RAX; break;
25071       case X86::DX: DestReg = X86::RDX; break;
25072       case X86::CX: DestReg = X86::RCX; break;
25073       case X86::BX: DestReg = X86::RBX; break;
25074       case X86::SI: DestReg = X86::RSI; break;
25075       case X86::DI: DestReg = X86::RDI; break;
25076       case X86::BP: DestReg = X86::RBP; break;
25077       case X86::SP: DestReg = X86::RSP; break;
25078       }
25079       if (DestReg) {
25080         Res.first = DestReg;
25081         Res.second = &X86::GR64RegClass;
25082       }
25083     }
25084   } else if (Res.second == &X86::FR32RegClass ||
25085              Res.second == &X86::FR64RegClass ||
25086              Res.second == &X86::VR128RegClass ||
25087              Res.second == &X86::VR256RegClass ||
25088              Res.second == &X86::FR32XRegClass ||
25089              Res.second == &X86::FR64XRegClass ||
25090              Res.second == &X86::VR128XRegClass ||
25091              Res.second == &X86::VR256XRegClass ||
25092              Res.second == &X86::VR512RegClass) {
25093     // Handle references to XMM physical registers that got mapped into the
25094     // wrong class.  This can happen with constraints like {xmm0} where the
25095     // target independent register mapper will just pick the first match it can
25096     // find, ignoring the required type.
25097
25098     if (VT == MVT::f32 || VT == MVT::i32)
25099       Res.second = &X86::FR32RegClass;
25100     else if (VT == MVT::f64 || VT == MVT::i64)
25101       Res.second = &X86::FR64RegClass;
25102     else if (X86::VR128RegClass.hasType(VT))
25103       Res.second = &X86::VR128RegClass;
25104     else if (X86::VR256RegClass.hasType(VT))
25105       Res.second = &X86::VR256RegClass;
25106     else if (X86::VR512RegClass.hasType(VT))
25107       Res.second = &X86::VR512RegClass;
25108   }
25109
25110   return Res;
25111 }
25112
25113 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25114                                             Type *Ty) const {
25115   // Scaling factors are not free at all.
25116   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25117   // will take 2 allocations in the out of order engine instead of 1
25118   // for plain addressing mode, i.e. inst (reg1).
25119   // E.g.,
25120   // vaddps (%rsi,%drx), %ymm0, %ymm1
25121   // Requires two allocations (one for the load, one for the computation)
25122   // whereas:
25123   // vaddps (%rsi), %ymm0, %ymm1
25124   // Requires just 1 allocation, i.e., freeing allocations for other operations
25125   // and having less micro operations to execute.
25126   //
25127   // For some X86 architectures, this is even worse because for instance for
25128   // stores, the complex addressing mode forces the instruction to use the
25129   // "load" ports instead of the dedicated "store" port.
25130   // E.g., on Haswell:
25131   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25132   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25133   if (isLegalAddressingMode(AM, Ty))
25134     // Scale represents reg2 * scale, thus account for 1
25135     // as soon as we use a second register.
25136     return AM.Scale != 0;
25137   return -1;
25138 }
25139
25140 bool X86TargetLowering::isTargetFTOL() const {
25141   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25142 }