fixed compilation warning/error
[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     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1511     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1512   }
1513
1514   // We want to custom lower some of our intrinsics.
1515   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1516   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1517   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1518   if (!Subtarget->is64Bit())
1519     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1520
1521   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1522   // handle type legalization for these operations here.
1523   //
1524   // FIXME: We really should do custom legalization for addition and
1525   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1526   // than generic legalization for 64-bit multiplication-with-overflow, though.
1527   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1528     // Add/Sub/Mul with overflow operations are custom lowered.
1529     MVT VT = IntVTs[i];
1530     setOperationAction(ISD::SADDO, VT, Custom);
1531     setOperationAction(ISD::UADDO, VT, Custom);
1532     setOperationAction(ISD::SSUBO, VT, Custom);
1533     setOperationAction(ISD::USUBO, VT, Custom);
1534     setOperationAction(ISD::SMULO, VT, Custom);
1535     setOperationAction(ISD::UMULO, VT, Custom);
1536   }
1537
1538
1539   if (!Subtarget->is64Bit()) {
1540     // These libcalls are not available in 32-bit.
1541     setLibcallName(RTLIB::SHL_I128, nullptr);
1542     setLibcallName(RTLIB::SRL_I128, nullptr);
1543     setLibcallName(RTLIB::SRA_I128, nullptr);
1544   }
1545
1546   // Combine sin / cos into one node or libcall if possible.
1547   if (Subtarget->hasSinCos()) {
1548     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1549     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1550     if (Subtarget->isTargetDarwin()) {
1551       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1552       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1553       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1554       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1555     }
1556   }
1557
1558   if (Subtarget->isTargetWin64()) {
1559     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1560     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1561     setOperationAction(ISD::SREM, MVT::i128, Custom);
1562     setOperationAction(ISD::UREM, MVT::i128, Custom);
1563     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1564     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1565   }
1566
1567   // We have target-specific dag combine patterns for the following nodes:
1568   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1569   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1570   setTargetDAGCombine(ISD::BITCAST);
1571   setTargetDAGCombine(ISD::VSELECT);
1572   setTargetDAGCombine(ISD::SELECT);
1573   setTargetDAGCombine(ISD::SHL);
1574   setTargetDAGCombine(ISD::SRA);
1575   setTargetDAGCombine(ISD::SRL);
1576   setTargetDAGCombine(ISD::OR);
1577   setTargetDAGCombine(ISD::AND);
1578   setTargetDAGCombine(ISD::ADD);
1579   setTargetDAGCombine(ISD::FADD);
1580   setTargetDAGCombine(ISD::FSUB);
1581   setTargetDAGCombine(ISD::FMA);
1582   setTargetDAGCombine(ISD::SUB);
1583   setTargetDAGCombine(ISD::LOAD);
1584   setTargetDAGCombine(ISD::MLOAD);
1585   setTargetDAGCombine(ISD::STORE);
1586   setTargetDAGCombine(ISD::MSTORE);
1587   setTargetDAGCombine(ISD::ZERO_EXTEND);
1588   setTargetDAGCombine(ISD::ANY_EXTEND);
1589   setTargetDAGCombine(ISD::SIGN_EXTEND);
1590   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1591   setTargetDAGCombine(ISD::SINT_TO_FP);
1592   setTargetDAGCombine(ISD::SETCC);
1593   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1594   setTargetDAGCombine(ISD::BUILD_VECTOR);
1595   setTargetDAGCombine(ISD::MUL);
1596   setTargetDAGCombine(ISD::XOR);
1597
1598   computeRegisterProperties(Subtarget->getRegisterInfo());
1599
1600   // On Darwin, -Os means optimize for size without hurting performance,
1601   // do not reduce the limit.
1602   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1603   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1604   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1605   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1606   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1607   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1608   setPrefLoopAlignment(4); // 2^4 bytes.
1609
1610   // Predictable cmov don't hurt on atom because it's in-order.
1611   PredictableSelectIsExpensive = !Subtarget->isAtom();
1612   EnableExtLdPromotion = true;
1613   setPrefFunctionAlignment(4); // 2^4 bytes.
1614
1615   verifyIntrinsicTables();
1616 }
1617
1618 // This has so far only been implemented for 64-bit MachO.
1619 bool X86TargetLowering::useLoadStackGuardNode() const {
1620   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1621 }
1622
1623 TargetLoweringBase::LegalizeTypeAction
1624 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1625   if (ExperimentalVectorWideningLegalization &&
1626       VT.getVectorNumElements() != 1 &&
1627       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1628     return TypeWidenVector;
1629
1630   return TargetLoweringBase::getPreferredVectorAction(VT);
1631 }
1632
1633 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1634   if (!VT.isVector())
1635     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1636
1637   const unsigned NumElts = VT.getVectorNumElements();
1638   const EVT EltVT = VT.getVectorElementType();
1639   if (VT.is512BitVector()) {
1640     if (Subtarget->hasAVX512())
1641       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1642           EltVT == MVT::f32 || EltVT == MVT::f64)
1643         switch(NumElts) {
1644         case  8: return MVT::v8i1;
1645         case 16: return MVT::v16i1;
1646       }
1647     if (Subtarget->hasBWI())
1648       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1649         switch(NumElts) {
1650         case 32: return MVT::v32i1;
1651         case 64: return MVT::v64i1;
1652       }
1653   }
1654
1655   if (VT.is256BitVector() || VT.is128BitVector()) {
1656     if (Subtarget->hasVLX())
1657       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1658           EltVT == MVT::f32 || EltVT == MVT::f64)
1659         switch(NumElts) {
1660         case 2: return MVT::v2i1;
1661         case 4: return MVT::v4i1;
1662         case 8: return MVT::v8i1;
1663       }
1664     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1665       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1666         switch(NumElts) {
1667         case  8: return MVT::v8i1;
1668         case 16: return MVT::v16i1;
1669         case 32: return MVT::v32i1;
1670       }
1671   }
1672
1673   return VT.changeVectorElementTypeToInteger();
1674 }
1675
1676 /// Helper for getByValTypeAlignment to determine
1677 /// the desired ByVal argument alignment.
1678 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1679   if (MaxAlign == 16)
1680     return;
1681   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1682     if (VTy->getBitWidth() == 128)
1683       MaxAlign = 16;
1684   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1685     unsigned EltAlign = 0;
1686     getMaxByValAlign(ATy->getElementType(), EltAlign);
1687     if (EltAlign > MaxAlign)
1688       MaxAlign = EltAlign;
1689   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1690     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1691       unsigned EltAlign = 0;
1692       getMaxByValAlign(STy->getElementType(i), EltAlign);
1693       if (EltAlign > MaxAlign)
1694         MaxAlign = EltAlign;
1695       if (MaxAlign == 16)
1696         break;
1697     }
1698   }
1699 }
1700
1701 /// Return the desired alignment for ByVal aggregate
1702 /// function arguments in the caller parameter area. For X86, aggregates
1703 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1704 /// are at 4-byte boundaries.
1705 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1706   if (Subtarget->is64Bit()) {
1707     // Max of 8 and alignment of type.
1708     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1709     if (TyAlign > 8)
1710       return TyAlign;
1711     return 8;
1712   }
1713
1714   unsigned Align = 4;
1715   if (Subtarget->hasSSE1())
1716     getMaxByValAlign(Ty, Align);
1717   return Align;
1718 }
1719
1720 /// Returns the target specific optimal type for load
1721 /// and store operations as a result of memset, memcpy, and memmove
1722 /// lowering. If DstAlign is zero that means it's safe to destination
1723 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1724 /// means there isn't a need to check it against alignment requirement,
1725 /// probably because the source does not need to be loaded. If 'IsMemset' is
1726 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1727 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1728 /// source is constant so it does not need to be loaded.
1729 /// It returns EVT::Other if the type should be determined using generic
1730 /// target-independent logic.
1731 EVT
1732 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1733                                        unsigned DstAlign, unsigned SrcAlign,
1734                                        bool IsMemset, bool ZeroMemset,
1735                                        bool MemcpyStrSrc,
1736                                        MachineFunction &MF) const {
1737   const Function *F = MF.getFunction();
1738   if ((!IsMemset || ZeroMemset) &&
1739       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1740     if (Size >= 16 &&
1741         (Subtarget->isUnalignedMemAccessFast() ||
1742          ((DstAlign == 0 || DstAlign >= 16) &&
1743           (SrcAlign == 0 || SrcAlign >= 16)))) {
1744       if (Size >= 32) {
1745         if (Subtarget->hasInt256())
1746           return MVT::v8i32;
1747         if (Subtarget->hasFp256())
1748           return MVT::v8f32;
1749       }
1750       if (Subtarget->hasSSE2())
1751         return MVT::v4i32;
1752       if (Subtarget->hasSSE1())
1753         return MVT::v4f32;
1754     } else if (!MemcpyStrSrc && Size >= 8 &&
1755                !Subtarget->is64Bit() &&
1756                Subtarget->hasSSE2()) {
1757       // Do not use f64 to lower memcpy if source is string constant. It's
1758       // better to use i32 to avoid the loads.
1759       return MVT::f64;
1760     }
1761   }
1762   if (Subtarget->is64Bit() && Size >= 8)
1763     return MVT::i64;
1764   return MVT::i32;
1765 }
1766
1767 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1768   if (VT == MVT::f32)
1769     return X86ScalarSSEf32;
1770   else if (VT == MVT::f64)
1771     return X86ScalarSSEf64;
1772   return true;
1773 }
1774
1775 bool
1776 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1777                                                   unsigned,
1778                                                   unsigned,
1779                                                   bool *Fast) const {
1780   if (Fast)
1781     *Fast = Subtarget->isUnalignedMemAccessFast();
1782   return true;
1783 }
1784
1785 /// Return the entry encoding for a jump table in the
1786 /// current function.  The returned value is a member of the
1787 /// MachineJumpTableInfo::JTEntryKind enum.
1788 unsigned X86TargetLowering::getJumpTableEncoding() const {
1789   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1790   // symbol.
1791   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1792       Subtarget->isPICStyleGOT())
1793     return MachineJumpTableInfo::EK_Custom32;
1794
1795   // Otherwise, use the normal jump table encoding heuristics.
1796   return TargetLowering::getJumpTableEncoding();
1797 }
1798
1799 bool X86TargetLowering::useSoftFloat() const {
1800   return Subtarget->useSoftFloat();
1801 }
1802
1803 const MCExpr *
1804 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1805                                              const MachineBasicBlock *MBB,
1806                                              unsigned uid,MCContext &Ctx) const{
1807   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1808          Subtarget->isPICStyleGOT());
1809   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1810   // entries.
1811   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1812                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1813 }
1814
1815 /// Returns relocation base for the given PIC jumptable.
1816 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1817                                                     SelectionDAG &DAG) const {
1818   if (!Subtarget->is64Bit())
1819     // This doesn't have SDLoc associated with it, but is not really the
1820     // same as a Register.
1821     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1822   return Table;
1823 }
1824
1825 /// This returns the relocation base for the given PIC jumptable,
1826 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1827 const MCExpr *X86TargetLowering::
1828 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1829                              MCContext &Ctx) const {
1830   // X86-64 uses RIP relative addressing based on the jump table label.
1831   if (Subtarget->isPICStyleRIPRel())
1832     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1833
1834   // Otherwise, the reference is relative to the PIC base.
1835   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1836 }
1837
1838 std::pair<const TargetRegisterClass *, uint8_t>
1839 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1840                                            MVT VT) const {
1841   const TargetRegisterClass *RRC = nullptr;
1842   uint8_t Cost = 1;
1843   switch (VT.SimpleTy) {
1844   default:
1845     return TargetLowering::findRepresentativeClass(TRI, VT);
1846   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1847     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1848     break;
1849   case MVT::x86mmx:
1850     RRC = &X86::VR64RegClass;
1851     break;
1852   case MVT::f32: case MVT::f64:
1853   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1854   case MVT::v4f32: case MVT::v2f64:
1855   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1856   case MVT::v4f64:
1857     RRC = &X86::VR128RegClass;
1858     break;
1859   }
1860   return std::make_pair(RRC, Cost);
1861 }
1862
1863 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1864                                                unsigned &Offset) const {
1865   if (!Subtarget->isTargetLinux())
1866     return false;
1867
1868   if (Subtarget->is64Bit()) {
1869     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1870     Offset = 0x28;
1871     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1872       AddressSpace = 256;
1873     else
1874       AddressSpace = 257;
1875   } else {
1876     // %gs:0x14 on i386
1877     Offset = 0x14;
1878     AddressSpace = 256;
1879   }
1880   return true;
1881 }
1882
1883 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1884                                             unsigned DestAS) const {
1885   assert(SrcAS != DestAS && "Expected different address spaces!");
1886
1887   return SrcAS < 256 && DestAS < 256;
1888 }
1889
1890 //===----------------------------------------------------------------------===//
1891 //               Return Value Calling Convention Implementation
1892 //===----------------------------------------------------------------------===//
1893
1894 #include "X86GenCallingConv.inc"
1895
1896 bool
1897 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1898                                   MachineFunction &MF, bool isVarArg,
1899                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1900                         LLVMContext &Context) const {
1901   SmallVector<CCValAssign, 16> RVLocs;
1902   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1903   return CCInfo.CheckReturn(Outs, RetCC_X86);
1904 }
1905
1906 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1907   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1908   return ScratchRegs;
1909 }
1910
1911 SDValue
1912 X86TargetLowering::LowerReturn(SDValue Chain,
1913                                CallingConv::ID CallConv, bool isVarArg,
1914                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1915                                const SmallVectorImpl<SDValue> &OutVals,
1916                                SDLoc dl, SelectionDAG &DAG) const {
1917   MachineFunction &MF = DAG.getMachineFunction();
1918   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1919
1920   SmallVector<CCValAssign, 16> RVLocs;
1921   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1922   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1923
1924   SDValue Flag;
1925   SmallVector<SDValue, 6> RetOps;
1926   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1927   // Operand #1 = Bytes To Pop
1928   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1929                    MVT::i16));
1930
1931   // Copy the result values into the output registers.
1932   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1933     CCValAssign &VA = RVLocs[i];
1934     assert(VA.isRegLoc() && "Can only return in registers!");
1935     SDValue ValToCopy = OutVals[i];
1936     EVT ValVT = ValToCopy.getValueType();
1937
1938     // Promote values to the appropriate types.
1939     if (VA.getLocInfo() == CCValAssign::SExt)
1940       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1941     else if (VA.getLocInfo() == CCValAssign::ZExt)
1942       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1943     else if (VA.getLocInfo() == CCValAssign::AExt) {
1944       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
1945         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1946       else
1947         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1948     }
1949     else if (VA.getLocInfo() == CCValAssign::BCvt)
1950       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1951
1952     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1953            "Unexpected FP-extend for return value.");
1954
1955     // If this is x86-64, and we disabled SSE, we can't return FP values,
1956     // or SSE or MMX vectors.
1957     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1958          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1959           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1960       report_fatal_error("SSE register return with SSE disabled");
1961     }
1962     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1963     // llvm-gcc has never done it right and no one has noticed, so this
1964     // should be OK for now.
1965     if (ValVT == MVT::f64 &&
1966         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1967       report_fatal_error("SSE2 register return with SSE2 disabled");
1968
1969     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1970     // the RET instruction and handled by the FP Stackifier.
1971     if (VA.getLocReg() == X86::FP0 ||
1972         VA.getLocReg() == X86::FP1) {
1973       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1974       // change the value to the FP stack register class.
1975       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1976         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1977       RetOps.push_back(ValToCopy);
1978       // Don't emit a copytoreg.
1979       continue;
1980     }
1981
1982     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1983     // which is returned in RAX / RDX.
1984     if (Subtarget->is64Bit()) {
1985       if (ValVT == MVT::x86mmx) {
1986         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1987           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1988           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1989                                   ValToCopy);
1990           // If we don't have SSE2 available, convert to v4f32 so the generated
1991           // register is legal.
1992           if (!Subtarget->hasSSE2())
1993             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1994         }
1995       }
1996     }
1997
1998     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1999     Flag = Chain.getValue(1);
2000     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2001   }
2002
2003   // The x86-64 ABIs require that for returning structs by value we copy
2004   // the sret argument into %rax/%eax (depending on ABI) for the return.
2005   // Win32 requires us to put the sret argument to %eax as well.
2006   // We saved the argument into a virtual register in the entry block,
2007   // so now we copy the value out and into %rax/%eax.
2008   //
2009   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2010   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2011   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2012   // either case FuncInfo->setSRetReturnReg() will have been called.
2013   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2014     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2015            "No need for an sret register");
2016     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2017
2018     unsigned RetValReg
2019         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2020           X86::RAX : X86::EAX;
2021     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2022     Flag = Chain.getValue(1);
2023
2024     // RAX/EAX now acts like a return value.
2025     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2026   }
2027
2028   RetOps[0] = Chain;  // Update chain.
2029
2030   // Add the flag if we have it.
2031   if (Flag.getNode())
2032     RetOps.push_back(Flag);
2033
2034   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2035 }
2036
2037 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2038   if (N->getNumValues() != 1)
2039     return false;
2040   if (!N->hasNUsesOfValue(1, 0))
2041     return false;
2042
2043   SDValue TCChain = Chain;
2044   SDNode *Copy = *N->use_begin();
2045   if (Copy->getOpcode() == ISD::CopyToReg) {
2046     // If the copy has a glue operand, we conservatively assume it isn't safe to
2047     // perform a tail call.
2048     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2049       return false;
2050     TCChain = Copy->getOperand(0);
2051   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2052     return false;
2053
2054   bool HasRet = false;
2055   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2056        UI != UE; ++UI) {
2057     if (UI->getOpcode() != X86ISD::RET_FLAG)
2058       return false;
2059     // If we are returning more than one value, we can definitely
2060     // not make a tail call see PR19530
2061     if (UI->getNumOperands() > 4)
2062       return false;
2063     if (UI->getNumOperands() == 4 &&
2064         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2065       return false;
2066     HasRet = true;
2067   }
2068
2069   if (!HasRet)
2070     return false;
2071
2072   Chain = TCChain;
2073   return true;
2074 }
2075
2076 EVT
2077 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2078                                             ISD::NodeType ExtendKind) const {
2079   MVT ReturnMVT;
2080   // TODO: Is this also valid on 32-bit?
2081   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2082     ReturnMVT = MVT::i8;
2083   else
2084     ReturnMVT = MVT::i32;
2085
2086   EVT MinVT = getRegisterType(Context, ReturnMVT);
2087   return VT.bitsLT(MinVT) ? MinVT : VT;
2088 }
2089
2090 /// Lower the result values of a call into the
2091 /// appropriate copies out of appropriate physical registers.
2092 ///
2093 SDValue
2094 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2095                                    CallingConv::ID CallConv, bool isVarArg,
2096                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2097                                    SDLoc dl, SelectionDAG &DAG,
2098                                    SmallVectorImpl<SDValue> &InVals) const {
2099
2100   // Assign locations to each value returned by this call.
2101   SmallVector<CCValAssign, 16> RVLocs;
2102   bool Is64Bit = Subtarget->is64Bit();
2103   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2104                  *DAG.getContext());
2105   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2106
2107   // Copy all of the result registers out of their specified physreg.
2108   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2109     CCValAssign &VA = RVLocs[i];
2110     EVT CopyVT = VA.getLocVT();
2111
2112     // If this is x86-64, and we disabled SSE, we can't return FP values
2113     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2114         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2115       report_fatal_error("SSE register return with SSE disabled");
2116     }
2117
2118     // If we prefer to use the value in xmm registers, copy it out as f80 and
2119     // use a truncate to move it from fp stack reg to xmm reg.
2120     bool RoundAfterCopy = false;
2121     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2122         isScalarFPTypeInSSEReg(VA.getValVT())) {
2123       CopyVT = MVT::f80;
2124       RoundAfterCopy = (CopyVT != VA.getLocVT());
2125     }
2126
2127     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2128                                CopyVT, InFlag).getValue(1);
2129     SDValue Val = Chain.getValue(0);
2130
2131     if (RoundAfterCopy)
2132       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2133                         // This truncation won't change the value.
2134                         DAG.getIntPtrConstant(1, dl));
2135
2136     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2137       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2138
2139     InFlag = Chain.getValue(2);
2140     InVals.push_back(Val);
2141   }
2142
2143   return Chain;
2144 }
2145
2146 //===----------------------------------------------------------------------===//
2147 //                C & StdCall & Fast Calling Convention implementation
2148 //===----------------------------------------------------------------------===//
2149 //  StdCall calling convention seems to be standard for many Windows' API
2150 //  routines and around. It differs from C calling convention just a little:
2151 //  callee should clean up the stack, not caller. Symbols should be also
2152 //  decorated in some fancy way :) It doesn't support any vector arguments.
2153 //  For info on fast calling convention see Fast Calling Convention (tail call)
2154 //  implementation LowerX86_32FastCCCallTo.
2155
2156 /// CallIsStructReturn - Determines whether a call uses struct return
2157 /// semantics.
2158 enum StructReturnType {
2159   NotStructReturn,
2160   RegStructReturn,
2161   StackStructReturn
2162 };
2163 static StructReturnType
2164 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2165   if (Outs.empty())
2166     return NotStructReturn;
2167
2168   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2169   if (!Flags.isSRet())
2170     return NotStructReturn;
2171   if (Flags.isInReg())
2172     return RegStructReturn;
2173   return StackStructReturn;
2174 }
2175
2176 /// Determines whether a function uses struct return semantics.
2177 static StructReturnType
2178 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2179   if (Ins.empty())
2180     return NotStructReturn;
2181
2182   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2183   if (!Flags.isSRet())
2184     return NotStructReturn;
2185   if (Flags.isInReg())
2186     return RegStructReturn;
2187   return StackStructReturn;
2188 }
2189
2190 /// Make a copy of an aggregate at address specified by "Src" to address
2191 /// "Dst" with size and alignment information specified by the specific
2192 /// parameter attribute. The copy will be passed as a byval function parameter.
2193 static SDValue
2194 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2195                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2196                           SDLoc dl) {
2197   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2198
2199   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2200                        /*isVolatile*/false, /*AlwaysInline=*/true,
2201                        /*isTailCall*/false,
2202                        MachinePointerInfo(), MachinePointerInfo());
2203 }
2204
2205 /// Return true if the calling convention is one that
2206 /// supports tail call optimization.
2207 static bool IsTailCallConvention(CallingConv::ID CC) {
2208   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2209           CC == CallingConv::HiPE);
2210 }
2211
2212 /// \brief Return true if the calling convention is a C calling convention.
2213 static bool IsCCallConvention(CallingConv::ID CC) {
2214   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2215           CC == CallingConv::X86_64_SysV);
2216 }
2217
2218 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2219   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2220     return false;
2221
2222   CallSite CS(CI);
2223   CallingConv::ID CalleeCC = CS.getCallingConv();
2224   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2225     return false;
2226
2227   return true;
2228 }
2229
2230 /// Return true if the function is being made into
2231 /// a tailcall target by changing its ABI.
2232 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2233                                    bool GuaranteedTailCallOpt) {
2234   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2235 }
2236
2237 SDValue
2238 X86TargetLowering::LowerMemArgument(SDValue Chain,
2239                                     CallingConv::ID CallConv,
2240                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2241                                     SDLoc dl, SelectionDAG &DAG,
2242                                     const CCValAssign &VA,
2243                                     MachineFrameInfo *MFI,
2244                                     unsigned i) const {
2245   // Create the nodes corresponding to a load from this parameter slot.
2246   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2247   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2248       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2249   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2250   EVT ValVT;
2251
2252   // If value is passed by pointer we have address passed instead of the value
2253   // itself.
2254   bool ExtendedInMem = VA.isExtInLoc() &&
2255     VA.getValVT().getScalarType() == MVT::i1;
2256
2257   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2258     ValVT = VA.getLocVT();
2259   else
2260     ValVT = VA.getValVT();
2261
2262   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2263   // changed with more analysis.
2264   // In case of tail call optimization mark all arguments mutable. Since they
2265   // could be overwritten by lowering of arguments in case of a tail call.
2266   if (Flags.isByVal()) {
2267     unsigned Bytes = Flags.getByValSize();
2268     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2269     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2270     return DAG.getFrameIndex(FI, getPointerTy());
2271   } else {
2272     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2273                                     VA.getLocMemOffset(), isImmutable);
2274     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2275     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2276                                MachinePointerInfo::getFixedStack(FI),
2277                                false, false, false, 0);
2278     return ExtendedInMem ?
2279       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2280   }
2281 }
2282
2283 // FIXME: Get this from tablegen.
2284 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2285                                                 const X86Subtarget *Subtarget) {
2286   assert(Subtarget->is64Bit());
2287
2288   if (Subtarget->isCallingConvWin64(CallConv)) {
2289     static const MCPhysReg GPR64ArgRegsWin64[] = {
2290       X86::RCX, X86::RDX, X86::R8,  X86::R9
2291     };
2292     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2293   }
2294
2295   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2296     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2297   };
2298   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2299 }
2300
2301 // FIXME: Get this from tablegen.
2302 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2303                                                 CallingConv::ID CallConv,
2304                                                 const X86Subtarget *Subtarget) {
2305   assert(Subtarget->is64Bit());
2306   if (Subtarget->isCallingConvWin64(CallConv)) {
2307     // The XMM registers which might contain var arg parameters are shadowed
2308     // in their paired GPR.  So we only need to save the GPR to their home
2309     // slots.
2310     // TODO: __vectorcall will change this.
2311     return None;
2312   }
2313
2314   const Function *Fn = MF.getFunction();
2315   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2316   bool isSoftFloat = Subtarget->useSoftFloat();
2317   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2318          "SSE register cannot be used when SSE is disabled!");
2319   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2320     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2321     // registers.
2322     return None;
2323
2324   static const MCPhysReg XMMArgRegs64Bit[] = {
2325     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2326     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2327   };
2328   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2329 }
2330
2331 SDValue
2332 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2333                                         CallingConv::ID CallConv,
2334                                         bool isVarArg,
2335                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2336                                         SDLoc dl,
2337                                         SelectionDAG &DAG,
2338                                         SmallVectorImpl<SDValue> &InVals)
2339                                           const {
2340   MachineFunction &MF = DAG.getMachineFunction();
2341   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2342   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2343
2344   const Function* Fn = MF.getFunction();
2345   if (Fn->hasExternalLinkage() &&
2346       Subtarget->isTargetCygMing() &&
2347       Fn->getName() == "main")
2348     FuncInfo->setForceFramePointer(true);
2349
2350   MachineFrameInfo *MFI = MF.getFrameInfo();
2351   bool Is64Bit = Subtarget->is64Bit();
2352   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2353
2354   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2355          "Var args not supported with calling convention fastcc, ghc or hipe");
2356
2357   // Assign locations to all of the incoming arguments.
2358   SmallVector<CCValAssign, 16> ArgLocs;
2359   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2360
2361   // Allocate shadow area for Win64
2362   if (IsWin64)
2363     CCInfo.AllocateStack(32, 8);
2364
2365   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2366
2367   unsigned LastVal = ~0U;
2368   SDValue ArgValue;
2369   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2370     CCValAssign &VA = ArgLocs[i];
2371     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2372     // places.
2373     assert(VA.getValNo() != LastVal &&
2374            "Don't support value assigned to multiple locs yet");
2375     (void)LastVal;
2376     LastVal = VA.getValNo();
2377
2378     if (VA.isRegLoc()) {
2379       EVT RegVT = VA.getLocVT();
2380       const TargetRegisterClass *RC;
2381       if (RegVT == MVT::i32)
2382         RC = &X86::GR32RegClass;
2383       else if (Is64Bit && RegVT == MVT::i64)
2384         RC = &X86::GR64RegClass;
2385       else if (RegVT == MVT::f32)
2386         RC = &X86::FR32RegClass;
2387       else if (RegVT == MVT::f64)
2388         RC = &X86::FR64RegClass;
2389       else if (RegVT.is512BitVector())
2390         RC = &X86::VR512RegClass;
2391       else if (RegVT.is256BitVector())
2392         RC = &X86::VR256RegClass;
2393       else if (RegVT.is128BitVector())
2394         RC = &X86::VR128RegClass;
2395       else if (RegVT == MVT::x86mmx)
2396         RC = &X86::VR64RegClass;
2397       else if (RegVT == MVT::i1)
2398         RC = &X86::VK1RegClass;
2399       else if (RegVT == MVT::v8i1)
2400         RC = &X86::VK8RegClass;
2401       else if (RegVT == MVT::v16i1)
2402         RC = &X86::VK16RegClass;
2403       else if (RegVT == MVT::v32i1)
2404         RC = &X86::VK32RegClass;
2405       else if (RegVT == MVT::v64i1)
2406         RC = &X86::VK64RegClass;
2407       else
2408         llvm_unreachable("Unknown argument type!");
2409
2410       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2411       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2412
2413       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2414       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2415       // right size.
2416       if (VA.getLocInfo() == CCValAssign::SExt)
2417         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2418                                DAG.getValueType(VA.getValVT()));
2419       else if (VA.getLocInfo() == CCValAssign::ZExt)
2420         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2421                                DAG.getValueType(VA.getValVT()));
2422       else if (VA.getLocInfo() == CCValAssign::BCvt)
2423         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2424
2425       if (VA.isExtInLoc()) {
2426         // Handle MMX values passed in XMM regs.
2427         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2428           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2429         else
2430           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2431       }
2432     } else {
2433       assert(VA.isMemLoc());
2434       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2435     }
2436
2437     // If value is passed via pointer - do a load.
2438     if (VA.getLocInfo() == CCValAssign::Indirect)
2439       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2440                              MachinePointerInfo(), false, false, false, 0);
2441
2442     InVals.push_back(ArgValue);
2443   }
2444
2445   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2446     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2447       // The x86-64 ABIs require that for returning structs by value we copy
2448       // the sret argument into %rax/%eax (depending on ABI) for the return.
2449       // Win32 requires us to put the sret argument to %eax as well.
2450       // Save the argument into a virtual register so that we can access it
2451       // from the return points.
2452       if (Ins[i].Flags.isSRet()) {
2453         unsigned Reg = FuncInfo->getSRetReturnReg();
2454         if (!Reg) {
2455           MVT PtrTy = getPointerTy();
2456           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2457           FuncInfo->setSRetReturnReg(Reg);
2458         }
2459         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2460         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2461         break;
2462       }
2463     }
2464   }
2465
2466   unsigned StackSize = CCInfo.getNextStackOffset();
2467   // Align stack specially for tail calls.
2468   if (FuncIsMadeTailCallSafe(CallConv,
2469                              MF.getTarget().Options.GuaranteedTailCallOpt))
2470     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2471
2472   // If the function takes variable number of arguments, make a frame index for
2473   // the start of the first vararg value... for expansion of llvm.va_start. We
2474   // can skip this if there are no va_start calls.
2475   if (MFI->hasVAStart() &&
2476       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2477                    CallConv != CallingConv::X86_ThisCall))) {
2478     FuncInfo->setVarArgsFrameIndex(
2479         MFI->CreateFixedObject(1, StackSize, true));
2480   }
2481
2482   MachineModuleInfo &MMI = MF.getMMI();
2483   const Function *WinEHParent = nullptr;
2484   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2485     WinEHParent = MMI.getWinEHParent(Fn);
2486   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2487   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2488
2489   // Figure out if XMM registers are in use.
2490   assert(!(Subtarget->useSoftFloat() &&
2491            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2492          "SSE register cannot be used when SSE is disabled!");
2493
2494   // 64-bit calling conventions support varargs and register parameters, so we
2495   // have to do extra work to spill them in the prologue.
2496   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2497     // Find the first unallocated argument registers.
2498     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2499     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2500     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2501     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2502     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2503            "SSE register cannot be used when SSE is disabled!");
2504
2505     // Gather all the live in physical registers.
2506     SmallVector<SDValue, 6> LiveGPRs;
2507     SmallVector<SDValue, 8> LiveXMMRegs;
2508     SDValue ALVal;
2509     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2510       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2511       LiveGPRs.push_back(
2512           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2513     }
2514     if (!ArgXMMs.empty()) {
2515       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2516       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2517       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2518         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2519         LiveXMMRegs.push_back(
2520             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2521       }
2522     }
2523
2524     if (IsWin64) {
2525       // Get to the caller-allocated home save location.  Add 8 to account
2526       // for the return address.
2527       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2528       FuncInfo->setRegSaveFrameIndex(
2529           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2530       // Fixup to set vararg frame on shadow area (4 x i64).
2531       if (NumIntRegs < 4)
2532         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2533     } else {
2534       // For X86-64, if there are vararg parameters that are passed via
2535       // registers, then we must store them to their spots on the stack so
2536       // they may be loaded by deferencing the result of va_next.
2537       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2538       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2539       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2540           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2541     }
2542
2543     // Store the integer parameter registers.
2544     SmallVector<SDValue, 8> MemOps;
2545     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2546                                       getPointerTy());
2547     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2548     for (SDValue Val : LiveGPRs) {
2549       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2550                                 DAG.getIntPtrConstant(Offset, dl));
2551       SDValue Store =
2552         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2553                      MachinePointerInfo::getFixedStack(
2554                        FuncInfo->getRegSaveFrameIndex(), Offset),
2555                      false, false, 0);
2556       MemOps.push_back(Store);
2557       Offset += 8;
2558     }
2559
2560     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2561       // Now store the XMM (fp + vector) parameter registers.
2562       SmallVector<SDValue, 12> SaveXMMOps;
2563       SaveXMMOps.push_back(Chain);
2564       SaveXMMOps.push_back(ALVal);
2565       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2566                              FuncInfo->getRegSaveFrameIndex(), dl));
2567       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2568                              FuncInfo->getVarArgsFPOffset(), dl));
2569       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2570                         LiveXMMRegs.end());
2571       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2572                                    MVT::Other, SaveXMMOps));
2573     }
2574
2575     if (!MemOps.empty())
2576       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2577   } else if (IsWinEHOutlined) {
2578     // Get to the caller-allocated home save location.  Add 8 to account
2579     // for the return address.
2580     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2581     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2582         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2583
2584     MMI.getWinEHFuncInfo(Fn)
2585         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2586         FuncInfo->getRegSaveFrameIndex();
2587
2588     // Store the second integer parameter (rdx) into rsp+16 relative to the
2589     // stack pointer at the entry of the function.
2590     SDValue RSFIN =
2591         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2592     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2593     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2594     Chain = DAG.getStore(
2595         Val.getValue(1), dl, Val, RSFIN,
2596         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2597         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2598   }
2599
2600   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2601     // Find the largest legal vector type.
2602     MVT VecVT = MVT::Other;
2603     // FIXME: Only some x86_32 calling conventions support AVX512.
2604     if (Subtarget->hasAVX512() &&
2605         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2606                      CallConv == CallingConv::Intel_OCL_BI)))
2607       VecVT = MVT::v16f32;
2608     else if (Subtarget->hasAVX())
2609       VecVT = MVT::v8f32;
2610     else if (Subtarget->hasSSE2())
2611       VecVT = MVT::v4f32;
2612
2613     // We forward some GPRs and some vector types.
2614     SmallVector<MVT, 2> RegParmTypes;
2615     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2616     RegParmTypes.push_back(IntVT);
2617     if (VecVT != MVT::Other)
2618       RegParmTypes.push_back(VecVT);
2619
2620     // Compute the set of forwarded registers. The rest are scratch.
2621     SmallVectorImpl<ForwardedRegister> &Forwards =
2622         FuncInfo->getForwardedMustTailRegParms();
2623     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2624
2625     // Conservatively forward AL on x86_64, since it might be used for varargs.
2626     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2627       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2628       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2629     }
2630
2631     // Copy all forwards from physical to virtual registers.
2632     for (ForwardedRegister &F : Forwards) {
2633       // FIXME: Can we use a less constrained schedule?
2634       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2635       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2636       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2637     }
2638   }
2639
2640   // Some CCs need callee pop.
2641   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2642                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2643     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2644   } else {
2645     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2646     // If this is an sret function, the return should pop the hidden pointer.
2647     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2648         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2649         argsAreStructReturn(Ins) == StackStructReturn)
2650       FuncInfo->setBytesToPopOnReturn(4);
2651   }
2652
2653   if (!Is64Bit) {
2654     // RegSaveFrameIndex is X86-64 only.
2655     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2656     if (CallConv == CallingConv::X86_FastCall ||
2657         CallConv == CallingConv::X86_ThisCall)
2658       // fastcc functions can't have varargs.
2659       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2660   }
2661
2662   FuncInfo->setArgumentStackSize(StackSize);
2663
2664   if (IsWinEHParent) {
2665     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2666     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2667     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2668     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2669     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2670                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2671                          /*isVolatile=*/true,
2672                          /*isNonTemporal=*/false, /*Alignment=*/0);
2673   }
2674
2675   return Chain;
2676 }
2677
2678 SDValue
2679 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2680                                     SDValue StackPtr, SDValue Arg,
2681                                     SDLoc dl, SelectionDAG &DAG,
2682                                     const CCValAssign &VA,
2683                                     ISD::ArgFlagsTy Flags) const {
2684   unsigned LocMemOffset = VA.getLocMemOffset();
2685   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2686   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2687   if (Flags.isByVal())
2688     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2689
2690   return DAG.getStore(Chain, dl, Arg, PtrOff,
2691                       MachinePointerInfo::getStack(LocMemOffset),
2692                       false, false, 0);
2693 }
2694
2695 /// Emit a load of return address if tail call
2696 /// optimization is performed and it is required.
2697 SDValue
2698 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2699                                            SDValue &OutRetAddr, SDValue Chain,
2700                                            bool IsTailCall, bool Is64Bit,
2701                                            int FPDiff, SDLoc dl) const {
2702   // Adjust the Return address stack slot.
2703   EVT VT = getPointerTy();
2704   OutRetAddr = getReturnAddressFrameIndex(DAG);
2705
2706   // Load the "old" Return address.
2707   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2708                            false, false, false, 0);
2709   return SDValue(OutRetAddr.getNode(), 1);
2710 }
2711
2712 /// Emit a store of the return address if tail call
2713 /// optimization is performed and it is required (FPDiff!=0).
2714 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2715                                         SDValue Chain, SDValue RetAddrFrIdx,
2716                                         EVT PtrVT, unsigned SlotSize,
2717                                         int FPDiff, SDLoc dl) {
2718   // Store the return address to the appropriate stack slot.
2719   if (!FPDiff) return Chain;
2720   // Calculate the new stack slot for the return address.
2721   int NewReturnAddrFI =
2722     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2723                                          false);
2724   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2725   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2726                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2727                        false, false, 0);
2728   return Chain;
2729 }
2730
2731 SDValue
2732 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2733                              SmallVectorImpl<SDValue> &InVals) const {
2734   SelectionDAG &DAG                     = CLI.DAG;
2735   SDLoc &dl                             = CLI.DL;
2736   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2737   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2738   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2739   SDValue Chain                         = CLI.Chain;
2740   SDValue Callee                        = CLI.Callee;
2741   CallingConv::ID CallConv              = CLI.CallConv;
2742   bool &isTailCall                      = CLI.IsTailCall;
2743   bool isVarArg                         = CLI.IsVarArg;
2744
2745   MachineFunction &MF = DAG.getMachineFunction();
2746   bool Is64Bit        = Subtarget->is64Bit();
2747   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2748   StructReturnType SR = callIsStructReturn(Outs);
2749   bool IsSibcall      = false;
2750   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2751
2752   if (MF.getTarget().Options.DisableTailCalls)
2753     isTailCall = false;
2754
2755   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2756   if (IsMustTail) {
2757     // Force this to be a tail call.  The verifier rules are enough to ensure
2758     // that we can lower this successfully without moving the return address
2759     // around.
2760     isTailCall = true;
2761   } else if (isTailCall) {
2762     // Check if it's really possible to do a tail call.
2763     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2764                     isVarArg, SR != NotStructReturn,
2765                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2766                     Outs, OutVals, Ins, DAG);
2767
2768     // Sibcalls are automatically detected tailcalls which do not require
2769     // ABI changes.
2770     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2771       IsSibcall = true;
2772
2773     if (isTailCall)
2774       ++NumTailCalls;
2775   }
2776
2777   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2778          "Var args not supported with calling convention fastcc, ghc or hipe");
2779
2780   // Analyze operands of the call, assigning locations to each operand.
2781   SmallVector<CCValAssign, 16> ArgLocs;
2782   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2783
2784   // Allocate shadow area for Win64
2785   if (IsWin64)
2786     CCInfo.AllocateStack(32, 8);
2787
2788   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2789
2790   // Get a count of how many bytes are to be pushed on the stack.
2791   unsigned NumBytes = CCInfo.getNextStackOffset();
2792   if (IsSibcall)
2793     // This is a sibcall. The memory operands are available in caller's
2794     // own caller's stack.
2795     NumBytes = 0;
2796   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2797            IsTailCallConvention(CallConv))
2798     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2799
2800   int FPDiff = 0;
2801   if (isTailCall && !IsSibcall && !IsMustTail) {
2802     // Lower arguments at fp - stackoffset + fpdiff.
2803     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2804
2805     FPDiff = NumBytesCallerPushed - NumBytes;
2806
2807     // Set the delta of movement of the returnaddr stackslot.
2808     // But only set if delta is greater than previous delta.
2809     if (FPDiff < X86Info->getTCReturnAddrDelta())
2810       X86Info->setTCReturnAddrDelta(FPDiff);
2811   }
2812
2813   unsigned NumBytesToPush = NumBytes;
2814   unsigned NumBytesToPop = NumBytes;
2815
2816   // If we have an inalloca argument, all stack space has already been allocated
2817   // for us and be right at the top of the stack.  We don't support multiple
2818   // arguments passed in memory when using inalloca.
2819   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2820     NumBytesToPush = 0;
2821     if (!ArgLocs.back().isMemLoc())
2822       report_fatal_error("cannot use inalloca attribute on a register "
2823                          "parameter");
2824     if (ArgLocs.back().getLocMemOffset() != 0)
2825       report_fatal_error("any parameter with the inalloca attribute must be "
2826                          "the only memory argument");
2827   }
2828
2829   if (!IsSibcall)
2830     Chain = DAG.getCALLSEQ_START(
2831         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2832
2833   SDValue RetAddrFrIdx;
2834   // Load return address for tail calls.
2835   if (isTailCall && FPDiff)
2836     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2837                                     Is64Bit, FPDiff, dl);
2838
2839   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2840   SmallVector<SDValue, 8> MemOpChains;
2841   SDValue StackPtr;
2842
2843   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2844   // of tail call optimization arguments are handle later.
2845   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2846   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2847     // Skip inalloca arguments, they have already been written.
2848     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2849     if (Flags.isInAlloca())
2850       continue;
2851
2852     CCValAssign &VA = ArgLocs[i];
2853     EVT RegVT = VA.getLocVT();
2854     SDValue Arg = OutVals[i];
2855     bool isByVal = Flags.isByVal();
2856
2857     // Promote the value if needed.
2858     switch (VA.getLocInfo()) {
2859     default: llvm_unreachable("Unknown loc info!");
2860     case CCValAssign::Full: break;
2861     case CCValAssign::SExt:
2862       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2863       break;
2864     case CCValAssign::ZExt:
2865       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2866       break;
2867     case CCValAssign::AExt:
2868       if (Arg.getValueType().isVector() &&
2869           Arg.getValueType().getScalarType() == MVT::i1)
2870         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2871       else if (RegVT.is128BitVector()) {
2872         // Special case: passing MMX values in XMM registers.
2873         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2874         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2875         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2876       } else
2877         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2878       break;
2879     case CCValAssign::BCvt:
2880       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2881       break;
2882     case CCValAssign::Indirect: {
2883       // Store the argument.
2884       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2885       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2886       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2887                            MachinePointerInfo::getFixedStack(FI),
2888                            false, false, 0);
2889       Arg = SpillSlot;
2890       break;
2891     }
2892     }
2893
2894     if (VA.isRegLoc()) {
2895       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2896       if (isVarArg && IsWin64) {
2897         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2898         // shadow reg if callee is a varargs function.
2899         unsigned ShadowReg = 0;
2900         switch (VA.getLocReg()) {
2901         case X86::XMM0: ShadowReg = X86::RCX; break;
2902         case X86::XMM1: ShadowReg = X86::RDX; break;
2903         case X86::XMM2: ShadowReg = X86::R8; break;
2904         case X86::XMM3: ShadowReg = X86::R9; break;
2905         }
2906         if (ShadowReg)
2907           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2908       }
2909     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2910       assert(VA.isMemLoc());
2911       if (!StackPtr.getNode())
2912         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2913                                       getPointerTy());
2914       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2915                                              dl, DAG, VA, Flags));
2916     }
2917   }
2918
2919   if (!MemOpChains.empty())
2920     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2921
2922   if (Subtarget->isPICStyleGOT()) {
2923     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2924     // GOT pointer.
2925     if (!isTailCall) {
2926       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2927                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2928     } else {
2929       // If we are tail calling and generating PIC/GOT style code load the
2930       // address of the callee into ECX. The value in ecx is used as target of
2931       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2932       // for tail calls on PIC/GOT architectures. Normally we would just put the
2933       // address of GOT into ebx and then call target@PLT. But for tail calls
2934       // ebx would be restored (since ebx is callee saved) before jumping to the
2935       // target@PLT.
2936
2937       // Note: The actual moving to ECX is done further down.
2938       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2939       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2940           !G->getGlobal()->hasProtectedVisibility())
2941         Callee = LowerGlobalAddress(Callee, DAG);
2942       else if (isa<ExternalSymbolSDNode>(Callee))
2943         Callee = LowerExternalSymbol(Callee, DAG);
2944     }
2945   }
2946
2947   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2948     // From AMD64 ABI document:
2949     // For calls that may call functions that use varargs or stdargs
2950     // (prototype-less calls or calls to functions containing ellipsis (...) in
2951     // the declaration) %al is used as hidden argument to specify the number
2952     // of SSE registers used. The contents of %al do not need to match exactly
2953     // the number of registers, but must be an ubound on the number of SSE
2954     // registers used and is in the range 0 - 8 inclusive.
2955
2956     // Count the number of XMM registers allocated.
2957     static const MCPhysReg XMMArgRegs[] = {
2958       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2959       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2960     };
2961     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2962     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2963            && "SSE registers cannot be used when SSE is disabled");
2964
2965     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2966                                         DAG.getConstant(NumXMMRegs, dl,
2967                                                         MVT::i8)));
2968   }
2969
2970   if (isVarArg && IsMustTail) {
2971     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2972     for (const auto &F : Forwards) {
2973       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2974       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2975     }
2976   }
2977
2978   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2979   // don't need this because the eligibility check rejects calls that require
2980   // shuffling arguments passed in memory.
2981   if (!IsSibcall && isTailCall) {
2982     // Force all the incoming stack arguments to be loaded from the stack
2983     // before any new outgoing arguments are stored to the stack, because the
2984     // outgoing stack slots may alias the incoming argument stack slots, and
2985     // the alias isn't otherwise explicit. This is slightly more conservative
2986     // than necessary, because it means that each store effectively depends
2987     // on every argument instead of just those arguments it would clobber.
2988     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2989
2990     SmallVector<SDValue, 8> MemOpChains2;
2991     SDValue FIN;
2992     int FI = 0;
2993     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2994       CCValAssign &VA = ArgLocs[i];
2995       if (VA.isRegLoc())
2996         continue;
2997       assert(VA.isMemLoc());
2998       SDValue Arg = OutVals[i];
2999       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3000       // Skip inalloca arguments.  They don't require any work.
3001       if (Flags.isInAlloca())
3002         continue;
3003       // Create frame index.
3004       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3005       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3006       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3007       FIN = DAG.getFrameIndex(FI, getPointerTy());
3008
3009       if (Flags.isByVal()) {
3010         // Copy relative to framepointer.
3011         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3012         if (!StackPtr.getNode())
3013           StackPtr = DAG.getCopyFromReg(Chain, dl,
3014                                         RegInfo->getStackRegister(),
3015                                         getPointerTy());
3016         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3017
3018         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3019                                                          ArgChain,
3020                                                          Flags, DAG, dl));
3021       } else {
3022         // Store relative to framepointer.
3023         MemOpChains2.push_back(
3024           DAG.getStore(ArgChain, dl, Arg, FIN,
3025                        MachinePointerInfo::getFixedStack(FI),
3026                        false, false, 0));
3027       }
3028     }
3029
3030     if (!MemOpChains2.empty())
3031       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3032
3033     // Store the return address to the appropriate stack slot.
3034     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3035                                      getPointerTy(), RegInfo->getSlotSize(),
3036                                      FPDiff, dl);
3037   }
3038
3039   // Build a sequence of copy-to-reg nodes chained together with token chain
3040   // and flag operands which copy the outgoing args into registers.
3041   SDValue InFlag;
3042   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3043     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3044                              RegsToPass[i].second, InFlag);
3045     InFlag = Chain.getValue(1);
3046   }
3047
3048   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3049     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3050     // In the 64-bit large code model, we have to make all calls
3051     // through a register, since the call instruction's 32-bit
3052     // pc-relative offset may not be large enough to hold the whole
3053     // address.
3054   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3055     // If the callee is a GlobalAddress node (quite common, every direct call
3056     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3057     // it.
3058     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3059
3060     // We should use extra load for direct calls to dllimported functions in
3061     // non-JIT mode.
3062     const GlobalValue *GV = G->getGlobal();
3063     if (!GV->hasDLLImportStorageClass()) {
3064       unsigned char OpFlags = 0;
3065       bool ExtraLoad = false;
3066       unsigned WrapperKind = ISD::DELETED_NODE;
3067
3068       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3069       // external symbols most go through the PLT in PIC mode.  If the symbol
3070       // has hidden or protected visibility, or if it is static or local, then
3071       // we don't need to use the PLT - we can directly call it.
3072       if (Subtarget->isTargetELF() &&
3073           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3074           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3075         OpFlags = X86II::MO_PLT;
3076       } else if (Subtarget->isPICStyleStubAny() &&
3077                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3078                  (!Subtarget->getTargetTriple().isMacOSX() ||
3079                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3080         // PC-relative references to external symbols should go through $stub,
3081         // unless we're building with the leopard linker or later, which
3082         // automatically synthesizes these stubs.
3083         OpFlags = X86II::MO_DARWIN_STUB;
3084       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3085                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3086         // If the function is marked as non-lazy, generate an indirect call
3087         // which loads from the GOT directly. This avoids runtime overhead
3088         // at the cost of eager binding (and one extra byte of encoding).
3089         OpFlags = X86II::MO_GOTPCREL;
3090         WrapperKind = X86ISD::WrapperRIP;
3091         ExtraLoad = true;
3092       }
3093
3094       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3095                                           G->getOffset(), OpFlags);
3096
3097       // Add a wrapper if needed.
3098       if (WrapperKind != ISD::DELETED_NODE)
3099         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3100       // Add extra indirection if needed.
3101       if (ExtraLoad)
3102         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3103                              MachinePointerInfo::getGOT(),
3104                              false, false, false, 0);
3105     }
3106   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3107     unsigned char OpFlags = 0;
3108
3109     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3110     // external symbols should go through the PLT.
3111     if (Subtarget->isTargetELF() &&
3112         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3113       OpFlags = X86II::MO_PLT;
3114     } else if (Subtarget->isPICStyleStubAny() &&
3115                (!Subtarget->getTargetTriple().isMacOSX() ||
3116                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3117       // PC-relative references to external symbols should go through $stub,
3118       // unless we're building with the leopard linker or later, which
3119       // automatically synthesizes these stubs.
3120       OpFlags = X86II::MO_DARWIN_STUB;
3121     }
3122
3123     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3124                                          OpFlags);
3125   } else if (Subtarget->isTarget64BitILP32() &&
3126              Callee->getValueType(0) == MVT::i32) {
3127     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3128     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3129   }
3130
3131   // Returns a chain & a flag for retval copy to use.
3132   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3133   SmallVector<SDValue, 8> Ops;
3134
3135   if (!IsSibcall && isTailCall) {
3136     Chain = DAG.getCALLSEQ_END(Chain,
3137                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3138                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3139     InFlag = Chain.getValue(1);
3140   }
3141
3142   Ops.push_back(Chain);
3143   Ops.push_back(Callee);
3144
3145   if (isTailCall)
3146     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3147
3148   // Add argument registers to the end of the list so that they are known live
3149   // into the call.
3150   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3151     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3152                                   RegsToPass[i].second.getValueType()));
3153
3154   // Add a register mask operand representing the call-preserved registers.
3155   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3156   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3157   assert(Mask && "Missing call preserved mask for calling convention");
3158   Ops.push_back(DAG.getRegisterMask(Mask));
3159
3160   if (InFlag.getNode())
3161     Ops.push_back(InFlag);
3162
3163   if (isTailCall) {
3164     // We used to do:
3165     //// If this is the first return lowered for this function, add the regs
3166     //// to the liveout set for the function.
3167     // This isn't right, although it's probably harmless on x86; liveouts
3168     // should be computed from returns not tail calls.  Consider a void
3169     // function making a tail call to a function returning int.
3170     MF.getFrameInfo()->setHasTailCall();
3171     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3172   }
3173
3174   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3175   InFlag = Chain.getValue(1);
3176
3177   // Create the CALLSEQ_END node.
3178   unsigned NumBytesForCalleeToPop;
3179   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3180                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3181     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3182   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3183            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3184            SR == StackStructReturn)
3185     // If this is a call to a struct-return function, the callee
3186     // pops the hidden struct pointer, so we have to push it back.
3187     // This is common for Darwin/X86, Linux & Mingw32 targets.
3188     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3189     NumBytesForCalleeToPop = 4;
3190   else
3191     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3192
3193   // Returns a flag for retval copy to use.
3194   if (!IsSibcall) {
3195     Chain = DAG.getCALLSEQ_END(Chain,
3196                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3197                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3198                                                      true),
3199                                InFlag, dl);
3200     InFlag = Chain.getValue(1);
3201   }
3202
3203   // Handle result values, copying them out of physregs into vregs that we
3204   // return.
3205   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3206                          Ins, dl, DAG, InVals);
3207 }
3208
3209 //===----------------------------------------------------------------------===//
3210 //                Fast Calling Convention (tail call) implementation
3211 //===----------------------------------------------------------------------===//
3212
3213 //  Like std call, callee cleans arguments, convention except that ECX is
3214 //  reserved for storing the tail called function address. Only 2 registers are
3215 //  free for argument passing (inreg). Tail call optimization is performed
3216 //  provided:
3217 //                * tailcallopt is enabled
3218 //                * caller/callee are fastcc
3219 //  On X86_64 architecture with GOT-style position independent code only local
3220 //  (within module) calls are supported at the moment.
3221 //  To keep the stack aligned according to platform abi the function
3222 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3223 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3224 //  If a tail called function callee has more arguments than the caller the
3225 //  caller needs to make sure that there is room to move the RETADDR to. This is
3226 //  achieved by reserving an area the size of the argument delta right after the
3227 //  original RETADDR, but before the saved framepointer or the spilled registers
3228 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3229 //  stack layout:
3230 //    arg1
3231 //    arg2
3232 //    RETADDR
3233 //    [ new RETADDR
3234 //      move area ]
3235 //    (possible EBP)
3236 //    ESI
3237 //    EDI
3238 //    local1 ..
3239
3240 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3241 /// for a 16 byte align requirement.
3242 unsigned
3243 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3244                                                SelectionDAG& DAG) const {
3245   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3246   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3247   unsigned StackAlignment = TFI.getStackAlignment();
3248   uint64_t AlignMask = StackAlignment - 1;
3249   int64_t Offset = StackSize;
3250   unsigned SlotSize = RegInfo->getSlotSize();
3251   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3252     // Number smaller than 12 so just add the difference.
3253     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3254   } else {
3255     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3256     Offset = ((~AlignMask) & Offset) + StackAlignment +
3257       (StackAlignment-SlotSize);
3258   }
3259   return Offset;
3260 }
3261
3262 /// MatchingStackOffset - Return true if the given stack call argument is
3263 /// already available in the same position (relatively) of the caller's
3264 /// incoming argument stack.
3265 static
3266 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3267                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3268                          const X86InstrInfo *TII) {
3269   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3270   int FI = INT_MAX;
3271   if (Arg.getOpcode() == ISD::CopyFromReg) {
3272     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3273     if (!TargetRegisterInfo::isVirtualRegister(VR))
3274       return false;
3275     MachineInstr *Def = MRI->getVRegDef(VR);
3276     if (!Def)
3277       return false;
3278     if (!Flags.isByVal()) {
3279       if (!TII->isLoadFromStackSlot(Def, FI))
3280         return false;
3281     } else {
3282       unsigned Opcode = Def->getOpcode();
3283       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3284            Opcode == X86::LEA64_32r) &&
3285           Def->getOperand(1).isFI()) {
3286         FI = Def->getOperand(1).getIndex();
3287         Bytes = Flags.getByValSize();
3288       } else
3289         return false;
3290     }
3291   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3292     if (Flags.isByVal())
3293       // ByVal argument is passed in as a pointer but it's now being
3294       // dereferenced. e.g.
3295       // define @foo(%struct.X* %A) {
3296       //   tail call @bar(%struct.X* byval %A)
3297       // }
3298       return false;
3299     SDValue Ptr = Ld->getBasePtr();
3300     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3301     if (!FINode)
3302       return false;
3303     FI = FINode->getIndex();
3304   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3305     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3306     FI = FINode->getIndex();
3307     Bytes = Flags.getByValSize();
3308   } else
3309     return false;
3310
3311   assert(FI != INT_MAX);
3312   if (!MFI->isFixedObjectIndex(FI))
3313     return false;
3314   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3315 }
3316
3317 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3318 /// for tail call optimization. Targets which want to do tail call
3319 /// optimization should implement this function.
3320 bool
3321 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3322                                                      CallingConv::ID CalleeCC,
3323                                                      bool isVarArg,
3324                                                      bool isCalleeStructRet,
3325                                                      bool isCallerStructRet,
3326                                                      Type *RetTy,
3327                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3328                                     const SmallVectorImpl<SDValue> &OutVals,
3329                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3330                                                      SelectionDAG &DAG) const {
3331   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3332     return false;
3333
3334   // If -tailcallopt is specified, make fastcc functions tail-callable.
3335   const MachineFunction &MF = DAG.getMachineFunction();
3336   const Function *CallerF = MF.getFunction();
3337
3338   // If the function return type is x86_fp80 and the callee return type is not,
3339   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3340   // perform a tailcall optimization here.
3341   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3342     return false;
3343
3344   CallingConv::ID CallerCC = CallerF->getCallingConv();
3345   bool CCMatch = CallerCC == CalleeCC;
3346   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3347   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3348
3349   // Win64 functions have extra shadow space for argument homing. Don't do the
3350   // sibcall if the caller and callee have mismatched expectations for this
3351   // space.
3352   if (IsCalleeWin64 != IsCallerWin64)
3353     return false;
3354
3355   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3356     if (IsTailCallConvention(CalleeCC) && CCMatch)
3357       return true;
3358     return false;
3359   }
3360
3361   // Look for obvious safe cases to perform tail call optimization that do not
3362   // require ABI changes. This is what gcc calls sibcall.
3363
3364   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3365   // emit a special epilogue.
3366   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3367   if (RegInfo->needsStackRealignment(MF))
3368     return false;
3369
3370   // Also avoid sibcall optimization if either caller or callee uses struct
3371   // return semantics.
3372   if (isCalleeStructRet || isCallerStructRet)
3373     return false;
3374
3375   // An stdcall/thiscall caller is expected to clean up its arguments; the
3376   // callee isn't going to do that.
3377   // FIXME: this is more restrictive than needed. We could produce a tailcall
3378   // when the stack adjustment matches. For example, with a thiscall that takes
3379   // only one argument.
3380   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3381                    CallerCC == CallingConv::X86_ThisCall))
3382     return false;
3383
3384   // Do not sibcall optimize vararg calls unless all arguments are passed via
3385   // registers.
3386   if (isVarArg && !Outs.empty()) {
3387
3388     // Optimizing for varargs on Win64 is unlikely to be safe without
3389     // additional testing.
3390     if (IsCalleeWin64 || IsCallerWin64)
3391       return false;
3392
3393     SmallVector<CCValAssign, 16> ArgLocs;
3394     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3395                    *DAG.getContext());
3396
3397     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3398     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3399       if (!ArgLocs[i].isRegLoc())
3400         return false;
3401   }
3402
3403   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3404   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3405   // this into a sibcall.
3406   bool Unused = false;
3407   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3408     if (!Ins[i].Used) {
3409       Unused = true;
3410       break;
3411     }
3412   }
3413   if (Unused) {
3414     SmallVector<CCValAssign, 16> RVLocs;
3415     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3416                    *DAG.getContext());
3417     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3418     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3419       CCValAssign &VA = RVLocs[i];
3420       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3421         return false;
3422     }
3423   }
3424
3425   // If the calling conventions do not match, then we'd better make sure the
3426   // results are returned in the same way as what the caller expects.
3427   if (!CCMatch) {
3428     SmallVector<CCValAssign, 16> RVLocs1;
3429     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3430                     *DAG.getContext());
3431     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3432
3433     SmallVector<CCValAssign, 16> RVLocs2;
3434     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3435                     *DAG.getContext());
3436     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3437
3438     if (RVLocs1.size() != RVLocs2.size())
3439       return false;
3440     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3441       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3442         return false;
3443       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3444         return false;
3445       if (RVLocs1[i].isRegLoc()) {
3446         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3447           return false;
3448       } else {
3449         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3450           return false;
3451       }
3452     }
3453   }
3454
3455   // If the callee takes no arguments then go on to check the results of the
3456   // call.
3457   if (!Outs.empty()) {
3458     // Check if stack adjustment is needed. For now, do not do this if any
3459     // argument is passed on the stack.
3460     SmallVector<CCValAssign, 16> ArgLocs;
3461     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3462                    *DAG.getContext());
3463
3464     // Allocate shadow area for Win64
3465     if (IsCalleeWin64)
3466       CCInfo.AllocateStack(32, 8);
3467
3468     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3469     if (CCInfo.getNextStackOffset()) {
3470       MachineFunction &MF = DAG.getMachineFunction();
3471       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3472         return false;
3473
3474       // Check if the arguments are already laid out in the right way as
3475       // the caller's fixed stack objects.
3476       MachineFrameInfo *MFI = MF.getFrameInfo();
3477       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3478       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3479       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3480         CCValAssign &VA = ArgLocs[i];
3481         SDValue Arg = OutVals[i];
3482         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3483         if (VA.getLocInfo() == CCValAssign::Indirect)
3484           return false;
3485         if (!VA.isRegLoc()) {
3486           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3487                                    MFI, MRI, TII))
3488             return false;
3489         }
3490       }
3491     }
3492
3493     // If the tailcall address may be in a register, then make sure it's
3494     // possible to register allocate for it. In 32-bit, the call address can
3495     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3496     // callee-saved registers are restored. These happen to be the same
3497     // registers used to pass 'inreg' arguments so watch out for those.
3498     if (!Subtarget->is64Bit() &&
3499         ((!isa<GlobalAddressSDNode>(Callee) &&
3500           !isa<ExternalSymbolSDNode>(Callee)) ||
3501          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3502       unsigned NumInRegs = 0;
3503       // In PIC we need an extra register to formulate the address computation
3504       // for the callee.
3505       unsigned MaxInRegs =
3506         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3507
3508       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3509         CCValAssign &VA = ArgLocs[i];
3510         if (!VA.isRegLoc())
3511           continue;
3512         unsigned Reg = VA.getLocReg();
3513         switch (Reg) {
3514         default: break;
3515         case X86::EAX: case X86::EDX: case X86::ECX:
3516           if (++NumInRegs == MaxInRegs)
3517             return false;
3518           break;
3519         }
3520       }
3521     }
3522   }
3523
3524   return true;
3525 }
3526
3527 FastISel *
3528 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3529                                   const TargetLibraryInfo *libInfo) const {
3530   return X86::createFastISel(funcInfo, libInfo);
3531 }
3532
3533 //===----------------------------------------------------------------------===//
3534 //                           Other Lowering Hooks
3535 //===----------------------------------------------------------------------===//
3536
3537 static bool MayFoldLoad(SDValue Op) {
3538   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3539 }
3540
3541 static bool MayFoldIntoStore(SDValue Op) {
3542   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3543 }
3544
3545 static bool isTargetShuffle(unsigned Opcode) {
3546   switch(Opcode) {
3547   default: return false;
3548   case X86ISD::BLENDI:
3549   case X86ISD::PSHUFB:
3550   case X86ISD::PSHUFD:
3551   case X86ISD::PSHUFHW:
3552   case X86ISD::PSHUFLW:
3553   case X86ISD::SHUFP:
3554   case X86ISD::PALIGNR:
3555   case X86ISD::MOVLHPS:
3556   case X86ISD::MOVLHPD:
3557   case X86ISD::MOVHLPS:
3558   case X86ISD::MOVLPS:
3559   case X86ISD::MOVLPD:
3560   case X86ISD::MOVSHDUP:
3561   case X86ISD::MOVSLDUP:
3562   case X86ISD::MOVDDUP:
3563   case X86ISD::MOVSS:
3564   case X86ISD::MOVSD:
3565   case X86ISD::UNPCKL:
3566   case X86ISD::UNPCKH:
3567   case X86ISD::VPERMILPI:
3568   case X86ISD::VPERM2X128:
3569   case X86ISD::VPERMI:
3570     return true;
3571   }
3572 }
3573
3574 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3575                                     SDValue V1, unsigned TargetMask,
3576                                     SelectionDAG &DAG) {
3577   switch(Opc) {
3578   default: llvm_unreachable("Unknown x86 shuffle node");
3579   case X86ISD::PSHUFD:
3580   case X86ISD::PSHUFHW:
3581   case X86ISD::PSHUFLW:
3582   case X86ISD::VPERMILPI:
3583   case X86ISD::VPERMI:
3584     return DAG.getNode(Opc, dl, VT, V1,
3585                        DAG.getConstant(TargetMask, dl, MVT::i8));
3586   }
3587 }
3588
3589 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3590                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3591   switch(Opc) {
3592   default: llvm_unreachable("Unknown x86 shuffle node");
3593   case X86ISD::MOVLHPS:
3594   case X86ISD::MOVLHPD:
3595   case X86ISD::MOVHLPS:
3596   case X86ISD::MOVLPS:
3597   case X86ISD::MOVLPD:
3598   case X86ISD::MOVSS:
3599   case X86ISD::MOVSD:
3600   case X86ISD::UNPCKL:
3601   case X86ISD::UNPCKH:
3602     return DAG.getNode(Opc, dl, VT, V1, V2);
3603   }
3604 }
3605
3606 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3607   MachineFunction &MF = DAG.getMachineFunction();
3608   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3609   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3610   int ReturnAddrIndex = FuncInfo->getRAIndex();
3611
3612   if (ReturnAddrIndex == 0) {
3613     // Set up a frame object for the return address.
3614     unsigned SlotSize = RegInfo->getSlotSize();
3615     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3616                                                            -(int64_t)SlotSize,
3617                                                            false);
3618     FuncInfo->setRAIndex(ReturnAddrIndex);
3619   }
3620
3621   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3622 }
3623
3624 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3625                                        bool hasSymbolicDisplacement) {
3626   // Offset should fit into 32 bit immediate field.
3627   if (!isInt<32>(Offset))
3628     return false;
3629
3630   // If we don't have a symbolic displacement - we don't have any extra
3631   // restrictions.
3632   if (!hasSymbolicDisplacement)
3633     return true;
3634
3635   // FIXME: Some tweaks might be needed for medium code model.
3636   if (M != CodeModel::Small && M != CodeModel::Kernel)
3637     return false;
3638
3639   // For small code model we assume that latest object is 16MB before end of 31
3640   // bits boundary. We may also accept pretty large negative constants knowing
3641   // that all objects are in the positive half of address space.
3642   if (M == CodeModel::Small && Offset < 16*1024*1024)
3643     return true;
3644
3645   // For kernel code model we know that all object resist in the negative half
3646   // of 32bits address space. We may not accept negative offsets, since they may
3647   // be just off and we may accept pretty large positive ones.
3648   if (M == CodeModel::Kernel && Offset >= 0)
3649     return true;
3650
3651   return false;
3652 }
3653
3654 /// isCalleePop - Determines whether the callee is required to pop its
3655 /// own arguments. Callee pop is necessary to support tail calls.
3656 bool X86::isCalleePop(CallingConv::ID CallingConv,
3657                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3658   switch (CallingConv) {
3659   default:
3660     return false;
3661   case CallingConv::X86_StdCall:
3662   case CallingConv::X86_FastCall:
3663   case CallingConv::X86_ThisCall:
3664     return !is64Bit;
3665   case CallingConv::Fast:
3666   case CallingConv::GHC:
3667   case CallingConv::HiPE:
3668     if (IsVarArg)
3669       return false;
3670     return TailCallOpt;
3671   }
3672 }
3673
3674 /// \brief Return true if the condition is an unsigned comparison operation.
3675 static bool isX86CCUnsigned(unsigned X86CC) {
3676   switch (X86CC) {
3677   default: llvm_unreachable("Invalid integer condition!");
3678   case X86::COND_E:     return true;
3679   case X86::COND_G:     return false;
3680   case X86::COND_GE:    return false;
3681   case X86::COND_L:     return false;
3682   case X86::COND_LE:    return false;
3683   case X86::COND_NE:    return true;
3684   case X86::COND_B:     return true;
3685   case X86::COND_A:     return true;
3686   case X86::COND_BE:    return true;
3687   case X86::COND_AE:    return true;
3688   }
3689   llvm_unreachable("covered switch fell through?!");
3690 }
3691
3692 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3693 /// specific condition code, returning the condition code and the LHS/RHS of the
3694 /// comparison to make.
3695 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3696                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3697   if (!isFP) {
3698     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3699       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3700         // X > -1   -> X == 0, jump !sign.
3701         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3702         return X86::COND_NS;
3703       }
3704       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3705         // X < 0   -> X == 0, jump on sign.
3706         return X86::COND_S;
3707       }
3708       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3709         // X < 1   -> X <= 0
3710         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3711         return X86::COND_LE;
3712       }
3713     }
3714
3715     switch (SetCCOpcode) {
3716     default: llvm_unreachable("Invalid integer condition!");
3717     case ISD::SETEQ:  return X86::COND_E;
3718     case ISD::SETGT:  return X86::COND_G;
3719     case ISD::SETGE:  return X86::COND_GE;
3720     case ISD::SETLT:  return X86::COND_L;
3721     case ISD::SETLE:  return X86::COND_LE;
3722     case ISD::SETNE:  return X86::COND_NE;
3723     case ISD::SETULT: return X86::COND_B;
3724     case ISD::SETUGT: return X86::COND_A;
3725     case ISD::SETULE: return X86::COND_BE;
3726     case ISD::SETUGE: return X86::COND_AE;
3727     }
3728   }
3729
3730   // First determine if it is required or is profitable to flip the operands.
3731
3732   // If LHS is a foldable load, but RHS is not, flip the condition.
3733   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3734       !ISD::isNON_EXTLoad(RHS.getNode())) {
3735     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3736     std::swap(LHS, RHS);
3737   }
3738
3739   switch (SetCCOpcode) {
3740   default: break;
3741   case ISD::SETOLT:
3742   case ISD::SETOLE:
3743   case ISD::SETUGT:
3744   case ISD::SETUGE:
3745     std::swap(LHS, RHS);
3746     break;
3747   }
3748
3749   // On a floating point condition, the flags are set as follows:
3750   // ZF  PF  CF   op
3751   //  0 | 0 | 0 | X > Y
3752   //  0 | 0 | 1 | X < Y
3753   //  1 | 0 | 0 | X == Y
3754   //  1 | 1 | 1 | unordered
3755   switch (SetCCOpcode) {
3756   default: llvm_unreachable("Condcode should be pre-legalized away");
3757   case ISD::SETUEQ:
3758   case ISD::SETEQ:   return X86::COND_E;
3759   case ISD::SETOLT:              // flipped
3760   case ISD::SETOGT:
3761   case ISD::SETGT:   return X86::COND_A;
3762   case ISD::SETOLE:              // flipped
3763   case ISD::SETOGE:
3764   case ISD::SETGE:   return X86::COND_AE;
3765   case ISD::SETUGT:              // flipped
3766   case ISD::SETULT:
3767   case ISD::SETLT:   return X86::COND_B;
3768   case ISD::SETUGE:              // flipped
3769   case ISD::SETULE:
3770   case ISD::SETLE:   return X86::COND_BE;
3771   case ISD::SETONE:
3772   case ISD::SETNE:   return X86::COND_NE;
3773   case ISD::SETUO:   return X86::COND_P;
3774   case ISD::SETO:    return X86::COND_NP;
3775   case ISD::SETOEQ:
3776   case ISD::SETUNE:  return X86::COND_INVALID;
3777   }
3778 }
3779
3780 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3781 /// code. Current x86 isa includes the following FP cmov instructions:
3782 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3783 static bool hasFPCMov(unsigned X86CC) {
3784   switch (X86CC) {
3785   default:
3786     return false;
3787   case X86::COND_B:
3788   case X86::COND_BE:
3789   case X86::COND_E:
3790   case X86::COND_P:
3791   case X86::COND_A:
3792   case X86::COND_AE:
3793   case X86::COND_NE:
3794   case X86::COND_NP:
3795     return true;
3796   }
3797 }
3798
3799 /// isFPImmLegal - Returns true if the target can instruction select the
3800 /// specified FP immediate natively. If false, the legalizer will
3801 /// materialize the FP immediate as a load from a constant pool.
3802 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3803   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3804     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3805       return true;
3806   }
3807   return false;
3808 }
3809
3810 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3811                                               ISD::LoadExtType ExtTy,
3812                                               EVT NewVT) const {
3813   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3814   // relocation target a movq or addq instruction: don't let the load shrink.
3815   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3816   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3817     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3818       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3819   return true;
3820 }
3821
3822 /// \brief Returns true if it is beneficial to convert a load of a constant
3823 /// to just the constant itself.
3824 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3825                                                           Type *Ty) const {
3826   assert(Ty->isIntegerTy());
3827
3828   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3829   if (BitSize == 0 || BitSize > 64)
3830     return false;
3831   return true;
3832 }
3833
3834 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3835                                                 unsigned Index) const {
3836   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3837     return false;
3838
3839   return (Index == 0 || Index == ResVT.getVectorNumElements());
3840 }
3841
3842 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3843   // Speculate cttz only if we can directly use TZCNT.
3844   return Subtarget->hasBMI();
3845 }
3846
3847 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3848   // Speculate ctlz only if we can directly use LZCNT.
3849   return Subtarget->hasLZCNT();
3850 }
3851
3852 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3853 /// the specified range (L, H].
3854 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3855   return (Val < 0) || (Val >= Low && Val < Hi);
3856 }
3857
3858 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3859 /// specified value.
3860 static bool isUndefOrEqual(int Val, int CmpVal) {
3861   return (Val < 0 || Val == CmpVal);
3862 }
3863
3864 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3865 /// from position Pos and ending in Pos+Size, falls within the specified
3866 /// sequential range (Low, Low+Size]. or is undef.
3867 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3868                                        unsigned Pos, unsigned Size, int Low) {
3869   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3870     if (!isUndefOrEqual(Mask[i], Low))
3871       return false;
3872   return true;
3873 }
3874
3875 /// isVEXTRACTIndex - Return true if the specified
3876 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3877 /// suitable for instruction that extract 128 or 256 bit vectors
3878 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3879   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3880   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3881     return false;
3882
3883   // The index should be aligned on a vecWidth-bit boundary.
3884   uint64_t Index =
3885     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3886
3887   MVT VT = N->getSimpleValueType(0);
3888   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3889   bool Result = (Index * ElSize) % vecWidth == 0;
3890
3891   return Result;
3892 }
3893
3894 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3895 /// operand specifies a subvector insert that is suitable for input to
3896 /// insertion of 128 or 256-bit subvectors
3897 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3898   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3899   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3900     return false;
3901   // The index should be aligned on a vecWidth-bit boundary.
3902   uint64_t Index =
3903     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3904
3905   MVT VT = N->getSimpleValueType(0);
3906   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3907   bool Result = (Index * ElSize) % vecWidth == 0;
3908
3909   return Result;
3910 }
3911
3912 bool X86::isVINSERT128Index(SDNode *N) {
3913   return isVINSERTIndex(N, 128);
3914 }
3915
3916 bool X86::isVINSERT256Index(SDNode *N) {
3917   return isVINSERTIndex(N, 256);
3918 }
3919
3920 bool X86::isVEXTRACT128Index(SDNode *N) {
3921   return isVEXTRACTIndex(N, 128);
3922 }
3923
3924 bool X86::isVEXTRACT256Index(SDNode *N) {
3925   return isVEXTRACTIndex(N, 256);
3926 }
3927
3928 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3929   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3930   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3931     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3932
3933   uint64_t Index =
3934     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3935
3936   MVT VecVT = N->getOperand(0).getSimpleValueType();
3937   MVT ElVT = VecVT.getVectorElementType();
3938
3939   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3940   return Index / NumElemsPerChunk;
3941 }
3942
3943 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3944   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3945   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3946     llvm_unreachable("Illegal insert subvector for VINSERT");
3947
3948   uint64_t Index =
3949     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3950
3951   MVT VecVT = N->getSimpleValueType(0);
3952   MVT ElVT = VecVT.getVectorElementType();
3953
3954   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3955   return Index / NumElemsPerChunk;
3956 }
3957
3958 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3959 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3960 /// and VINSERTI128 instructions.
3961 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3962   return getExtractVEXTRACTImmediate(N, 128);
3963 }
3964
3965 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3966 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3967 /// and VINSERTI64x4 instructions.
3968 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3969   return getExtractVEXTRACTImmediate(N, 256);
3970 }
3971
3972 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3973 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3974 /// and VINSERTI128 instructions.
3975 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3976   return getInsertVINSERTImmediate(N, 128);
3977 }
3978
3979 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3980 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3981 /// and VINSERTI64x4 instructions.
3982 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3983   return getInsertVINSERTImmediate(N, 256);
3984 }
3985
3986 /// isZero - Returns true if Elt is a constant integer zero
3987 static bool isZero(SDValue V) {
3988   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3989   return C && C->isNullValue();
3990 }
3991
3992 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3993 /// constant +0.0.
3994 bool X86::isZeroNode(SDValue Elt) {
3995   if (isZero(Elt))
3996     return true;
3997   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3998     return CFP->getValueAPF().isPosZero();
3999   return false;
4000 }
4001
4002 /// getZeroVector - Returns a vector of specified type with all zero elements.
4003 ///
4004 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4005                              SelectionDAG &DAG, SDLoc dl) {
4006   assert(VT.isVector() && "Expected a vector type");
4007
4008   // Always build SSE zero vectors as <4 x i32> bitcasted
4009   // to their dest type. This ensures they get CSE'd.
4010   SDValue Vec;
4011   if (VT.is128BitVector()) {  // SSE
4012     if (Subtarget->hasSSE2()) {  // SSE2
4013       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4014       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4015     } else { // SSE1
4016       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4017       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4018     }
4019   } else if (VT.is256BitVector()) { // AVX
4020     if (Subtarget->hasInt256()) { // AVX2
4021       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4022       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4023       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4024     } else {
4025       // 256-bit logic and arithmetic instructions in AVX are all
4026       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4027       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4028       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4029       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4030     }
4031   } else if (VT.is512BitVector()) { // AVX-512
4032       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4033       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4034                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4035       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4036   } else if (VT.getScalarType() == MVT::i1) {
4037
4038     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4039             && "Unexpected vector type");
4040     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4041             && "Unexpected vector type");
4042     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4043     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4044     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4045   } else
4046     llvm_unreachable("Unexpected vector type");
4047
4048   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4049 }
4050
4051 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4052                                 SelectionDAG &DAG, SDLoc dl,
4053                                 unsigned vectorWidth) {
4054   assert((vectorWidth == 128 || vectorWidth == 256) &&
4055          "Unsupported vector width");
4056   EVT VT = Vec.getValueType();
4057   EVT ElVT = VT.getVectorElementType();
4058   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4059   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4060                                   VT.getVectorNumElements()/Factor);
4061
4062   // Extract from UNDEF is UNDEF.
4063   if (Vec.getOpcode() == ISD::UNDEF)
4064     return DAG.getUNDEF(ResultVT);
4065
4066   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4067   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4068
4069   // This is the index of the first element of the vectorWidth-bit chunk
4070   // we want.
4071   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4072                                * ElemsPerChunk);
4073
4074   // If the input is a buildvector just emit a smaller one.
4075   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4076     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4077                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4078                                     ElemsPerChunk));
4079
4080   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4081   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4082 }
4083
4084 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4085 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4086 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4087 /// instructions or a simple subregister reference. Idx is an index in the
4088 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4089 /// lowering EXTRACT_VECTOR_ELT operations easier.
4090 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4091                                    SelectionDAG &DAG, SDLoc dl) {
4092   assert((Vec.getValueType().is256BitVector() ||
4093           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4094   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4095 }
4096
4097 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4098 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4099                                    SelectionDAG &DAG, SDLoc dl) {
4100   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4101   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4102 }
4103
4104 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4105                                unsigned IdxVal, SelectionDAG &DAG,
4106                                SDLoc dl, unsigned vectorWidth) {
4107   assert((vectorWidth == 128 || vectorWidth == 256) &&
4108          "Unsupported vector width");
4109   // Inserting UNDEF is Result
4110   if (Vec.getOpcode() == ISD::UNDEF)
4111     return Result;
4112   EVT VT = Vec.getValueType();
4113   EVT ElVT = VT.getVectorElementType();
4114   EVT ResultVT = Result.getValueType();
4115
4116   // Insert the relevant vectorWidth bits.
4117   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4118
4119   // This is the index of the first element of the vectorWidth-bit chunk
4120   // we want.
4121   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4122                                * ElemsPerChunk);
4123
4124   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4125   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4126 }
4127
4128 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4129 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4130 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4131 /// simple superregister reference.  Idx is an index in the 128 bits
4132 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4133 /// lowering INSERT_VECTOR_ELT operations easier.
4134 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4135                                   SelectionDAG &DAG, SDLoc dl) {
4136   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4137
4138   // For insertion into the zero index (low half) of a 256-bit vector, it is
4139   // more efficient to generate a blend with immediate instead of an insert*128.
4140   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4141   // extend the subvector to the size of the result vector. Make sure that
4142   // we are not recursing on that node by checking for undef here.
4143   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4144       Result.getOpcode() != ISD::UNDEF) {
4145     EVT ResultVT = Result.getValueType();
4146     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4147     SDValue Undef = DAG.getUNDEF(ResultVT);
4148     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4149                                  Vec, ZeroIndex);
4150
4151     // The blend instruction, and therefore its mask, depend on the data type.
4152     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4153     if (ScalarType.isFloatingPoint()) {
4154       // Choose either vblendps (float) or vblendpd (double).
4155       unsigned ScalarSize = ScalarType.getSizeInBits();
4156       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4157       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4158       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4159       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4160     }
4161
4162     const X86Subtarget &Subtarget =
4163     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4164
4165     // AVX2 is needed for 256-bit integer blend support.
4166     // Integers must be cast to 32-bit because there is only vpblendd;
4167     // vpblendw can't be used for this because it has a handicapped mask.
4168
4169     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4170     // is still more efficient than using the wrong domain vinsertf128 that
4171     // will be created by InsertSubVector().
4172     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4173
4174     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4175     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4176     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4177     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4178   }
4179
4180   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4181 }
4182
4183 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4184                                   SelectionDAG &DAG, SDLoc dl) {
4185   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4186   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4187 }
4188
4189 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4190 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4191 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4192 /// large BUILD_VECTORS.
4193 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4194                                    unsigned NumElems, SelectionDAG &DAG,
4195                                    SDLoc dl) {
4196   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4197   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4198 }
4199
4200 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4201                                    unsigned NumElems, SelectionDAG &DAG,
4202                                    SDLoc dl) {
4203   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4204   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4205 }
4206
4207 /// getOnesVector - Returns a vector of specified type with all bits set.
4208 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4209 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4210 /// Then bitcast to their original type, ensuring they get CSE'd.
4211 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4212                              SDLoc dl) {
4213   assert(VT.isVector() && "Expected a vector type");
4214
4215   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4216   SDValue Vec;
4217   if (VT.is256BitVector()) {
4218     if (HasInt256) { // AVX2
4219       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4220       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4221     } else { // AVX
4222       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4223       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4224     }
4225   } else if (VT.is128BitVector()) {
4226     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4227   } else
4228     llvm_unreachable("Unexpected vector type");
4229
4230   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4231 }
4232
4233 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4234 /// operation of specified width.
4235 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4236                        SDValue V2) {
4237   unsigned NumElems = VT.getVectorNumElements();
4238   SmallVector<int, 8> Mask;
4239   Mask.push_back(NumElems);
4240   for (unsigned i = 1; i != NumElems; ++i)
4241     Mask.push_back(i);
4242   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4243 }
4244
4245 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4246 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4247                           SDValue V2) {
4248   unsigned NumElems = VT.getVectorNumElements();
4249   SmallVector<int, 8> Mask;
4250   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4251     Mask.push_back(i);
4252     Mask.push_back(i + NumElems);
4253   }
4254   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4255 }
4256
4257 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4258 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4259                           SDValue V2) {
4260   unsigned NumElems = VT.getVectorNumElements();
4261   SmallVector<int, 8> Mask;
4262   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4263     Mask.push_back(i + Half);
4264     Mask.push_back(i + NumElems + Half);
4265   }
4266   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4267 }
4268
4269 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4270 /// vector of zero or undef vector.  This produces a shuffle where the low
4271 /// element of V2 is swizzled into the zero/undef vector, landing at element
4272 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4273 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4274                                            bool IsZero,
4275                                            const X86Subtarget *Subtarget,
4276                                            SelectionDAG &DAG) {
4277   MVT VT = V2.getSimpleValueType();
4278   SDValue V1 = IsZero
4279     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4280   unsigned NumElems = VT.getVectorNumElements();
4281   SmallVector<int, 16> MaskVec;
4282   for (unsigned i = 0; i != NumElems; ++i)
4283     // If this is the insertion idx, put the low elt of V2 here.
4284     MaskVec.push_back(i == Idx ? NumElems : i);
4285   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4286 }
4287
4288 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4289 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4290 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4291 /// shuffles which use a single input multiple times, and in those cases it will
4292 /// adjust the mask to only have indices within that single input.
4293 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4294                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4295   unsigned NumElems = VT.getVectorNumElements();
4296   SDValue ImmN;
4297
4298   IsUnary = false;
4299   bool IsFakeUnary = false;
4300   switch(N->getOpcode()) {
4301   case X86ISD::BLENDI:
4302     ImmN = N->getOperand(N->getNumOperands()-1);
4303     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4304     break;
4305   case X86ISD::SHUFP:
4306     ImmN = N->getOperand(N->getNumOperands()-1);
4307     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4308     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4309     break;
4310   case X86ISD::UNPCKH:
4311     DecodeUNPCKHMask(VT, Mask);
4312     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4313     break;
4314   case X86ISD::UNPCKL:
4315     DecodeUNPCKLMask(VT, Mask);
4316     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4317     break;
4318   case X86ISD::MOVHLPS:
4319     DecodeMOVHLPSMask(NumElems, Mask);
4320     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4321     break;
4322   case X86ISD::MOVLHPS:
4323     DecodeMOVLHPSMask(NumElems, Mask);
4324     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4325     break;
4326   case X86ISD::PALIGNR:
4327     ImmN = N->getOperand(N->getNumOperands()-1);
4328     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4329     break;
4330   case X86ISD::PSHUFD:
4331   case X86ISD::VPERMILPI:
4332     ImmN = N->getOperand(N->getNumOperands()-1);
4333     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4334     IsUnary = true;
4335     break;
4336   case X86ISD::PSHUFHW:
4337     ImmN = N->getOperand(N->getNumOperands()-1);
4338     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4339     IsUnary = true;
4340     break;
4341   case X86ISD::PSHUFLW:
4342     ImmN = N->getOperand(N->getNumOperands()-1);
4343     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4344     IsUnary = true;
4345     break;
4346   case X86ISD::PSHUFB: {
4347     IsUnary = true;
4348     SDValue MaskNode = N->getOperand(1);
4349     while (MaskNode->getOpcode() == ISD::BITCAST)
4350       MaskNode = MaskNode->getOperand(0);
4351
4352     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4353       // If we have a build-vector, then things are easy.
4354       EVT VT = MaskNode.getValueType();
4355       assert(VT.isVector() &&
4356              "Can't produce a non-vector with a build_vector!");
4357       if (!VT.isInteger())
4358         return false;
4359
4360       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4361
4362       SmallVector<uint64_t, 32> RawMask;
4363       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4364         SDValue Op = MaskNode->getOperand(i);
4365         if (Op->getOpcode() == ISD::UNDEF) {
4366           RawMask.push_back((uint64_t)SM_SentinelUndef);
4367           continue;
4368         }
4369         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4370         if (!CN)
4371           return false;
4372         APInt MaskElement = CN->getAPIntValue();
4373
4374         // We now have to decode the element which could be any integer size and
4375         // extract each byte of it.
4376         for (int j = 0; j < NumBytesPerElement; ++j) {
4377           // Note that this is x86 and so always little endian: the low byte is
4378           // the first byte of the mask.
4379           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4380           MaskElement = MaskElement.lshr(8);
4381         }
4382       }
4383       DecodePSHUFBMask(RawMask, Mask);
4384       break;
4385     }
4386
4387     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4388     if (!MaskLoad)
4389       return false;
4390
4391     SDValue Ptr = MaskLoad->getBasePtr();
4392     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4393         Ptr->getOpcode() == X86ISD::WrapperRIP)
4394       Ptr = Ptr->getOperand(0);
4395
4396     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4397     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4398       return false;
4399
4400     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4401       DecodePSHUFBMask(C, Mask);
4402       if (Mask.empty())
4403         return false;
4404       break;
4405     }
4406
4407     return false;
4408   }
4409   case X86ISD::VPERMI:
4410     ImmN = N->getOperand(N->getNumOperands()-1);
4411     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4412     IsUnary = true;
4413     break;
4414   case X86ISD::MOVSS:
4415   case X86ISD::MOVSD:
4416     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4417     break;
4418   case X86ISD::VPERM2X128:
4419     ImmN = N->getOperand(N->getNumOperands()-1);
4420     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4421     if (Mask.empty()) return false;
4422     break;
4423   case X86ISD::MOVSLDUP:
4424     DecodeMOVSLDUPMask(VT, Mask);
4425     IsUnary = true;
4426     break;
4427   case X86ISD::MOVSHDUP:
4428     DecodeMOVSHDUPMask(VT, Mask);
4429     IsUnary = true;
4430     break;
4431   case X86ISD::MOVDDUP:
4432     DecodeMOVDDUPMask(VT, Mask);
4433     IsUnary = true;
4434     break;
4435   case X86ISD::MOVLHPD:
4436   case X86ISD::MOVLPD:
4437   case X86ISD::MOVLPS:
4438     // Not yet implemented
4439     return false;
4440   default: llvm_unreachable("unknown target shuffle node");
4441   }
4442
4443   // If we have a fake unary shuffle, the shuffle mask is spread across two
4444   // inputs that are actually the same node. Re-map the mask to always point
4445   // into the first input.
4446   if (IsFakeUnary)
4447     for (int &M : Mask)
4448       if (M >= (int)Mask.size())
4449         M -= Mask.size();
4450
4451   return true;
4452 }
4453
4454 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4455 /// element of the result of the vector shuffle.
4456 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4457                                    unsigned Depth) {
4458   if (Depth == 6)
4459     return SDValue();  // Limit search depth.
4460
4461   SDValue V = SDValue(N, 0);
4462   EVT VT = V.getValueType();
4463   unsigned Opcode = V.getOpcode();
4464
4465   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4466   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4467     int Elt = SV->getMaskElt(Index);
4468
4469     if (Elt < 0)
4470       return DAG.getUNDEF(VT.getVectorElementType());
4471
4472     unsigned NumElems = VT.getVectorNumElements();
4473     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4474                                          : SV->getOperand(1);
4475     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4476   }
4477
4478   // Recurse into target specific vector shuffles to find scalars.
4479   if (isTargetShuffle(Opcode)) {
4480     MVT ShufVT = V.getSimpleValueType();
4481     unsigned NumElems = ShufVT.getVectorNumElements();
4482     SmallVector<int, 16> ShuffleMask;
4483     bool IsUnary;
4484
4485     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4486       return SDValue();
4487
4488     int Elt = ShuffleMask[Index];
4489     if (Elt < 0)
4490       return DAG.getUNDEF(ShufVT.getVectorElementType());
4491
4492     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4493                                          : N->getOperand(1);
4494     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4495                                Depth+1);
4496   }
4497
4498   // Actual nodes that may contain scalar elements
4499   if (Opcode == ISD::BITCAST) {
4500     V = V.getOperand(0);
4501     EVT SrcVT = V.getValueType();
4502     unsigned NumElems = VT.getVectorNumElements();
4503
4504     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4505       return SDValue();
4506   }
4507
4508   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4509     return (Index == 0) ? V.getOperand(0)
4510                         : DAG.getUNDEF(VT.getVectorElementType());
4511
4512   if (V.getOpcode() == ISD::BUILD_VECTOR)
4513     return V.getOperand(Index);
4514
4515   return SDValue();
4516 }
4517
4518 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4519 ///
4520 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4521                                        unsigned NumNonZero, unsigned NumZero,
4522                                        SelectionDAG &DAG,
4523                                        const X86Subtarget* Subtarget,
4524                                        const TargetLowering &TLI) {
4525   if (NumNonZero > 8)
4526     return SDValue();
4527
4528   SDLoc dl(Op);
4529   SDValue V;
4530   bool First = true;
4531
4532   // SSE4.1 - use PINSRB to insert each byte directly.
4533   if (Subtarget->hasSSE41()) {
4534     for (unsigned i = 0; i < 16; ++i) {
4535       bool isNonZero = (NonZeros & (1 << i)) != 0;
4536       if (isNonZero) {
4537         if (First) {
4538           if (NumZero)
4539             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4540           else
4541             V = DAG.getUNDEF(MVT::v16i8);
4542           First = false;
4543         }
4544         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4545                         MVT::v16i8, V, Op.getOperand(i),
4546                         DAG.getIntPtrConstant(i, dl));
4547       }
4548     }
4549
4550     return V;
4551   }
4552
4553   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4554   for (unsigned i = 0; i < 16; ++i) {
4555     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4556     if (ThisIsNonZero && First) {
4557       if (NumZero)
4558         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4559       else
4560         V = DAG.getUNDEF(MVT::v8i16);
4561       First = false;
4562     }
4563
4564     if ((i & 1) != 0) {
4565       SDValue ThisElt, LastElt;
4566       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4567       if (LastIsNonZero) {
4568         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4569                               MVT::i16, Op.getOperand(i-1));
4570       }
4571       if (ThisIsNonZero) {
4572         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4573         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4574                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4575         if (LastIsNonZero)
4576           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4577       } else
4578         ThisElt = LastElt;
4579
4580       if (ThisElt.getNode())
4581         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4582                         DAG.getIntPtrConstant(i/2, dl));
4583     }
4584   }
4585
4586   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4587 }
4588
4589 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4590 ///
4591 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4592                                      unsigned NumNonZero, unsigned NumZero,
4593                                      SelectionDAG &DAG,
4594                                      const X86Subtarget* Subtarget,
4595                                      const TargetLowering &TLI) {
4596   if (NumNonZero > 4)
4597     return SDValue();
4598
4599   SDLoc dl(Op);
4600   SDValue V;
4601   bool First = true;
4602   for (unsigned i = 0; i < 8; ++i) {
4603     bool isNonZero = (NonZeros & (1 << i)) != 0;
4604     if (isNonZero) {
4605       if (First) {
4606         if (NumZero)
4607           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4608         else
4609           V = DAG.getUNDEF(MVT::v8i16);
4610         First = false;
4611       }
4612       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4613                       MVT::v8i16, V, Op.getOperand(i),
4614                       DAG.getIntPtrConstant(i, dl));
4615     }
4616   }
4617
4618   return V;
4619 }
4620
4621 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4622 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4623                                      const X86Subtarget *Subtarget,
4624                                      const TargetLowering &TLI) {
4625   // Find all zeroable elements.
4626   std::bitset<4> Zeroable;
4627   for (int i=0; i < 4; ++i) {
4628     SDValue Elt = Op->getOperand(i);
4629     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4630   }
4631   assert(Zeroable.size() - Zeroable.count() > 1 &&
4632          "We expect at least two non-zero elements!");
4633
4634   // We only know how to deal with build_vector nodes where elements are either
4635   // zeroable or extract_vector_elt with constant index.
4636   SDValue FirstNonZero;
4637   unsigned FirstNonZeroIdx;
4638   for (unsigned i=0; i < 4; ++i) {
4639     if (Zeroable[i])
4640       continue;
4641     SDValue Elt = Op->getOperand(i);
4642     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4643         !isa<ConstantSDNode>(Elt.getOperand(1)))
4644       return SDValue();
4645     // Make sure that this node is extracting from a 128-bit vector.
4646     MVT VT = Elt.getOperand(0).getSimpleValueType();
4647     if (!VT.is128BitVector())
4648       return SDValue();
4649     if (!FirstNonZero.getNode()) {
4650       FirstNonZero = Elt;
4651       FirstNonZeroIdx = i;
4652     }
4653   }
4654
4655   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4656   SDValue V1 = FirstNonZero.getOperand(0);
4657   MVT VT = V1.getSimpleValueType();
4658
4659   // See if this build_vector can be lowered as a blend with zero.
4660   SDValue Elt;
4661   unsigned EltMaskIdx, EltIdx;
4662   int Mask[4];
4663   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4664     if (Zeroable[EltIdx]) {
4665       // The zero vector will be on the right hand side.
4666       Mask[EltIdx] = EltIdx+4;
4667       continue;
4668     }
4669
4670     Elt = Op->getOperand(EltIdx);
4671     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4672     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4673     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4674       break;
4675     Mask[EltIdx] = EltIdx;
4676   }
4677
4678   if (EltIdx == 4) {
4679     // Let the shuffle legalizer deal with blend operations.
4680     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4681     if (V1.getSimpleValueType() != VT)
4682       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4683     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4684   }
4685
4686   // See if we can lower this build_vector to a INSERTPS.
4687   if (!Subtarget->hasSSE41())
4688     return SDValue();
4689
4690   SDValue V2 = Elt.getOperand(0);
4691   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4692     V1 = SDValue();
4693
4694   bool CanFold = true;
4695   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4696     if (Zeroable[i])
4697       continue;
4698
4699     SDValue Current = Op->getOperand(i);
4700     SDValue SrcVector = Current->getOperand(0);
4701     if (!V1.getNode())
4702       V1 = SrcVector;
4703     CanFold = SrcVector == V1 &&
4704       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4705   }
4706
4707   if (!CanFold)
4708     return SDValue();
4709
4710   assert(V1.getNode() && "Expected at least two non-zero elements!");
4711   if (V1.getSimpleValueType() != MVT::v4f32)
4712     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4713   if (V2.getSimpleValueType() != MVT::v4f32)
4714     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4715
4716   // Ok, we can emit an INSERTPS instruction.
4717   unsigned ZMask = Zeroable.to_ulong();
4718
4719   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4720   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4721   SDLoc DL(Op);
4722   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4723                                DAG.getIntPtrConstant(InsertPSMask, DL));
4724   return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4725 }
4726
4727 /// Return a vector logical shift node.
4728 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4729                          unsigned NumBits, SelectionDAG &DAG,
4730                          const TargetLowering &TLI, SDLoc dl) {
4731   assert(VT.is128BitVector() && "Unknown type for VShift");
4732   MVT ShVT = MVT::v2i64;
4733   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4734   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4735   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4736   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4737   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4738   return DAG.getNode(ISD::BITCAST, dl, VT,
4739                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4740 }
4741
4742 static SDValue
4743 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4744
4745   // Check if the scalar load can be widened into a vector load. And if
4746   // the address is "base + cst" see if the cst can be "absorbed" into
4747   // the shuffle mask.
4748   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4749     SDValue Ptr = LD->getBasePtr();
4750     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4751       return SDValue();
4752     EVT PVT = LD->getValueType(0);
4753     if (PVT != MVT::i32 && PVT != MVT::f32)
4754       return SDValue();
4755
4756     int FI = -1;
4757     int64_t Offset = 0;
4758     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4759       FI = FINode->getIndex();
4760       Offset = 0;
4761     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4762                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4763       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4764       Offset = Ptr.getConstantOperandVal(1);
4765       Ptr = Ptr.getOperand(0);
4766     } else {
4767       return SDValue();
4768     }
4769
4770     // FIXME: 256-bit vector instructions don't require a strict alignment,
4771     // improve this code to support it better.
4772     unsigned RequiredAlign = VT.getSizeInBits()/8;
4773     SDValue Chain = LD->getChain();
4774     // Make sure the stack object alignment is at least 16 or 32.
4775     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4776     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4777       if (MFI->isFixedObjectIndex(FI)) {
4778         // Can't change the alignment. FIXME: It's possible to compute
4779         // the exact stack offset and reference FI + adjust offset instead.
4780         // If someone *really* cares about this. That's the way to implement it.
4781         return SDValue();
4782       } else {
4783         MFI->setObjectAlignment(FI, RequiredAlign);
4784       }
4785     }
4786
4787     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4788     // Ptr + (Offset & ~15).
4789     if (Offset < 0)
4790       return SDValue();
4791     if ((Offset % RequiredAlign) & 3)
4792       return SDValue();
4793     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4794     if (StartOffset) {
4795       SDLoc DL(Ptr);
4796       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4797                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4798     }
4799
4800     int EltNo = (Offset - StartOffset) >> 2;
4801     unsigned NumElems = VT.getVectorNumElements();
4802
4803     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4804     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4805                              LD->getPointerInfo().getWithOffset(StartOffset),
4806                              false, false, false, 0);
4807
4808     SmallVector<int, 8> Mask(NumElems, EltNo);
4809
4810     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4811   }
4812
4813   return SDValue();
4814 }
4815
4816 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4817 /// elements can be replaced by a single large load which has the same value as
4818 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4819 ///
4820 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4821 ///
4822 /// FIXME: we'd also like to handle the case where the last elements are zero
4823 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4824 /// There's even a handy isZeroNode for that purpose.
4825 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4826                                         SDLoc &DL, SelectionDAG &DAG,
4827                                         bool isAfterLegalize) {
4828   unsigned NumElems = Elts.size();
4829
4830   LoadSDNode *LDBase = nullptr;
4831   unsigned LastLoadedElt = -1U;
4832
4833   // For each element in the initializer, see if we've found a load or an undef.
4834   // If we don't find an initial load element, or later load elements are
4835   // non-consecutive, bail out.
4836   for (unsigned i = 0; i < NumElems; ++i) {
4837     SDValue Elt = Elts[i];
4838     // Look through a bitcast.
4839     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4840       Elt = Elt.getOperand(0);
4841     if (!Elt.getNode() ||
4842         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4843       return SDValue();
4844     if (!LDBase) {
4845       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4846         return SDValue();
4847       LDBase = cast<LoadSDNode>(Elt.getNode());
4848       LastLoadedElt = i;
4849       continue;
4850     }
4851     if (Elt.getOpcode() == ISD::UNDEF)
4852       continue;
4853
4854     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4855     EVT LdVT = Elt.getValueType();
4856     // Each loaded element must be the correct fractional portion of the
4857     // requested vector load.
4858     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4859       return SDValue();
4860     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4861       return SDValue();
4862     LastLoadedElt = i;
4863   }
4864
4865   // If we have found an entire vector of loads and undefs, then return a large
4866   // load of the entire vector width starting at the base pointer.  If we found
4867   // consecutive loads for the low half, generate a vzext_load node.
4868   if (LastLoadedElt == NumElems - 1) {
4869     assert(LDBase && "Did not find base load for merging consecutive loads");
4870     EVT EltVT = LDBase->getValueType(0);
4871     // Ensure that the input vector size for the merged loads matches the
4872     // cumulative size of the input elements.
4873     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4874       return SDValue();
4875
4876     if (isAfterLegalize &&
4877         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4878       return SDValue();
4879
4880     SDValue NewLd = SDValue();
4881
4882     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4883                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4884                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4885                         LDBase->getAlignment());
4886
4887     if (LDBase->hasAnyUseOfValue(1)) {
4888       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4889                                      SDValue(LDBase, 1),
4890                                      SDValue(NewLd.getNode(), 1));
4891       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4892       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4893                              SDValue(NewLd.getNode(), 1));
4894     }
4895
4896     return NewLd;
4897   }
4898
4899   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4900   //of a v4i32 / v4f32. It's probably worth generalizing.
4901   EVT EltVT = VT.getVectorElementType();
4902   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4903       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4904     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4905     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4906     SDValue ResNode =
4907         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4908                                 LDBase->getPointerInfo(),
4909                                 LDBase->getAlignment(),
4910                                 false/*isVolatile*/, true/*ReadMem*/,
4911                                 false/*WriteMem*/);
4912
4913     // Make sure the newly-created LOAD is in the same position as LDBase in
4914     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4915     // update uses of LDBase's output chain to use the TokenFactor.
4916     if (LDBase->hasAnyUseOfValue(1)) {
4917       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4918                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4919       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4920       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4921                              SDValue(ResNode.getNode(), 1));
4922     }
4923
4924     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4925   }
4926   return SDValue();
4927 }
4928
4929 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4930 /// to generate a splat value for the following cases:
4931 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4932 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4933 /// a scalar load, or a constant.
4934 /// The VBROADCAST node is returned when a pattern is found,
4935 /// or SDValue() otherwise.
4936 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4937                                     SelectionDAG &DAG) {
4938   // VBROADCAST requires AVX.
4939   // TODO: Splats could be generated for non-AVX CPUs using SSE
4940   // instructions, but there's less potential gain for only 128-bit vectors.
4941   if (!Subtarget->hasAVX())
4942     return SDValue();
4943
4944   MVT VT = Op.getSimpleValueType();
4945   SDLoc dl(Op);
4946
4947   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4948          "Unsupported vector type for broadcast.");
4949
4950   SDValue Ld;
4951   bool ConstSplatVal;
4952
4953   switch (Op.getOpcode()) {
4954     default:
4955       // Unknown pattern found.
4956       return SDValue();
4957
4958     case ISD::BUILD_VECTOR: {
4959       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4960       BitVector UndefElements;
4961       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4962
4963       // We need a splat of a single value to use broadcast, and it doesn't
4964       // make any sense if the value is only in one element of the vector.
4965       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4966         return SDValue();
4967
4968       Ld = Splat;
4969       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4970                        Ld.getOpcode() == ISD::ConstantFP);
4971
4972       // Make sure that all of the users of a non-constant load are from the
4973       // BUILD_VECTOR node.
4974       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4975         return SDValue();
4976       break;
4977     }
4978
4979     case ISD::VECTOR_SHUFFLE: {
4980       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4981
4982       // Shuffles must have a splat mask where the first element is
4983       // broadcasted.
4984       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4985         return SDValue();
4986
4987       SDValue Sc = Op.getOperand(0);
4988       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4989           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4990
4991         if (!Subtarget->hasInt256())
4992           return SDValue();
4993
4994         // Use the register form of the broadcast instruction available on AVX2.
4995         if (VT.getSizeInBits() >= 256)
4996           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4997         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4998       }
4999
5000       Ld = Sc.getOperand(0);
5001       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5002                        Ld.getOpcode() == ISD::ConstantFP);
5003
5004       // The scalar_to_vector node and the suspected
5005       // load node must have exactly one user.
5006       // Constants may have multiple users.
5007
5008       // AVX-512 has register version of the broadcast
5009       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5010         Ld.getValueType().getSizeInBits() >= 32;
5011       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5012           !hasRegVer))
5013         return SDValue();
5014       break;
5015     }
5016   }
5017
5018   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5019   bool IsGE256 = (VT.getSizeInBits() >= 256);
5020
5021   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5022   // instruction to save 8 or more bytes of constant pool data.
5023   // TODO: If multiple splats are generated to load the same constant,
5024   // it may be detrimental to overall size. There needs to be a way to detect
5025   // that condition to know if this is truly a size win.
5026   const Function *F = DAG.getMachineFunction().getFunction();
5027   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5028
5029   // Handle broadcasting a single constant scalar from the constant pool
5030   // into a vector.
5031   // On Sandybridge (no AVX2), it is still better to load a constant vector
5032   // from the constant pool and not to broadcast it from a scalar.
5033   // But override that restriction when optimizing for size.
5034   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5035   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5036     EVT CVT = Ld.getValueType();
5037     assert(!CVT.isVector() && "Must not broadcast a vector type");
5038
5039     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5040     // For size optimization, also splat v2f64 and v2i64, and for size opt
5041     // with AVX2, also splat i8 and i16.
5042     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5043     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5044         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5045       const Constant *C = nullptr;
5046       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5047         C = CI->getConstantIntValue();
5048       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5049         C = CF->getConstantFPValue();
5050
5051       assert(C && "Invalid constant type");
5052
5053       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5054       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5055       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5056       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5057                        MachinePointerInfo::getConstantPool(),
5058                        false, false, false, Alignment);
5059
5060       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5061     }
5062   }
5063
5064   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5065
5066   // Handle AVX2 in-register broadcasts.
5067   if (!IsLoad && Subtarget->hasInt256() &&
5068       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5069     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5070
5071   // The scalar source must be a normal load.
5072   if (!IsLoad)
5073     return SDValue();
5074
5075   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5076       (Subtarget->hasVLX() && ScalarSize == 64))
5077     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5078
5079   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5080   // double since there is no vbroadcastsd xmm
5081   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5082     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5083       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5084   }
5085
5086   // Unsupported broadcast.
5087   return SDValue();
5088 }
5089
5090 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5091 /// underlying vector and index.
5092 ///
5093 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5094 /// index.
5095 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5096                                          SDValue ExtIdx) {
5097   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5098   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5099     return Idx;
5100
5101   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5102   // lowered this:
5103   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5104   // to:
5105   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5106   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5107   //                           undef)
5108   //                       Constant<0>)
5109   // In this case the vector is the extract_subvector expression and the index
5110   // is 2, as specified by the shuffle.
5111   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5112   SDValue ShuffleVec = SVOp->getOperand(0);
5113   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5114   assert(ShuffleVecVT.getVectorElementType() ==
5115          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5116
5117   int ShuffleIdx = SVOp->getMaskElt(Idx);
5118   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5119     ExtractedFromVec = ShuffleVec;
5120     return ShuffleIdx;
5121   }
5122   return Idx;
5123 }
5124
5125 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5126   MVT VT = Op.getSimpleValueType();
5127
5128   // Skip if insert_vec_elt is not supported.
5129   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5130   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5131     return SDValue();
5132
5133   SDLoc DL(Op);
5134   unsigned NumElems = Op.getNumOperands();
5135
5136   SDValue VecIn1;
5137   SDValue VecIn2;
5138   SmallVector<unsigned, 4> InsertIndices;
5139   SmallVector<int, 8> Mask(NumElems, -1);
5140
5141   for (unsigned i = 0; i != NumElems; ++i) {
5142     unsigned Opc = Op.getOperand(i).getOpcode();
5143
5144     if (Opc == ISD::UNDEF)
5145       continue;
5146
5147     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5148       // Quit if more than 1 elements need inserting.
5149       if (InsertIndices.size() > 1)
5150         return SDValue();
5151
5152       InsertIndices.push_back(i);
5153       continue;
5154     }
5155
5156     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5157     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5158     // Quit if non-constant index.
5159     if (!isa<ConstantSDNode>(ExtIdx))
5160       return SDValue();
5161     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5162
5163     // Quit if extracted from vector of different type.
5164     if (ExtractedFromVec.getValueType() != VT)
5165       return SDValue();
5166
5167     if (!VecIn1.getNode())
5168       VecIn1 = ExtractedFromVec;
5169     else if (VecIn1 != ExtractedFromVec) {
5170       if (!VecIn2.getNode())
5171         VecIn2 = ExtractedFromVec;
5172       else if (VecIn2 != ExtractedFromVec)
5173         // Quit if more than 2 vectors to shuffle
5174         return SDValue();
5175     }
5176
5177     if (ExtractedFromVec == VecIn1)
5178       Mask[i] = Idx;
5179     else if (ExtractedFromVec == VecIn2)
5180       Mask[i] = Idx + NumElems;
5181   }
5182
5183   if (!VecIn1.getNode())
5184     return SDValue();
5185
5186   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5187   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5188   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5189     unsigned Idx = InsertIndices[i];
5190     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5191                      DAG.getIntPtrConstant(Idx, DL));
5192   }
5193
5194   return NV;
5195 }
5196
5197 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5198 SDValue
5199 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5200
5201   MVT VT = Op.getSimpleValueType();
5202   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5203          "Unexpected type in LowerBUILD_VECTORvXi1!");
5204
5205   SDLoc dl(Op);
5206   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5207     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5208     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5209     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5210   }
5211
5212   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5213     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5214     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5215     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5216   }
5217
5218   bool AllContants = true;
5219   uint64_t Immediate = 0;
5220   int NonConstIdx = -1;
5221   bool IsSplat = true;
5222   unsigned NumNonConsts = 0;
5223   unsigned NumConsts = 0;
5224   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5225     SDValue In = Op.getOperand(idx);
5226     if (In.getOpcode() == ISD::UNDEF)
5227       continue;
5228     if (!isa<ConstantSDNode>(In)) {
5229       AllContants = false;
5230       NonConstIdx = idx;
5231       NumNonConsts++;
5232     } else {
5233       NumConsts++;
5234       if (cast<ConstantSDNode>(In)->getZExtValue())
5235       Immediate |= (1ULL << idx);
5236     }
5237     if (In != Op.getOperand(0))
5238       IsSplat = false;
5239   }
5240
5241   if (AllContants) {
5242     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5243       DAG.getConstant(Immediate, dl, MVT::i16));
5244     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5245                        DAG.getIntPtrConstant(0, dl));
5246   }
5247
5248   if (NumNonConsts == 1 && NonConstIdx != 0) {
5249     SDValue DstVec;
5250     if (NumConsts) {
5251       SDValue VecAsImm = DAG.getConstant(Immediate, dl,
5252                                          MVT::getIntegerVT(VT.getSizeInBits()));
5253       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5254     }
5255     else
5256       DstVec = DAG.getUNDEF(VT);
5257     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5258                        Op.getOperand(NonConstIdx),
5259                        DAG.getIntPtrConstant(NonConstIdx, dl));
5260   }
5261   if (!IsSplat && (NonConstIdx != 0))
5262     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5263   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5264   SDValue Select;
5265   if (IsSplat)
5266     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5267                           DAG.getConstant(-1, dl, SelectVT),
5268                           DAG.getConstant(0, dl, SelectVT));
5269   else
5270     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5271                          DAG.getConstant((Immediate | 1), dl, SelectVT),
5272                          DAG.getConstant(Immediate, dl, SelectVT));
5273   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5274 }
5275
5276 /// \brief Return true if \p N implements a horizontal binop and return the
5277 /// operands for the horizontal binop into V0 and V1.
5278 ///
5279 /// This is a helper function of LowerToHorizontalOp().
5280 /// This function checks that the build_vector \p N in input implements a
5281 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5282 /// operation to match.
5283 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5284 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5285 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5286 /// arithmetic sub.
5287 ///
5288 /// This function only analyzes elements of \p N whose indices are
5289 /// in range [BaseIdx, LastIdx).
5290 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5291                               SelectionDAG &DAG,
5292                               unsigned BaseIdx, unsigned LastIdx,
5293                               SDValue &V0, SDValue &V1) {
5294   EVT VT = N->getValueType(0);
5295
5296   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5297   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5298          "Invalid Vector in input!");
5299
5300   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5301   bool CanFold = true;
5302   unsigned ExpectedVExtractIdx = BaseIdx;
5303   unsigned NumElts = LastIdx - BaseIdx;
5304   V0 = DAG.getUNDEF(VT);
5305   V1 = DAG.getUNDEF(VT);
5306
5307   // Check if N implements a horizontal binop.
5308   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5309     SDValue Op = N->getOperand(i + BaseIdx);
5310
5311     // Skip UNDEFs.
5312     if (Op->getOpcode() == ISD::UNDEF) {
5313       // Update the expected vector extract index.
5314       if (i * 2 == NumElts)
5315         ExpectedVExtractIdx = BaseIdx;
5316       ExpectedVExtractIdx += 2;
5317       continue;
5318     }
5319
5320     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5321
5322     if (!CanFold)
5323       break;
5324
5325     SDValue Op0 = Op.getOperand(0);
5326     SDValue Op1 = Op.getOperand(1);
5327
5328     // Try to match the following pattern:
5329     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5330     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5331         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5332         Op0.getOperand(0) == Op1.getOperand(0) &&
5333         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5334         isa<ConstantSDNode>(Op1.getOperand(1)));
5335     if (!CanFold)
5336       break;
5337
5338     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5339     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5340
5341     if (i * 2 < NumElts) {
5342       if (V0.getOpcode() == ISD::UNDEF) {
5343         V0 = Op0.getOperand(0);
5344         if (V0.getValueType() != VT)
5345           return false;
5346       }
5347     } else {
5348       if (V1.getOpcode() == ISD::UNDEF) {
5349         V1 = Op0.getOperand(0);
5350         if (V1.getValueType() != VT)
5351           return false;
5352       }
5353       if (i * 2 == NumElts)
5354         ExpectedVExtractIdx = BaseIdx;
5355     }
5356
5357     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5358     if (I0 == ExpectedVExtractIdx)
5359       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5360     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5361       // Try to match the following dag sequence:
5362       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5363       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5364     } else
5365       CanFold = false;
5366
5367     ExpectedVExtractIdx += 2;
5368   }
5369
5370   return CanFold;
5371 }
5372
5373 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5374 /// a concat_vector.
5375 ///
5376 /// This is a helper function of LowerToHorizontalOp().
5377 /// This function expects two 256-bit vectors called V0 and V1.
5378 /// At first, each vector is split into two separate 128-bit vectors.
5379 /// Then, the resulting 128-bit vectors are used to implement two
5380 /// horizontal binary operations.
5381 ///
5382 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5383 ///
5384 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5385 /// the two new horizontal binop.
5386 /// When Mode is set, the first horizontal binop dag node would take as input
5387 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5388 /// horizontal binop dag node would take as input the lower 128-bit of V1
5389 /// and the upper 128-bit of V1.
5390 ///   Example:
5391 ///     HADD V0_LO, V0_HI
5392 ///     HADD V1_LO, V1_HI
5393 ///
5394 /// Otherwise, the first horizontal binop dag node takes as input the lower
5395 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5396 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5397 ///   Example:
5398 ///     HADD V0_LO, V1_LO
5399 ///     HADD V0_HI, V1_HI
5400 ///
5401 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5402 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5403 /// the upper 128-bits of the result.
5404 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5405                                      SDLoc DL, SelectionDAG &DAG,
5406                                      unsigned X86Opcode, bool Mode,
5407                                      bool isUndefLO, bool isUndefHI) {
5408   EVT VT = V0.getValueType();
5409   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5410          "Invalid nodes in input!");
5411
5412   unsigned NumElts = VT.getVectorNumElements();
5413   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5414   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5415   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5416   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5417   EVT NewVT = V0_LO.getValueType();
5418
5419   SDValue LO = DAG.getUNDEF(NewVT);
5420   SDValue HI = DAG.getUNDEF(NewVT);
5421
5422   if (Mode) {
5423     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5424     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5425       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5426     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5427       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5428   } else {
5429     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5430     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5431                        V1_LO->getOpcode() != ISD::UNDEF))
5432       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5433
5434     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5435                        V1_HI->getOpcode() != ISD::UNDEF))
5436       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5437   }
5438
5439   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5440 }
5441
5442 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5443 /// node.
5444 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5445                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5446   EVT VT = BV->getValueType(0);
5447   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5448       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5449     return SDValue();
5450
5451   SDLoc DL(BV);
5452   unsigned NumElts = VT.getVectorNumElements();
5453   SDValue InVec0 = DAG.getUNDEF(VT);
5454   SDValue InVec1 = DAG.getUNDEF(VT);
5455
5456   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5457           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5458
5459   // Odd-numbered elements in the input build vector are obtained from
5460   // adding two integer/float elements.
5461   // Even-numbered elements in the input build vector are obtained from
5462   // subtracting two integer/float elements.
5463   unsigned ExpectedOpcode = ISD::FSUB;
5464   unsigned NextExpectedOpcode = ISD::FADD;
5465   bool AddFound = false;
5466   bool SubFound = false;
5467
5468   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5469     SDValue Op = BV->getOperand(i);
5470
5471     // Skip 'undef' values.
5472     unsigned Opcode = Op.getOpcode();
5473     if (Opcode == ISD::UNDEF) {
5474       std::swap(ExpectedOpcode, NextExpectedOpcode);
5475       continue;
5476     }
5477
5478     // Early exit if we found an unexpected opcode.
5479     if (Opcode != ExpectedOpcode)
5480       return SDValue();
5481
5482     SDValue Op0 = Op.getOperand(0);
5483     SDValue Op1 = Op.getOperand(1);
5484
5485     // Try to match the following pattern:
5486     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5487     // Early exit if we cannot match that sequence.
5488     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5489         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5490         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5491         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5492         Op0.getOperand(1) != Op1.getOperand(1))
5493       return SDValue();
5494
5495     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5496     if (I0 != i)
5497       return SDValue();
5498
5499     // We found a valid add/sub node. Update the information accordingly.
5500     if (i & 1)
5501       AddFound = true;
5502     else
5503       SubFound = true;
5504
5505     // Update InVec0 and InVec1.
5506     if (InVec0.getOpcode() == ISD::UNDEF) {
5507       InVec0 = Op0.getOperand(0);
5508       if (InVec0.getValueType() != VT)
5509         return SDValue();
5510     }
5511     if (InVec1.getOpcode() == ISD::UNDEF) {
5512       InVec1 = Op1.getOperand(0);
5513       if (InVec1.getValueType() != VT)
5514         return SDValue();
5515     }
5516
5517     // Make sure that operands in input to each add/sub node always
5518     // come from a same pair of vectors.
5519     if (InVec0 != Op0.getOperand(0)) {
5520       if (ExpectedOpcode == ISD::FSUB)
5521         return SDValue();
5522
5523       // FADD is commutable. Try to commute the operands
5524       // and then test again.
5525       std::swap(Op0, Op1);
5526       if (InVec0 != Op0.getOperand(0))
5527         return SDValue();
5528     }
5529
5530     if (InVec1 != Op1.getOperand(0))
5531       return SDValue();
5532
5533     // Update the pair of expected opcodes.
5534     std::swap(ExpectedOpcode, NextExpectedOpcode);
5535   }
5536
5537   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5538   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5539       InVec1.getOpcode() != ISD::UNDEF)
5540     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5541
5542   return SDValue();
5543 }
5544
5545 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5546 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5547                                    const X86Subtarget *Subtarget,
5548                                    SelectionDAG &DAG) {
5549   EVT VT = BV->getValueType(0);
5550   unsigned NumElts = VT.getVectorNumElements();
5551   unsigned NumUndefsLO = 0;
5552   unsigned NumUndefsHI = 0;
5553   unsigned Half = NumElts/2;
5554
5555   // Count the number of UNDEF operands in the build_vector in input.
5556   for (unsigned i = 0, e = Half; i != e; ++i)
5557     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5558       NumUndefsLO++;
5559
5560   for (unsigned i = Half, e = NumElts; i != e; ++i)
5561     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5562       NumUndefsHI++;
5563
5564   // Early exit if this is either a build_vector of all UNDEFs or all the
5565   // operands but one are UNDEF.
5566   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5567     return SDValue();
5568
5569   SDLoc DL(BV);
5570   SDValue InVec0, InVec1;
5571   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5572     // Try to match an SSE3 float HADD/HSUB.
5573     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5574       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5575
5576     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5577       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5578   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5579     // Try to match an SSSE3 integer HADD/HSUB.
5580     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5581       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5582
5583     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5584       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5585   }
5586
5587   if (!Subtarget->hasAVX())
5588     return SDValue();
5589
5590   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5591     // Try to match an AVX horizontal add/sub of packed single/double
5592     // precision floating point values from 256-bit vectors.
5593     SDValue InVec2, InVec3;
5594     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5595         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5596         ((InVec0.getOpcode() == ISD::UNDEF ||
5597           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5598         ((InVec1.getOpcode() == ISD::UNDEF ||
5599           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5600       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5601
5602     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5603         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5604         ((InVec0.getOpcode() == ISD::UNDEF ||
5605           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5606         ((InVec1.getOpcode() == ISD::UNDEF ||
5607           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5608       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5609   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5610     // Try to match an AVX2 horizontal add/sub of signed integers.
5611     SDValue InVec2, InVec3;
5612     unsigned X86Opcode;
5613     bool CanFold = true;
5614
5615     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5616         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5617         ((InVec0.getOpcode() == ISD::UNDEF ||
5618           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5619         ((InVec1.getOpcode() == ISD::UNDEF ||
5620           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5621       X86Opcode = X86ISD::HADD;
5622     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5623         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5624         ((InVec0.getOpcode() == ISD::UNDEF ||
5625           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5626         ((InVec1.getOpcode() == ISD::UNDEF ||
5627           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5628       X86Opcode = X86ISD::HSUB;
5629     else
5630       CanFold = false;
5631
5632     if (CanFold) {
5633       // Fold this build_vector into a single horizontal add/sub.
5634       // Do this only if the target has AVX2.
5635       if (Subtarget->hasAVX2())
5636         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5637
5638       // Do not try to expand this build_vector into a pair of horizontal
5639       // add/sub if we can emit a pair of scalar add/sub.
5640       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5641         return SDValue();
5642
5643       // Convert this build_vector into a pair of horizontal binop followed by
5644       // a concat vector.
5645       bool isUndefLO = NumUndefsLO == Half;
5646       bool isUndefHI = NumUndefsHI == Half;
5647       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5648                                    isUndefLO, isUndefHI);
5649     }
5650   }
5651
5652   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5653        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5654     unsigned X86Opcode;
5655     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5656       X86Opcode = X86ISD::HADD;
5657     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5658       X86Opcode = X86ISD::HSUB;
5659     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5660       X86Opcode = X86ISD::FHADD;
5661     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5662       X86Opcode = X86ISD::FHSUB;
5663     else
5664       return SDValue();
5665
5666     // Don't try to expand this build_vector into a pair of horizontal add/sub
5667     // if we can simply emit a pair of scalar add/sub.
5668     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5669       return SDValue();
5670
5671     // Convert this build_vector into two horizontal add/sub followed by
5672     // a concat vector.
5673     bool isUndefLO = NumUndefsLO == Half;
5674     bool isUndefHI = NumUndefsHI == Half;
5675     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5676                                  isUndefLO, isUndefHI);
5677   }
5678
5679   return SDValue();
5680 }
5681
5682 SDValue
5683 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5684   SDLoc dl(Op);
5685
5686   MVT VT = Op.getSimpleValueType();
5687   MVT ExtVT = VT.getVectorElementType();
5688   unsigned NumElems = Op.getNumOperands();
5689
5690   // Generate vectors for predicate vectors.
5691   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5692     return LowerBUILD_VECTORvXi1(Op, DAG);
5693
5694   // Vectors containing all zeros can be matched by pxor and xorps later
5695   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5696     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5697     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5698     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5699       return Op;
5700
5701     return getZeroVector(VT, Subtarget, DAG, dl);
5702   }
5703
5704   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5705   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5706   // vpcmpeqd on 256-bit vectors.
5707   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5708     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5709       return Op;
5710
5711     if (!VT.is512BitVector())
5712       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5713   }
5714
5715   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5716   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5717     return AddSub;
5718   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5719     return HorizontalOp;
5720   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5721     return Broadcast;
5722
5723   unsigned EVTBits = ExtVT.getSizeInBits();
5724
5725   unsigned NumZero  = 0;
5726   unsigned NumNonZero = 0;
5727   unsigned NonZeros = 0;
5728   bool IsAllConstants = true;
5729   SmallSet<SDValue, 8> Values;
5730   for (unsigned i = 0; i < NumElems; ++i) {
5731     SDValue Elt = Op.getOperand(i);
5732     if (Elt.getOpcode() == ISD::UNDEF)
5733       continue;
5734     Values.insert(Elt);
5735     if (Elt.getOpcode() != ISD::Constant &&
5736         Elt.getOpcode() != ISD::ConstantFP)
5737       IsAllConstants = false;
5738     if (X86::isZeroNode(Elt))
5739       NumZero++;
5740     else {
5741       NonZeros |= (1 << i);
5742       NumNonZero++;
5743     }
5744   }
5745
5746   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5747   if (NumNonZero == 0)
5748     return DAG.getUNDEF(VT);
5749
5750   // Special case for single non-zero, non-undef, element.
5751   if (NumNonZero == 1) {
5752     unsigned Idx = countTrailingZeros(NonZeros);
5753     SDValue Item = Op.getOperand(Idx);
5754
5755     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5756     // the value are obviously zero, truncate the value to i32 and do the
5757     // insertion that way.  Only do this if the value is non-constant or if the
5758     // value is a constant being inserted into element 0.  It is cheaper to do
5759     // a constant pool load than it is to do a movd + shuffle.
5760     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5761         (!IsAllConstants || Idx == 0)) {
5762       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5763         // Handle SSE only.
5764         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5765         EVT VecVT = MVT::v4i32;
5766
5767         // Truncate the value (which may itself be a constant) to i32, and
5768         // convert it to a vector with movd (S2V+shuffle to zero extend).
5769         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5770         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5771         return DAG.getNode(
5772             ISD::BITCAST, dl, VT,
5773             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5774       }
5775     }
5776
5777     // If we have a constant or non-constant insertion into the low element of
5778     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5779     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5780     // depending on what the source datatype is.
5781     if (Idx == 0) {
5782       if (NumZero == 0)
5783         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5784
5785       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5786           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5787         if (VT.is512BitVector()) {
5788           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5789           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5790                              Item, DAG.getIntPtrConstant(0, dl));
5791         }
5792         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5793                "Expected an SSE value type!");
5794         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5795         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5796         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5797       }
5798
5799       // We can't directly insert an i8 or i16 into a vector, so zero extend
5800       // it to i32 first.
5801       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5802         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5803         if (VT.is256BitVector()) {
5804           if (Subtarget->hasAVX()) {
5805             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5806             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5807           } else {
5808             // Without AVX, we need to extend to a 128-bit vector and then
5809             // insert into the 256-bit vector.
5810             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5811             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5812             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5813           }
5814         } else {
5815           assert(VT.is128BitVector() && "Expected an SSE value type!");
5816           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5817           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5818         }
5819         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5820       }
5821     }
5822
5823     // Is it a vector logical left shift?
5824     if (NumElems == 2 && Idx == 1 &&
5825         X86::isZeroNode(Op.getOperand(0)) &&
5826         !X86::isZeroNode(Op.getOperand(1))) {
5827       unsigned NumBits = VT.getSizeInBits();
5828       return getVShift(true, VT,
5829                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5830                                    VT, Op.getOperand(1)),
5831                        NumBits/2, DAG, *this, dl);
5832     }
5833
5834     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5835       return SDValue();
5836
5837     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5838     // is a non-constant being inserted into an element other than the low one,
5839     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5840     // movd/movss) to move this into the low element, then shuffle it into
5841     // place.
5842     if (EVTBits == 32) {
5843       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5844       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5845     }
5846   }
5847
5848   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5849   if (Values.size() == 1) {
5850     if (EVTBits == 32) {
5851       // Instead of a shuffle like this:
5852       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5853       // Check if it's possible to issue this instead.
5854       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5855       unsigned Idx = countTrailingZeros(NonZeros);
5856       SDValue Item = Op.getOperand(Idx);
5857       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5858         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5859     }
5860     return SDValue();
5861   }
5862
5863   // A vector full of immediates; various special cases are already
5864   // handled, so this is best done with a single constant-pool load.
5865   if (IsAllConstants)
5866     return SDValue();
5867
5868   // For AVX-length vectors, see if we can use a vector load to get all of the
5869   // elements, otherwise build the individual 128-bit pieces and use
5870   // shuffles to put them in place.
5871   if (VT.is256BitVector() || VT.is512BitVector()) {
5872     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5873
5874     // Check for a build vector of consecutive loads.
5875     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5876       return LD;
5877
5878     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5879
5880     // Build both the lower and upper subvector.
5881     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5882                                 makeArrayRef(&V[0], NumElems/2));
5883     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5884                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5885
5886     // Recreate the wider vector with the lower and upper part.
5887     if (VT.is256BitVector())
5888       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5889     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5890   }
5891
5892   // Let legalizer expand 2-wide build_vectors.
5893   if (EVTBits == 64) {
5894     if (NumNonZero == 1) {
5895       // One half is zero or undef.
5896       unsigned Idx = countTrailingZeros(NonZeros);
5897       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5898                                  Op.getOperand(Idx));
5899       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5900     }
5901     return SDValue();
5902   }
5903
5904   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5905   if (EVTBits == 8 && NumElems == 16)
5906     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5907                                         Subtarget, *this))
5908       return V;
5909
5910   if (EVTBits == 16 && NumElems == 8)
5911     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5912                                       Subtarget, *this))
5913       return V;
5914
5915   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5916   if (EVTBits == 32 && NumElems == 4)
5917     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5918       return V;
5919
5920   // If element VT is == 32 bits, turn it into a number of shuffles.
5921   SmallVector<SDValue, 8> V(NumElems);
5922   if (NumElems == 4 && NumZero > 0) {
5923     for (unsigned i = 0; i < 4; ++i) {
5924       bool isZero = !(NonZeros & (1 << i));
5925       if (isZero)
5926         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5927       else
5928         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5929     }
5930
5931     for (unsigned i = 0; i < 2; ++i) {
5932       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5933         default: break;
5934         case 0:
5935           V[i] = V[i*2];  // Must be a zero vector.
5936           break;
5937         case 1:
5938           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5939           break;
5940         case 2:
5941           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5942           break;
5943         case 3:
5944           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5945           break;
5946       }
5947     }
5948
5949     bool Reverse1 = (NonZeros & 0x3) == 2;
5950     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5951     int MaskVec[] = {
5952       Reverse1 ? 1 : 0,
5953       Reverse1 ? 0 : 1,
5954       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5955       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5956     };
5957     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5958   }
5959
5960   if (Values.size() > 1 && VT.is128BitVector()) {
5961     // Check for a build vector of consecutive loads.
5962     for (unsigned i = 0; i < NumElems; ++i)
5963       V[i] = Op.getOperand(i);
5964
5965     // Check for elements which are consecutive loads.
5966     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5967       return LD;
5968
5969     // Check for a build vector from mostly shuffle plus few inserting.
5970     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5971       return Sh;
5972
5973     // For SSE 4.1, use insertps to put the high elements into the low element.
5974     if (Subtarget->hasSSE41()) {
5975       SDValue Result;
5976       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5977         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5978       else
5979         Result = DAG.getUNDEF(VT);
5980
5981       for (unsigned i = 1; i < NumElems; ++i) {
5982         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5983         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5984                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
5985       }
5986       return Result;
5987     }
5988
5989     // Otherwise, expand into a number of unpckl*, start by extending each of
5990     // our (non-undef) elements to the full vector width with the element in the
5991     // bottom slot of the vector (which generates no code for SSE).
5992     for (unsigned i = 0; i < NumElems; ++i) {
5993       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5994         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5995       else
5996         V[i] = DAG.getUNDEF(VT);
5997     }
5998
5999     // Next, we iteratively mix elements, e.g. for v4f32:
6000     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6001     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6002     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6003     unsigned EltStride = NumElems >> 1;
6004     while (EltStride != 0) {
6005       for (unsigned i = 0; i < EltStride; ++i) {
6006         // If V[i+EltStride] is undef and this is the first round of mixing,
6007         // then it is safe to just drop this shuffle: V[i] is already in the
6008         // right place, the one element (since it's the first round) being
6009         // inserted as undef can be dropped.  This isn't safe for successive
6010         // rounds because they will permute elements within both vectors.
6011         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6012             EltStride == NumElems/2)
6013           continue;
6014
6015         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6016       }
6017       EltStride >>= 1;
6018     }
6019     return V[0];
6020   }
6021   return SDValue();
6022 }
6023
6024 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6025 // to create 256-bit vectors from two other 128-bit ones.
6026 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6027   SDLoc dl(Op);
6028   MVT ResVT = Op.getSimpleValueType();
6029
6030   assert((ResVT.is256BitVector() ||
6031           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6032
6033   SDValue V1 = Op.getOperand(0);
6034   SDValue V2 = Op.getOperand(1);
6035   unsigned NumElems = ResVT.getVectorNumElements();
6036   if (ResVT.is256BitVector())
6037     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6038
6039   if (Op.getNumOperands() == 4) {
6040     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6041                                 ResVT.getVectorNumElements()/2);
6042     SDValue V3 = Op.getOperand(2);
6043     SDValue V4 = Op.getOperand(3);
6044     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6045       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6046   }
6047   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6048 }
6049
6050 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6051                                        const X86Subtarget *Subtarget,
6052                                        SelectionDAG & DAG) {
6053   SDLoc dl(Op);
6054   MVT ResVT = Op.getSimpleValueType();
6055   unsigned NumOfOperands = Op.getNumOperands();
6056
6057   assert(isPowerOf2_32(NumOfOperands) &&
6058          "Unexpected number of operands in CONCAT_VECTORS");
6059
6060   if (NumOfOperands > 2) {
6061     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6062                                   ResVT.getVectorNumElements()/2);
6063     SmallVector<SDValue, 2> Ops;
6064     for (unsigned i = 0; i < NumOfOperands/2; i++)
6065       Ops.push_back(Op.getOperand(i));
6066     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6067     Ops.clear();
6068     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6069       Ops.push_back(Op.getOperand(i));
6070     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6071     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6072   }
6073
6074   SDValue V1 = Op.getOperand(0);
6075   SDValue V2 = Op.getOperand(1);
6076   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6077   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6078
6079   if (IsZeroV1 && IsZeroV2)
6080     return getZeroVector(ResVT, Subtarget, DAG, dl);
6081
6082   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6083   SDValue Undef = DAG.getUNDEF(ResVT);
6084   unsigned NumElems = ResVT.getVectorNumElements();
6085   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6086
6087   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6088   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6089   if (IsZeroV1)
6090     return V2;
6091
6092   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6093   // Zero the upper bits of V1
6094   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6095   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6096   if (IsZeroV2)
6097     return V1;
6098   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6099 }
6100
6101 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6102                                    const X86Subtarget *Subtarget,
6103                                    SelectionDAG &DAG) {
6104   MVT VT = Op.getSimpleValueType();
6105   if (VT.getVectorElementType() == MVT::i1)
6106     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6107
6108   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6109          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6110           Op.getNumOperands() == 4)));
6111
6112   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6113   // from two other 128-bit ones.
6114
6115   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6116   return LowerAVXCONCAT_VECTORS(Op, DAG);
6117 }
6118
6119
6120 //===----------------------------------------------------------------------===//
6121 // Vector shuffle lowering
6122 //
6123 // This is an experimental code path for lowering vector shuffles on x86. It is
6124 // designed to handle arbitrary vector shuffles and blends, gracefully
6125 // degrading performance as necessary. It works hard to recognize idiomatic
6126 // shuffles and lower them to optimal instruction patterns without leaving
6127 // a framework that allows reasonably efficient handling of all vector shuffle
6128 // patterns.
6129 //===----------------------------------------------------------------------===//
6130
6131 /// \brief Tiny helper function to identify a no-op mask.
6132 ///
6133 /// This is a somewhat boring predicate function. It checks whether the mask
6134 /// array input, which is assumed to be a single-input shuffle mask of the kind
6135 /// used by the X86 shuffle instructions (not a fully general
6136 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6137 /// in-place shuffle are 'no-op's.
6138 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6139   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6140     if (Mask[i] != -1 && Mask[i] != i)
6141       return false;
6142   return true;
6143 }
6144
6145 /// \brief Helper function to classify a mask as a single-input mask.
6146 ///
6147 /// This isn't a generic single-input test because in the vector shuffle
6148 /// lowering we canonicalize single inputs to be the first input operand. This
6149 /// means we can more quickly test for a single input by only checking whether
6150 /// an input from the second operand exists. We also assume that the size of
6151 /// mask corresponds to the size of the input vectors which isn't true in the
6152 /// fully general case.
6153 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6154   for (int M : Mask)
6155     if (M >= (int)Mask.size())
6156       return false;
6157   return true;
6158 }
6159
6160 /// \brief Test whether there are elements crossing 128-bit lanes in this
6161 /// shuffle mask.
6162 ///
6163 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6164 /// and we routinely test for these.
6165 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6166   int LaneSize = 128 / VT.getScalarSizeInBits();
6167   int Size = Mask.size();
6168   for (int i = 0; i < Size; ++i)
6169     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6170       return true;
6171   return false;
6172 }
6173
6174 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6175 ///
6176 /// This checks a shuffle mask to see if it is performing the same
6177 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6178 /// that it is also not lane-crossing. It may however involve a blend from the
6179 /// same lane of a second vector.
6180 ///
6181 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6182 /// non-trivial to compute in the face of undef lanes. The representation is
6183 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6184 /// entries from both V1 and V2 inputs to the wider mask.
6185 static bool
6186 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6187                                 SmallVectorImpl<int> &RepeatedMask) {
6188   int LaneSize = 128 / VT.getScalarSizeInBits();
6189   RepeatedMask.resize(LaneSize, -1);
6190   int Size = Mask.size();
6191   for (int i = 0; i < Size; ++i) {
6192     if (Mask[i] < 0)
6193       continue;
6194     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6195       // This entry crosses lanes, so there is no way to model this shuffle.
6196       return false;
6197
6198     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6199     if (RepeatedMask[i % LaneSize] == -1)
6200       // This is the first non-undef entry in this slot of a 128-bit lane.
6201       RepeatedMask[i % LaneSize] =
6202           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6203     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6204       // Found a mismatch with the repeated mask.
6205       return false;
6206   }
6207   return true;
6208 }
6209
6210 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6211 /// arguments.
6212 ///
6213 /// This is a fast way to test a shuffle mask against a fixed pattern:
6214 ///
6215 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6216 ///
6217 /// It returns true if the mask is exactly as wide as the argument list, and
6218 /// each element of the mask is either -1 (signifying undef) or the value given
6219 /// in the argument.
6220 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6221                                 ArrayRef<int> ExpectedMask) {
6222   if (Mask.size() != ExpectedMask.size())
6223     return false;
6224
6225   int Size = Mask.size();
6226
6227   // If the values are build vectors, we can look through them to find
6228   // equivalent inputs that make the shuffles equivalent.
6229   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6230   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6231
6232   for (int i = 0; i < Size; ++i)
6233     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6234       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6235       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6236       if (!MaskBV || !ExpectedBV ||
6237           MaskBV->getOperand(Mask[i] % Size) !=
6238               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6239         return false;
6240     }
6241
6242   return true;
6243 }
6244
6245 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6246 ///
6247 /// This helper function produces an 8-bit shuffle immediate corresponding to
6248 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6249 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6250 /// example.
6251 ///
6252 /// NB: We rely heavily on "undef" masks preserving the input lane.
6253 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6254                                           SelectionDAG &DAG) {
6255   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6256   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6257   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6258   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6259   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6260
6261   unsigned Imm = 0;
6262   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6263   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6264   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6265   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6266   return DAG.getConstant(Imm, DL, MVT::i8);
6267 }
6268
6269 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6270 ///
6271 /// This is used as a fallback approach when first class blend instructions are
6272 /// unavailable. Currently it is only suitable for integer vectors, but could
6273 /// be generalized for floating point vectors if desirable.
6274 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6275                                             SDValue V2, ArrayRef<int> Mask,
6276                                             SelectionDAG &DAG) {
6277   assert(VT.isInteger() && "Only supports integer vector types!");
6278   MVT EltVT = VT.getScalarType();
6279   int NumEltBits = EltVT.getSizeInBits();
6280   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6281   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6282                                     EltVT);
6283   SmallVector<SDValue, 16> MaskOps;
6284   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6285     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6286       return SDValue(); // Shuffled input!
6287     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6288   }
6289
6290   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6291   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6292   // We have to cast V2 around.
6293   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6294   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6295                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6296                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6297                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6298   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6299 }
6300
6301 /// \brief Try to emit a blend instruction for a shuffle.
6302 ///
6303 /// This doesn't do any checks for the availability of instructions for blending
6304 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6305 /// be matched in the backend with the type given. What it does check for is
6306 /// that the shuffle mask is in fact a blend.
6307 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6308                                          SDValue V2, ArrayRef<int> Mask,
6309                                          const X86Subtarget *Subtarget,
6310                                          SelectionDAG &DAG) {
6311   unsigned BlendMask = 0;
6312   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6313     if (Mask[i] >= Size) {
6314       if (Mask[i] != i + Size)
6315         return SDValue(); // Shuffled V2 input!
6316       BlendMask |= 1u << i;
6317       continue;
6318     }
6319     if (Mask[i] >= 0 && Mask[i] != i)
6320       return SDValue(); // Shuffled V1 input!
6321   }
6322   switch (VT.SimpleTy) {
6323   case MVT::v2f64:
6324   case MVT::v4f32:
6325   case MVT::v4f64:
6326   case MVT::v8f32:
6327     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6328                        DAG.getConstant(BlendMask, DL, MVT::i8));
6329
6330   case MVT::v4i64:
6331   case MVT::v8i32:
6332     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6333     // FALLTHROUGH
6334   case MVT::v2i64:
6335   case MVT::v4i32:
6336     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6337     // that instruction.
6338     if (Subtarget->hasAVX2()) {
6339       // Scale the blend by the number of 32-bit dwords per element.
6340       int Scale =  VT.getScalarSizeInBits() / 32;
6341       BlendMask = 0;
6342       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6343         if (Mask[i] >= Size)
6344           for (int j = 0; j < Scale; ++j)
6345             BlendMask |= 1u << (i * Scale + j);
6346
6347       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6348       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6349       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6350       return DAG.getNode(ISD::BITCAST, DL, VT,
6351                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6352                                      DAG.getConstant(BlendMask, DL, MVT::i8)));
6353     }
6354     // FALLTHROUGH
6355   case MVT::v8i16: {
6356     // For integer shuffles we need to expand the mask and cast the inputs to
6357     // v8i16s prior to blending.
6358     int Scale = 8 / VT.getVectorNumElements();
6359     BlendMask = 0;
6360     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6361       if (Mask[i] >= Size)
6362         for (int j = 0; j < Scale; ++j)
6363           BlendMask |= 1u << (i * Scale + j);
6364
6365     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6366     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6367     return DAG.getNode(ISD::BITCAST, DL, VT,
6368                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6369                                    DAG.getConstant(BlendMask, DL, MVT::i8)));
6370   }
6371
6372   case MVT::v16i16: {
6373     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6374     SmallVector<int, 8> RepeatedMask;
6375     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6376       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6377       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6378       BlendMask = 0;
6379       for (int i = 0; i < 8; ++i)
6380         if (RepeatedMask[i] >= 16)
6381           BlendMask |= 1u << i;
6382       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6383                          DAG.getConstant(BlendMask, DL, MVT::i8));
6384     }
6385   }
6386     // FALLTHROUGH
6387   case MVT::v16i8:
6388   case MVT::v32i8: {
6389     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6390            "256-bit byte-blends require AVX2 support!");
6391
6392     // Scale the blend by the number of bytes per element.
6393     int Scale = VT.getScalarSizeInBits() / 8;
6394
6395     // This form of blend is always done on bytes. Compute the byte vector
6396     // type.
6397     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6398
6399     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6400     // mix of LLVM's code generator and the x86 backend. We tell the code
6401     // generator that boolean values in the elements of an x86 vector register
6402     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6403     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6404     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6405     // of the element (the remaining are ignored) and 0 in that high bit would
6406     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6407     // the LLVM model for boolean values in vector elements gets the relevant
6408     // bit set, it is set backwards and over constrained relative to x86's
6409     // actual model.
6410     SmallVector<SDValue, 32> VSELECTMask;
6411     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6412       for (int j = 0; j < Scale; ++j)
6413         VSELECTMask.push_back(
6414             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6415                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6416                                           MVT::i8));
6417
6418     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6419     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6420     return DAG.getNode(
6421         ISD::BITCAST, DL, VT,
6422         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6423                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6424                     V1, V2));
6425   }
6426
6427   default:
6428     llvm_unreachable("Not a supported integer vector type!");
6429   }
6430 }
6431
6432 /// \brief Try to lower as a blend of elements from two inputs followed by
6433 /// a single-input permutation.
6434 ///
6435 /// This matches the pattern where we can blend elements from two inputs and
6436 /// then reduce the shuffle to a single-input permutation.
6437 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6438                                                    SDValue V2,
6439                                                    ArrayRef<int> Mask,
6440                                                    SelectionDAG &DAG) {
6441   // We build up the blend mask while checking whether a blend is a viable way
6442   // to reduce the shuffle.
6443   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6444   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6445
6446   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6447     if (Mask[i] < 0)
6448       continue;
6449
6450     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6451
6452     if (BlendMask[Mask[i] % Size] == -1)
6453       BlendMask[Mask[i] % Size] = Mask[i];
6454     else if (BlendMask[Mask[i] % Size] != Mask[i])
6455       return SDValue(); // Can't blend in the needed input!
6456
6457     PermuteMask[i] = Mask[i] % Size;
6458   }
6459
6460   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6461   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6462 }
6463
6464 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6465 /// blends and permutes.
6466 ///
6467 /// This matches the extremely common pattern for handling combined
6468 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6469 /// operations. It will try to pick the best arrangement of shuffles and
6470 /// blends.
6471 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6472                                                           SDValue V1,
6473                                                           SDValue V2,
6474                                                           ArrayRef<int> Mask,
6475                                                           SelectionDAG &DAG) {
6476   // Shuffle the input elements into the desired positions in V1 and V2 and
6477   // blend them together.
6478   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6479   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6480   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6481   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6482     if (Mask[i] >= 0 && Mask[i] < Size) {
6483       V1Mask[i] = Mask[i];
6484       BlendMask[i] = i;
6485     } else if (Mask[i] >= Size) {
6486       V2Mask[i] = Mask[i] - Size;
6487       BlendMask[i] = i + Size;
6488     }
6489
6490   // Try to lower with the simpler initial blend strategy unless one of the
6491   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6492   // shuffle may be able to fold with a load or other benefit. However, when
6493   // we'll have to do 2x as many shuffles in order to achieve this, blending
6494   // first is a better strategy.
6495   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6496     if (SDValue BlendPerm =
6497             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6498       return BlendPerm;
6499
6500   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6501   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6502   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6503 }
6504
6505 /// \brief Try to lower a vector shuffle as a byte rotation.
6506 ///
6507 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6508 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6509 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6510 /// try to generically lower a vector shuffle through such an pattern. It
6511 /// does not check for the profitability of lowering either as PALIGNR or
6512 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6513 /// This matches shuffle vectors that look like:
6514 ///
6515 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6516 ///
6517 /// Essentially it concatenates V1 and V2, shifts right by some number of
6518 /// elements, and takes the low elements as the result. Note that while this is
6519 /// specified as a *right shift* because x86 is little-endian, it is a *left
6520 /// rotate* of the vector lanes.
6521 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6522                                               SDValue V2,
6523                                               ArrayRef<int> Mask,
6524                                               const X86Subtarget *Subtarget,
6525                                               SelectionDAG &DAG) {
6526   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6527
6528   int NumElts = Mask.size();
6529   int NumLanes = VT.getSizeInBits() / 128;
6530   int NumLaneElts = NumElts / NumLanes;
6531
6532   // We need to detect various ways of spelling a rotation:
6533   //   [11, 12, 13, 14, 15,  0,  1,  2]
6534   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6535   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6536   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6537   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6538   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6539   int Rotation = 0;
6540   SDValue Lo, Hi;
6541   for (int l = 0; l < NumElts; l += NumLaneElts) {
6542     for (int i = 0; i < NumLaneElts; ++i) {
6543       if (Mask[l + i] == -1)
6544         continue;
6545       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6546
6547       // Get the mod-Size index and lane correct it.
6548       int LaneIdx = (Mask[l + i] % NumElts) - l;
6549       // Make sure it was in this lane.
6550       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6551         return SDValue();
6552
6553       // Determine where a rotated vector would have started.
6554       int StartIdx = i - LaneIdx;
6555       if (StartIdx == 0)
6556         // The identity rotation isn't interesting, stop.
6557         return SDValue();
6558
6559       // If we found the tail of a vector the rotation must be the missing
6560       // front. If we found the head of a vector, it must be how much of the
6561       // head.
6562       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6563
6564       if (Rotation == 0)
6565         Rotation = CandidateRotation;
6566       else if (Rotation != CandidateRotation)
6567         // The rotations don't match, so we can't match this mask.
6568         return SDValue();
6569
6570       // Compute which value this mask is pointing at.
6571       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6572
6573       // Compute which of the two target values this index should be assigned
6574       // to. This reflects whether the high elements are remaining or the low
6575       // elements are remaining.
6576       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6577
6578       // Either set up this value if we've not encountered it before, or check
6579       // that it remains consistent.
6580       if (!TargetV)
6581         TargetV = MaskV;
6582       else if (TargetV != MaskV)
6583         // This may be a rotation, but it pulls from the inputs in some
6584         // unsupported interleaving.
6585         return SDValue();
6586     }
6587   }
6588
6589   // Check that we successfully analyzed the mask, and normalize the results.
6590   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6591   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6592   if (!Lo)
6593     Lo = Hi;
6594   else if (!Hi)
6595     Hi = Lo;
6596
6597   // The actual rotate instruction rotates bytes, so we need to scale the
6598   // rotation based on how many bytes are in the vector lane.
6599   int Scale = 16 / NumLaneElts;
6600
6601   // SSSE3 targets can use the palignr instruction.
6602   if (Subtarget->hasSSSE3()) {
6603     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6604     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6605     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6606     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6607
6608     return DAG.getNode(ISD::BITCAST, DL, VT,
6609                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6610                                    DAG.getConstant(Rotation * Scale, DL,
6611                                                    MVT::i8)));
6612   }
6613
6614   assert(VT.getSizeInBits() == 128 &&
6615          "Rotate-based lowering only supports 128-bit lowering!");
6616   assert(Mask.size() <= 16 &&
6617          "Can shuffle at most 16 bytes in a 128-bit vector!");
6618
6619   // Default SSE2 implementation
6620   int LoByteShift = 16 - Rotation * Scale;
6621   int HiByteShift = Rotation * Scale;
6622
6623   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6624   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6625   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6626
6627   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6628                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6629   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6630                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6631   return DAG.getNode(ISD::BITCAST, DL, VT,
6632                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6633 }
6634
6635 /// \brief Compute whether each element of a shuffle is zeroable.
6636 ///
6637 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6638 /// Either it is an undef element in the shuffle mask, the element of the input
6639 /// referenced is undef, or the element of the input referenced is known to be
6640 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6641 /// as many lanes with this technique as possible to simplify the remaining
6642 /// shuffle.
6643 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6644                                                      SDValue V1, SDValue V2) {
6645   SmallBitVector Zeroable(Mask.size(), false);
6646
6647   while (V1.getOpcode() == ISD::BITCAST)
6648     V1 = V1->getOperand(0);
6649   while (V2.getOpcode() == ISD::BITCAST)
6650     V2 = V2->getOperand(0);
6651
6652   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6653   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6654
6655   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6656     int M = Mask[i];
6657     // Handle the easy cases.
6658     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6659       Zeroable[i] = true;
6660       continue;
6661     }
6662
6663     // If this is an index into a build_vector node (which has the same number
6664     // of elements), dig out the input value and use it.
6665     SDValue V = M < Size ? V1 : V2;
6666     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6667       continue;
6668
6669     SDValue Input = V.getOperand(M % Size);
6670     // The UNDEF opcode check really should be dead code here, but not quite
6671     // worth asserting on (it isn't invalid, just unexpected).
6672     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6673       Zeroable[i] = true;
6674   }
6675
6676   return Zeroable;
6677 }
6678
6679 /// \brief Try to emit a bitmask instruction for a shuffle.
6680 ///
6681 /// This handles cases where we can model a blend exactly as a bitmask due to
6682 /// one of the inputs being zeroable.
6683 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6684                                            SDValue V2, ArrayRef<int> Mask,
6685                                            SelectionDAG &DAG) {
6686   MVT EltVT = VT.getScalarType();
6687   int NumEltBits = EltVT.getSizeInBits();
6688   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6689   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6690   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6691                                     IntEltVT);
6692   if (EltVT.isFloatingPoint()) {
6693     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6694     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6695   }
6696   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6697   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6698   SDValue V;
6699   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6700     if (Zeroable[i])
6701       continue;
6702     if (Mask[i] % Size != i)
6703       return SDValue(); // Not a blend.
6704     if (!V)
6705       V = Mask[i] < Size ? V1 : V2;
6706     else if (V != (Mask[i] < Size ? V1 : V2))
6707       return SDValue(); // Can only let one input through the mask.
6708
6709     VMaskOps[i] = AllOnes;
6710   }
6711   if (!V)
6712     return SDValue(); // No non-zeroable elements!
6713
6714   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6715   V = DAG.getNode(VT.isFloatingPoint()
6716                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6717                   DL, VT, V, VMask);
6718   return V;
6719 }
6720
6721 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6722 ///
6723 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6724 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6725 /// matches elements from one of the input vectors shuffled to the left or
6726 /// right with zeroable elements 'shifted in'. It handles both the strictly
6727 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6728 /// quad word lane.
6729 ///
6730 /// PSHL : (little-endian) left bit shift.
6731 /// [ zz, 0, zz,  2 ]
6732 /// [ -1, 4, zz, -1 ]
6733 /// PSRL : (little-endian) right bit shift.
6734 /// [  1, zz,  3, zz]
6735 /// [ -1, -1,  7, zz]
6736 /// PSLLDQ : (little-endian) left byte shift
6737 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6738 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6739 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6740 /// PSRLDQ : (little-endian) right byte shift
6741 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6742 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6743 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6744 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6745                                          SDValue V2, ArrayRef<int> Mask,
6746                                          SelectionDAG &DAG) {
6747   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6748
6749   int Size = Mask.size();
6750   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6751
6752   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6753     for (int i = 0; i < Size; i += Scale)
6754       for (int j = 0; j < Shift; ++j)
6755         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6756           return false;
6757
6758     return true;
6759   };
6760
6761   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6762     for (int i = 0; i != Size; i += Scale) {
6763       unsigned Pos = Left ? i + Shift : i;
6764       unsigned Low = Left ? i : i + Shift;
6765       unsigned Len = Scale - Shift;
6766       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6767                                       Low + (V == V1 ? 0 : Size)))
6768         return SDValue();
6769     }
6770
6771     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6772     bool ByteShift = ShiftEltBits > 64;
6773     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6774                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6775     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6776
6777     // Normalize the scale for byte shifts to still produce an i64 element
6778     // type.
6779     Scale = ByteShift ? Scale / 2 : Scale;
6780
6781     // We need to round trip through the appropriate type for the shift.
6782     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6783     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6784     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6785            "Illegal integer vector type");
6786     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6787
6788     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6789                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6790     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6791   };
6792
6793   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6794   // keep doubling the size of the integer elements up to that. We can
6795   // then shift the elements of the integer vector by whole multiples of
6796   // their width within the elements of the larger integer vector. Test each
6797   // multiple to see if we can find a match with the moved element indices
6798   // and that the shifted in elements are all zeroable.
6799   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6800     for (int Shift = 1; Shift != Scale; ++Shift)
6801       for (bool Left : {true, false})
6802         if (CheckZeros(Shift, Scale, Left))
6803           for (SDValue V : {V1, V2})
6804             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6805               return Match;
6806
6807   // no match
6808   return SDValue();
6809 }
6810
6811 /// \brief Lower a vector shuffle as a zero or any extension.
6812 ///
6813 /// Given a specific number of elements, element bit width, and extension
6814 /// stride, produce either a zero or any extension based on the available
6815 /// features of the subtarget.
6816 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6817     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6818     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6819   assert(Scale > 1 && "Need a scale to extend.");
6820   int NumElements = VT.getVectorNumElements();
6821   int EltBits = VT.getScalarSizeInBits();
6822   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6823          "Only 8, 16, and 32 bit elements can be extended.");
6824   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6825
6826   // Found a valid zext mask! Try various lowering strategies based on the
6827   // input type and available ISA extensions.
6828   if (Subtarget->hasSSE41()) {
6829     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6830                                  NumElements / Scale);
6831     return DAG.getNode(ISD::BITCAST, DL, VT,
6832                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6833   }
6834
6835   // For any extends we can cheat for larger element sizes and use shuffle
6836   // instructions that can fold with a load and/or copy.
6837   if (AnyExt && EltBits == 32) {
6838     int PSHUFDMask[4] = {0, -1, 1, -1};
6839     return DAG.getNode(
6840         ISD::BITCAST, DL, VT,
6841         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6842                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6843                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6844   }
6845   if (AnyExt && EltBits == 16 && Scale > 2) {
6846     int PSHUFDMask[4] = {0, -1, 0, -1};
6847     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6848                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6849                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6850     int PSHUFHWMask[4] = {1, -1, -1, -1};
6851     return DAG.getNode(
6852         ISD::BITCAST, DL, VT,
6853         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6854                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6855                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6856   }
6857
6858   // If this would require more than 2 unpack instructions to expand, use
6859   // pshufb when available. We can only use more than 2 unpack instructions
6860   // when zero extending i8 elements which also makes it easier to use pshufb.
6861   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6862     assert(NumElements == 16 && "Unexpected byte vector width!");
6863     SDValue PSHUFBMask[16];
6864     for (int i = 0; i < 16; ++i)
6865       PSHUFBMask[i] =
6866           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6867     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6868     return DAG.getNode(ISD::BITCAST, DL, VT,
6869                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6870                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6871                                                MVT::v16i8, PSHUFBMask)));
6872   }
6873
6874   // Otherwise emit a sequence of unpacks.
6875   do {
6876     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6877     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6878                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6879     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6880     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6881     Scale /= 2;
6882     EltBits *= 2;
6883     NumElements /= 2;
6884   } while (Scale > 1);
6885   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6886 }
6887
6888 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6889 ///
6890 /// This routine will try to do everything in its power to cleverly lower
6891 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6892 /// check for the profitability of this lowering,  it tries to aggressively
6893 /// match this pattern. It will use all of the micro-architectural details it
6894 /// can to emit an efficient lowering. It handles both blends with all-zero
6895 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6896 /// masking out later).
6897 ///
6898 /// The reason we have dedicated lowering for zext-style shuffles is that they
6899 /// are both incredibly common and often quite performance sensitive.
6900 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6901     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6902     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6903   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6904
6905   int Bits = VT.getSizeInBits();
6906   int NumElements = VT.getVectorNumElements();
6907   assert(VT.getScalarSizeInBits() <= 32 &&
6908          "Exceeds 32-bit integer zero extension limit");
6909   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6910
6911   // Define a helper function to check a particular ext-scale and lower to it if
6912   // valid.
6913   auto Lower = [&](int Scale) -> SDValue {
6914     SDValue InputV;
6915     bool AnyExt = true;
6916     for (int i = 0; i < NumElements; ++i) {
6917       if (Mask[i] == -1)
6918         continue; // Valid anywhere but doesn't tell us anything.
6919       if (i % Scale != 0) {
6920         // Each of the extended elements need to be zeroable.
6921         if (!Zeroable[i])
6922           return SDValue();
6923
6924         // We no longer are in the anyext case.
6925         AnyExt = false;
6926         continue;
6927       }
6928
6929       // Each of the base elements needs to be consecutive indices into the
6930       // same input vector.
6931       SDValue V = Mask[i] < NumElements ? V1 : V2;
6932       if (!InputV)
6933         InputV = V;
6934       else if (InputV != V)
6935         return SDValue(); // Flip-flopping inputs.
6936
6937       if (Mask[i] % NumElements != i / Scale)
6938         return SDValue(); // Non-consecutive strided elements.
6939     }
6940
6941     // If we fail to find an input, we have a zero-shuffle which should always
6942     // have already been handled.
6943     // FIXME: Maybe handle this here in case during blending we end up with one?
6944     if (!InputV)
6945       return SDValue();
6946
6947     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6948         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6949   };
6950
6951   // The widest scale possible for extending is to a 64-bit integer.
6952   assert(Bits % 64 == 0 &&
6953          "The number of bits in a vector must be divisible by 64 on x86!");
6954   int NumExtElements = Bits / 64;
6955
6956   // Each iteration, try extending the elements half as much, but into twice as
6957   // many elements.
6958   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6959     assert(NumElements % NumExtElements == 0 &&
6960            "The input vector size must be divisible by the extended size.");
6961     if (SDValue V = Lower(NumElements / NumExtElements))
6962       return V;
6963   }
6964
6965   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6966   if (Bits != 128)
6967     return SDValue();
6968
6969   // Returns one of the source operands if the shuffle can be reduced to a
6970   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6971   auto CanZExtLowHalf = [&]() {
6972     for (int i = NumElements / 2; i != NumElements; ++i)
6973       if (!Zeroable[i])
6974         return SDValue();
6975     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6976       return V1;
6977     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6978       return V2;
6979     return SDValue();
6980   };
6981
6982   if (SDValue V = CanZExtLowHalf()) {
6983     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6984     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6985     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6986   }
6987
6988   // No viable ext lowering found.
6989   return SDValue();
6990 }
6991
6992 /// \brief Try to get a scalar value for a specific element of a vector.
6993 ///
6994 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6995 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6996                                               SelectionDAG &DAG) {
6997   MVT VT = V.getSimpleValueType();
6998   MVT EltVT = VT.getVectorElementType();
6999   while (V.getOpcode() == ISD::BITCAST)
7000     V = V.getOperand(0);
7001   // If the bitcasts shift the element size, we can't extract an equivalent
7002   // element from it.
7003   MVT NewVT = V.getSimpleValueType();
7004   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7005     return SDValue();
7006
7007   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7008       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7009     // Ensure the scalar operand is the same size as the destination.
7010     // FIXME: Add support for scalar truncation where possible.
7011     SDValue S = V.getOperand(Idx);
7012     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7013       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7014   }
7015
7016   return SDValue();
7017 }
7018
7019 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7020 ///
7021 /// This is particularly important because the set of instructions varies
7022 /// significantly based on whether the operand is a load or not.
7023 static bool isShuffleFoldableLoad(SDValue V) {
7024   while (V.getOpcode() == ISD::BITCAST)
7025     V = V.getOperand(0);
7026
7027   return ISD::isNON_EXTLoad(V.getNode());
7028 }
7029
7030 /// \brief Try to lower insertion of a single element into a zero vector.
7031 ///
7032 /// This is a common pattern that we have especially efficient patterns to lower
7033 /// across all subtarget feature sets.
7034 static SDValue lowerVectorShuffleAsElementInsertion(
7035     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7036     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7037   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7038   MVT ExtVT = VT;
7039   MVT EltVT = VT.getVectorElementType();
7040
7041   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7042                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7043                 Mask.begin();
7044   bool IsV1Zeroable = true;
7045   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7046     if (i != V2Index && !Zeroable[i]) {
7047       IsV1Zeroable = false;
7048       break;
7049     }
7050
7051   // Check for a single input from a SCALAR_TO_VECTOR node.
7052   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7053   // all the smarts here sunk into that routine. However, the current
7054   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7055   // vector shuffle lowering is dead.
7056   if (SDValue V2S = getScalarValueForVectorElement(
7057           V2, Mask[V2Index] - Mask.size(), DAG)) {
7058     // We need to zext the scalar if it is smaller than an i32.
7059     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7060     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7061       // Using zext to expand a narrow element won't work for non-zero
7062       // insertions.
7063       if (!IsV1Zeroable)
7064         return SDValue();
7065
7066       // Zero-extend directly to i32.
7067       ExtVT = MVT::v4i32;
7068       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7069     }
7070     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7071   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7072              EltVT == MVT::i16) {
7073     // Either not inserting from the low element of the input or the input
7074     // element size is too small to use VZEXT_MOVL to clear the high bits.
7075     return SDValue();
7076   }
7077
7078   if (!IsV1Zeroable) {
7079     // If V1 can't be treated as a zero vector we have fewer options to lower
7080     // this. We can't support integer vectors or non-zero targets cheaply, and
7081     // the V1 elements can't be permuted in any way.
7082     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7083     if (!VT.isFloatingPoint() || V2Index != 0)
7084       return SDValue();
7085     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7086     V1Mask[V2Index] = -1;
7087     if (!isNoopShuffleMask(V1Mask))
7088       return SDValue();
7089     // This is essentially a special case blend operation, but if we have
7090     // general purpose blend operations, they are always faster. Bail and let
7091     // the rest of the lowering handle these as blends.
7092     if (Subtarget->hasSSE41())
7093       return SDValue();
7094
7095     // Otherwise, use MOVSD or MOVSS.
7096     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7097            "Only two types of floating point element types to handle!");
7098     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7099                        ExtVT, V1, V2);
7100   }
7101
7102   // This lowering only works for the low element with floating point vectors.
7103   if (VT.isFloatingPoint() && V2Index != 0)
7104     return SDValue();
7105
7106   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7107   if (ExtVT != VT)
7108     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7109
7110   if (V2Index != 0) {
7111     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7112     // the desired position. Otherwise it is more efficient to do a vector
7113     // shift left. We know that we can do a vector shift left because all
7114     // the inputs are zero.
7115     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7116       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7117       V2Shuffle[V2Index] = 0;
7118       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7119     } else {
7120       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7121       V2 = DAG.getNode(
7122           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7123           DAG.getConstant(
7124               V2Index * EltVT.getSizeInBits()/8, DL,
7125               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7126       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7127     }
7128   }
7129   return V2;
7130 }
7131
7132 /// \brief Try to lower broadcast of a single element.
7133 ///
7134 /// For convenience, this code also bundles all of the subtarget feature set
7135 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7136 /// a convenient way to factor it out.
7137 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7138                                              ArrayRef<int> Mask,
7139                                              const X86Subtarget *Subtarget,
7140                                              SelectionDAG &DAG) {
7141   if (!Subtarget->hasAVX())
7142     return SDValue();
7143   if (VT.isInteger() && !Subtarget->hasAVX2())
7144     return SDValue();
7145
7146   // Check that the mask is a broadcast.
7147   int BroadcastIdx = -1;
7148   for (int M : Mask)
7149     if (M >= 0 && BroadcastIdx == -1)
7150       BroadcastIdx = M;
7151     else if (M >= 0 && M != BroadcastIdx)
7152       return SDValue();
7153
7154   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7155                                             "a sorted mask where the broadcast "
7156                                             "comes from V1.");
7157
7158   // Go up the chain of (vector) values to find a scalar load that we can
7159   // combine with the broadcast.
7160   for (;;) {
7161     switch (V.getOpcode()) {
7162     case ISD::CONCAT_VECTORS: {
7163       int OperandSize = Mask.size() / V.getNumOperands();
7164       V = V.getOperand(BroadcastIdx / OperandSize);
7165       BroadcastIdx %= OperandSize;
7166       continue;
7167     }
7168
7169     case ISD::INSERT_SUBVECTOR: {
7170       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7171       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7172       if (!ConstantIdx)
7173         break;
7174
7175       int BeginIdx = (int)ConstantIdx->getZExtValue();
7176       int EndIdx =
7177           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7178       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7179         BroadcastIdx -= BeginIdx;
7180         V = VInner;
7181       } else {
7182         V = VOuter;
7183       }
7184       continue;
7185     }
7186     }
7187     break;
7188   }
7189
7190   // Check if this is a broadcast of a scalar. We special case lowering
7191   // for scalars so that we can more effectively fold with loads.
7192   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7193       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7194     V = V.getOperand(BroadcastIdx);
7195
7196     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7197     // Only AVX2 has register broadcasts.
7198     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7199       return SDValue();
7200   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7201     // We can't broadcast from a vector register without AVX2, and we can only
7202     // broadcast from the zero-element of a vector register.
7203     return SDValue();
7204   }
7205
7206   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7207 }
7208
7209 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7210 // INSERTPS when the V1 elements are already in the correct locations
7211 // because otherwise we can just always use two SHUFPS instructions which
7212 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7213 // perform INSERTPS if a single V1 element is out of place and all V2
7214 // elements are zeroable.
7215 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7216                                             ArrayRef<int> Mask,
7217                                             SelectionDAG &DAG) {
7218   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7219   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7220   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7221   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7222
7223   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7224
7225   unsigned ZMask = 0;
7226   int V1DstIndex = -1;
7227   int V2DstIndex = -1;
7228   bool V1UsedInPlace = false;
7229
7230   for (int i = 0; i < 4; ++i) {
7231     // Synthesize a zero mask from the zeroable elements (includes undefs).
7232     if (Zeroable[i]) {
7233       ZMask |= 1 << i;
7234       continue;
7235     }
7236
7237     // Flag if we use any V1 inputs in place.
7238     if (i == Mask[i]) {
7239       V1UsedInPlace = true;
7240       continue;
7241     }
7242
7243     // We can only insert a single non-zeroable element.
7244     if (V1DstIndex != -1 || V2DstIndex != -1)
7245       return SDValue();
7246
7247     if (Mask[i] < 4) {
7248       // V1 input out of place for insertion.
7249       V1DstIndex = i;
7250     } else {
7251       // V2 input for insertion.
7252       V2DstIndex = i;
7253     }
7254   }
7255
7256   // Don't bother if we have no (non-zeroable) element for insertion.
7257   if (V1DstIndex == -1 && V2DstIndex == -1)
7258     return SDValue();
7259
7260   // Determine element insertion src/dst indices. The src index is from the
7261   // start of the inserted vector, not the start of the concatenated vector.
7262   unsigned V2SrcIndex = 0;
7263   if (V1DstIndex != -1) {
7264     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7265     // and don't use the original V2 at all.
7266     V2SrcIndex = Mask[V1DstIndex];
7267     V2DstIndex = V1DstIndex;
7268     V2 = V1;
7269   } else {
7270     V2SrcIndex = Mask[V2DstIndex] - 4;
7271   }
7272
7273   // If no V1 inputs are used in place, then the result is created only from
7274   // the zero mask and the V2 insertion - so remove V1 dependency.
7275   if (!V1UsedInPlace)
7276     V1 = DAG.getUNDEF(MVT::v4f32);
7277
7278   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7279   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7280
7281   // Insert the V2 element into the desired position.
7282   SDLoc DL(Op);
7283   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7284                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7285 }
7286
7287 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7288 /// UNPCK instruction.
7289 ///
7290 /// This specifically targets cases where we end up with alternating between
7291 /// the two inputs, and so can permute them into something that feeds a single
7292 /// UNPCK instruction. Note that this routine only targets integer vectors
7293 /// because for floating point vectors we have a generalized SHUFPS lowering
7294 /// strategy that handles everything that doesn't *exactly* match an unpack,
7295 /// making this clever lowering unnecessary.
7296 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7297                                           SDValue V2, ArrayRef<int> Mask,
7298                                           SelectionDAG &DAG) {
7299   assert(!VT.isFloatingPoint() &&
7300          "This routine only supports integer vectors.");
7301   assert(!isSingleInputShuffleMask(Mask) &&
7302          "This routine should only be used when blending two inputs.");
7303   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7304
7305   int Size = Mask.size();
7306
7307   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7308     return M >= 0 && M % Size < Size / 2;
7309   });
7310   int NumHiInputs = std::count_if(
7311       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7312
7313   bool UnpackLo = NumLoInputs >= NumHiInputs;
7314
7315   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7316     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7317     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7318
7319     for (int i = 0; i < Size; ++i) {
7320       if (Mask[i] < 0)
7321         continue;
7322
7323       // Each element of the unpack contains Scale elements from this mask.
7324       int UnpackIdx = i / Scale;
7325
7326       // We only handle the case where V1 feeds the first slots of the unpack.
7327       // We rely on canonicalization to ensure this is the case.
7328       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7329         return SDValue();
7330
7331       // Setup the mask for this input. The indexing is tricky as we have to
7332       // handle the unpack stride.
7333       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7334       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7335           Mask[i] % Size;
7336     }
7337
7338     // If we will have to shuffle both inputs to use the unpack, check whether
7339     // we can just unpack first and shuffle the result. If so, skip this unpack.
7340     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7341         !isNoopShuffleMask(V2Mask))
7342       return SDValue();
7343
7344     // Shuffle the inputs into place.
7345     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7346     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7347
7348     // Cast the inputs to the type we will use to unpack them.
7349     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7350     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7351
7352     // Unpack the inputs and cast the result back to the desired type.
7353     return DAG.getNode(ISD::BITCAST, DL, VT,
7354                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7355                                    DL, UnpackVT, V1, V2));
7356   };
7357
7358   // We try each unpack from the largest to the smallest to try and find one
7359   // that fits this mask.
7360   int OrigNumElements = VT.getVectorNumElements();
7361   int OrigScalarSize = VT.getScalarSizeInBits();
7362   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7363     int Scale = ScalarSize / OrigScalarSize;
7364     int NumElements = OrigNumElements / Scale;
7365     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7366     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7367       return Unpack;
7368   }
7369
7370   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7371   // initial unpack.
7372   if (NumLoInputs == 0 || NumHiInputs == 0) {
7373     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7374            "We have to have *some* inputs!");
7375     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7376
7377     // FIXME: We could consider the total complexity of the permute of each
7378     // possible unpacking. Or at the least we should consider how many
7379     // half-crossings are created.
7380     // FIXME: We could consider commuting the unpacks.
7381
7382     SmallVector<int, 32> PermMask;
7383     PermMask.assign(Size, -1);
7384     for (int i = 0; i < Size; ++i) {
7385       if (Mask[i] < 0)
7386         continue;
7387
7388       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7389
7390       PermMask[i] =
7391           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7392     }
7393     return DAG.getVectorShuffle(
7394         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7395                             DL, VT, V1, V2),
7396         DAG.getUNDEF(VT), PermMask);
7397   }
7398
7399   return SDValue();
7400 }
7401
7402 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7403 ///
7404 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7405 /// support for floating point shuffles but not integer shuffles. These
7406 /// instructions will incur a domain crossing penalty on some chips though so
7407 /// it is better to avoid lowering through this for integer vectors where
7408 /// possible.
7409 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7410                                        const X86Subtarget *Subtarget,
7411                                        SelectionDAG &DAG) {
7412   SDLoc DL(Op);
7413   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7414   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7415   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7416   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7417   ArrayRef<int> Mask = SVOp->getMask();
7418   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7419
7420   if (isSingleInputShuffleMask(Mask)) {
7421     // Use low duplicate instructions for masks that match their pattern.
7422     if (Subtarget->hasSSE3())
7423       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7424         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7425
7426     // Straight shuffle of a single input vector. Simulate this by using the
7427     // single input as both of the "inputs" to this instruction..
7428     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7429
7430     if (Subtarget->hasAVX()) {
7431       // If we have AVX, we can use VPERMILPS which will allow folding a load
7432       // into the shuffle.
7433       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7434                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7435     }
7436
7437     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7438                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7439   }
7440   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7441   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7442
7443   // If we have a single input, insert that into V1 if we can do so cheaply.
7444   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7445     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7446             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7447       return Insertion;
7448     // Try inverting the insertion since for v2 masks it is easy to do and we
7449     // can't reliably sort the mask one way or the other.
7450     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7451                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7452     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7453             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7454       return Insertion;
7455   }
7456
7457   // Try to use one of the special instruction patterns to handle two common
7458   // blend patterns if a zero-blend above didn't work.
7459   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7460       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7461     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7462       // We can either use a special instruction to load over the low double or
7463       // to move just the low double.
7464       return DAG.getNode(
7465           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7466           DL, MVT::v2f64, V2,
7467           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7468
7469   if (Subtarget->hasSSE41())
7470     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7471                                                   Subtarget, DAG))
7472       return Blend;
7473
7474   // Use dedicated unpack instructions for masks that match their pattern.
7475   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7476     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7477   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7478     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7479
7480   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7481   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7482                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7483 }
7484
7485 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7486 ///
7487 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7488 /// the integer unit to minimize domain crossing penalties. However, for blends
7489 /// it falls back to the floating point shuffle operation with appropriate bit
7490 /// casting.
7491 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7492                                        const X86Subtarget *Subtarget,
7493                                        SelectionDAG &DAG) {
7494   SDLoc DL(Op);
7495   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7496   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7497   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7498   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7499   ArrayRef<int> Mask = SVOp->getMask();
7500   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7501
7502   if (isSingleInputShuffleMask(Mask)) {
7503     // Check for being able to broadcast a single element.
7504     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7505                                                           Mask, Subtarget, DAG))
7506       return Broadcast;
7507
7508     // Straight shuffle of a single input vector. For everything from SSE2
7509     // onward this has a single fast instruction with no scary immediates.
7510     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7511     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7512     int WidenedMask[4] = {
7513         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7514         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7515     return DAG.getNode(
7516         ISD::BITCAST, DL, MVT::v2i64,
7517         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7518                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7519   }
7520   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7521   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7522   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7523   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7524
7525   // If we have a blend of two PACKUS operations an the blend aligns with the
7526   // low and half halves, we can just merge the PACKUS operations. This is
7527   // particularly important as it lets us merge shuffles that this routine itself
7528   // creates.
7529   auto GetPackNode = [](SDValue V) {
7530     while (V.getOpcode() == ISD::BITCAST)
7531       V = V.getOperand(0);
7532
7533     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7534   };
7535   if (SDValue V1Pack = GetPackNode(V1))
7536     if (SDValue V2Pack = GetPackNode(V2))
7537       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7538                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7539                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7540                                                   : V1Pack.getOperand(1),
7541                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7542                                                   : V2Pack.getOperand(1)));
7543
7544   // Try to use shift instructions.
7545   if (SDValue Shift =
7546           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7547     return Shift;
7548
7549   // When loading a scalar and then shuffling it into a vector we can often do
7550   // the insertion cheaply.
7551   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7552           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7553     return Insertion;
7554   // Try inverting the insertion since for v2 masks it is easy to do and we
7555   // can't reliably sort the mask one way or the other.
7556   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7557   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7558           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7559     return Insertion;
7560
7561   // We have different paths for blend lowering, but they all must use the
7562   // *exact* same predicate.
7563   bool IsBlendSupported = Subtarget->hasSSE41();
7564   if (IsBlendSupported)
7565     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7566                                                   Subtarget, DAG))
7567       return Blend;
7568
7569   // Use dedicated unpack instructions for masks that match their pattern.
7570   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7571     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7572   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7573     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7574
7575   // Try to use byte rotation instructions.
7576   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7577   if (Subtarget->hasSSSE3())
7578     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7579             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7580       return Rotate;
7581
7582   // If we have direct support for blends, we should lower by decomposing into
7583   // a permute. That will be faster than the domain cross.
7584   if (IsBlendSupported)
7585     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7586                                                       Mask, DAG);
7587
7588   // We implement this with SHUFPD which is pretty lame because it will likely
7589   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7590   // However, all the alternatives are still more cycles and newer chips don't
7591   // have this problem. It would be really nice if x86 had better shuffles here.
7592   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7593   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7594   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7595                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7596 }
7597
7598 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7599 ///
7600 /// This is used to disable more specialized lowerings when the shufps lowering
7601 /// will happen to be efficient.
7602 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7603   // This routine only handles 128-bit shufps.
7604   assert(Mask.size() == 4 && "Unsupported mask size!");
7605
7606   // To lower with a single SHUFPS we need to have the low half and high half
7607   // each requiring a single input.
7608   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7609     return false;
7610   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7611     return false;
7612
7613   return true;
7614 }
7615
7616 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7617 ///
7618 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7619 /// It makes no assumptions about whether this is the *best* lowering, it simply
7620 /// uses it.
7621 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7622                                             ArrayRef<int> Mask, SDValue V1,
7623                                             SDValue V2, SelectionDAG &DAG) {
7624   SDValue LowV = V1, HighV = V2;
7625   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7626
7627   int NumV2Elements =
7628       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7629
7630   if (NumV2Elements == 1) {
7631     int V2Index =
7632         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7633         Mask.begin();
7634
7635     // Compute the index adjacent to V2Index and in the same half by toggling
7636     // the low bit.
7637     int V2AdjIndex = V2Index ^ 1;
7638
7639     if (Mask[V2AdjIndex] == -1) {
7640       // Handles all the cases where we have a single V2 element and an undef.
7641       // This will only ever happen in the high lanes because we commute the
7642       // vector otherwise.
7643       if (V2Index < 2)
7644         std::swap(LowV, HighV);
7645       NewMask[V2Index] -= 4;
7646     } else {
7647       // Handle the case where the V2 element ends up adjacent to a V1 element.
7648       // To make this work, blend them together as the first step.
7649       int V1Index = V2AdjIndex;
7650       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7651       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7652                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7653
7654       // Now proceed to reconstruct the final blend as we have the necessary
7655       // high or low half formed.
7656       if (V2Index < 2) {
7657         LowV = V2;
7658         HighV = V1;
7659       } else {
7660         HighV = V2;
7661       }
7662       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7663       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7664     }
7665   } else if (NumV2Elements == 2) {
7666     if (Mask[0] < 4 && Mask[1] < 4) {
7667       // Handle the easy case where we have V1 in the low lanes and V2 in the
7668       // high lanes.
7669       NewMask[2] -= 4;
7670       NewMask[3] -= 4;
7671     } else if (Mask[2] < 4 && Mask[3] < 4) {
7672       // We also handle the reversed case because this utility may get called
7673       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7674       // arrange things in the right direction.
7675       NewMask[0] -= 4;
7676       NewMask[1] -= 4;
7677       HighV = V1;
7678       LowV = V2;
7679     } else {
7680       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7681       // trying to place elements directly, just blend them and set up the final
7682       // shuffle to place them.
7683
7684       // The first two blend mask elements are for V1, the second two are for
7685       // V2.
7686       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7687                           Mask[2] < 4 ? Mask[2] : Mask[3],
7688                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7689                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7690       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7691                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7692
7693       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7694       // a blend.
7695       LowV = HighV = V1;
7696       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7697       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7698       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7699       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7700     }
7701   }
7702   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7703                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7704 }
7705
7706 /// \brief Lower 4-lane 32-bit floating point shuffles.
7707 ///
7708 /// Uses instructions exclusively from the floating point unit to minimize
7709 /// domain crossing penalties, as these are sufficient to implement all v4f32
7710 /// shuffles.
7711 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7712                                        const X86Subtarget *Subtarget,
7713                                        SelectionDAG &DAG) {
7714   SDLoc DL(Op);
7715   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7716   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7717   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7718   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7719   ArrayRef<int> Mask = SVOp->getMask();
7720   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7721
7722   int NumV2Elements =
7723       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7724
7725   if (NumV2Elements == 0) {
7726     // Check for being able to broadcast a single element.
7727     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7728                                                           Mask, Subtarget, DAG))
7729       return Broadcast;
7730
7731     // Use even/odd duplicate instructions for masks that match their pattern.
7732     if (Subtarget->hasSSE3()) {
7733       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7734         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7735       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7736         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7737     }
7738
7739     if (Subtarget->hasAVX()) {
7740       // If we have AVX, we can use VPERMILPS which will allow folding a load
7741       // into the shuffle.
7742       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7743                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7744     }
7745
7746     // Otherwise, use a straight shuffle of a single input vector. We pass the
7747     // input vector to both operands to simulate this with a SHUFPS.
7748     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7749                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7750   }
7751
7752   // There are special ways we can lower some single-element blends. However, we
7753   // have custom ways we can lower more complex single-element blends below that
7754   // we defer to if both this and BLENDPS fail to match, so restrict this to
7755   // when the V2 input is targeting element 0 of the mask -- that is the fast
7756   // case here.
7757   if (NumV2Elements == 1 && Mask[0] >= 4)
7758     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7759                                                          Mask, Subtarget, DAG))
7760       return V;
7761
7762   if (Subtarget->hasSSE41()) {
7763     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7764                                                   Subtarget, DAG))
7765       return Blend;
7766
7767     // Use INSERTPS if we can complete the shuffle efficiently.
7768     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7769       return V;
7770
7771     if (!isSingleSHUFPSMask(Mask))
7772       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7773               DL, MVT::v4f32, V1, V2, Mask, DAG))
7774         return BlendPerm;
7775   }
7776
7777   // Use dedicated unpack instructions for masks that match their pattern.
7778   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7779     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7780   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7781     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7782   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7783     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7784   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7785     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7786
7787   // Otherwise fall back to a SHUFPS lowering strategy.
7788   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7789 }
7790
7791 /// \brief Lower 4-lane i32 vector shuffles.
7792 ///
7793 /// We try to handle these with integer-domain shuffles where we can, but for
7794 /// blends we use the floating point domain blend instructions.
7795 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7796                                        const X86Subtarget *Subtarget,
7797                                        SelectionDAG &DAG) {
7798   SDLoc DL(Op);
7799   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7800   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7801   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7802   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7803   ArrayRef<int> Mask = SVOp->getMask();
7804   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7805
7806   // Whenever we can lower this as a zext, that instruction is strictly faster
7807   // than any alternative. It also allows us to fold memory operands into the
7808   // shuffle in many cases.
7809   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7810                                                          Mask, Subtarget, DAG))
7811     return ZExt;
7812
7813   int NumV2Elements =
7814       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7815
7816   if (NumV2Elements == 0) {
7817     // Check for being able to broadcast a single element.
7818     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7819                                                           Mask, Subtarget, DAG))
7820       return Broadcast;
7821
7822     // Straight shuffle of a single input vector. For everything from SSE2
7823     // onward this has a single fast instruction with no scary immediates.
7824     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7825     // but we aren't actually going to use the UNPCK instruction because doing
7826     // so prevents folding a load into this instruction or making a copy.
7827     const int UnpackLoMask[] = {0, 0, 1, 1};
7828     const int UnpackHiMask[] = {2, 2, 3, 3};
7829     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7830       Mask = UnpackLoMask;
7831     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7832       Mask = UnpackHiMask;
7833
7834     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7835                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7836   }
7837
7838   // Try to use shift instructions.
7839   if (SDValue Shift =
7840           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7841     return Shift;
7842
7843   // There are special ways we can lower some single-element blends.
7844   if (NumV2Elements == 1)
7845     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7846                                                          Mask, Subtarget, DAG))
7847       return V;
7848
7849   // We have different paths for blend lowering, but they all must use the
7850   // *exact* same predicate.
7851   bool IsBlendSupported = Subtarget->hasSSE41();
7852   if (IsBlendSupported)
7853     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7854                                                   Subtarget, DAG))
7855       return Blend;
7856
7857   if (SDValue Masked =
7858           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7859     return Masked;
7860
7861   // Use dedicated unpack instructions for masks that match their pattern.
7862   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7863     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7864   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7865     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7866   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7867     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7868   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7869     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7870
7871   // Try to use byte rotation instructions.
7872   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7873   if (Subtarget->hasSSSE3())
7874     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7875             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7876       return Rotate;
7877
7878   // If we have direct support for blends, we should lower by decomposing into
7879   // a permute. That will be faster than the domain cross.
7880   if (IsBlendSupported)
7881     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7882                                                       Mask, DAG);
7883
7884   // Try to lower by permuting the inputs into an unpack instruction.
7885   if (SDValue Unpack =
7886           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7887     return Unpack;
7888
7889   // We implement this with SHUFPS because it can blend from two vectors.
7890   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7891   // up the inputs, bypassing domain shift penalties that we would encur if we
7892   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7893   // relevant.
7894   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7895                      DAG.getVectorShuffle(
7896                          MVT::v4f32, DL,
7897                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7898                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7899 }
7900
7901 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7902 /// shuffle lowering, and the most complex part.
7903 ///
7904 /// The lowering strategy is to try to form pairs of input lanes which are
7905 /// targeted at the same half of the final vector, and then use a dword shuffle
7906 /// to place them onto the right half, and finally unpack the paired lanes into
7907 /// their final position.
7908 ///
7909 /// The exact breakdown of how to form these dword pairs and align them on the
7910 /// correct sides is really tricky. See the comments within the function for
7911 /// more of the details.
7912 ///
7913 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7914 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7915 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7916 /// vector, form the analogous 128-bit 8-element Mask.
7917 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7918     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7919     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7920   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7921   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7922
7923   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7924   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7925   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7926
7927   SmallVector<int, 4> LoInputs;
7928   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7929                [](int M) { return M >= 0; });
7930   std::sort(LoInputs.begin(), LoInputs.end());
7931   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7932   SmallVector<int, 4> HiInputs;
7933   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7934                [](int M) { return M >= 0; });
7935   std::sort(HiInputs.begin(), HiInputs.end());
7936   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7937   int NumLToL =
7938       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7939   int NumHToL = LoInputs.size() - NumLToL;
7940   int NumLToH =
7941       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7942   int NumHToH = HiInputs.size() - NumLToH;
7943   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7944   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7945   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7946   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7947
7948   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7949   // such inputs we can swap two of the dwords across the half mark and end up
7950   // with <=2 inputs to each half in each half. Once there, we can fall through
7951   // to the generic code below. For example:
7952   //
7953   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7954   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7955   //
7956   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7957   // and an existing 2-into-2 on the other half. In this case we may have to
7958   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7959   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7960   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7961   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7962   // half than the one we target for fixing) will be fixed when we re-enter this
7963   // path. We will also combine away any sequence of PSHUFD instructions that
7964   // result into a single instruction. Here is an example of the tricky case:
7965   //
7966   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7967   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7968   //
7969   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7970   //
7971   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7972   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7973   //
7974   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7975   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7976   //
7977   // The result is fine to be handled by the generic logic.
7978   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7979                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7980                           int AOffset, int BOffset) {
7981     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7982            "Must call this with A having 3 or 1 inputs from the A half.");
7983     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7984            "Must call this with B having 1 or 3 inputs from the B half.");
7985     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7986            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7987
7988     // Compute the index of dword with only one word among the three inputs in
7989     // a half by taking the sum of the half with three inputs and subtracting
7990     // the sum of the actual three inputs. The difference is the remaining
7991     // slot.
7992     int ADWord, BDWord;
7993     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7994     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7995     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7996     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7997     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7998     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7999     int TripleNonInputIdx =
8000         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8001     TripleDWord = TripleNonInputIdx / 2;
8002
8003     // We use xor with one to compute the adjacent DWord to whichever one the
8004     // OneInput is in.
8005     OneInputDWord = (OneInput / 2) ^ 1;
8006
8007     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8008     // and BToA inputs. If there is also such a problem with the BToB and AToB
8009     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8010     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8011     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8012     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8013       // Compute how many inputs will be flipped by swapping these DWords. We
8014       // need
8015       // to balance this to ensure we don't form a 3-1 shuffle in the other
8016       // half.
8017       int NumFlippedAToBInputs =
8018           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8019           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8020       int NumFlippedBToBInputs =
8021           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8022           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8023       if ((NumFlippedAToBInputs == 1 &&
8024            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8025           (NumFlippedBToBInputs == 1 &&
8026            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8027         // We choose whether to fix the A half or B half based on whether that
8028         // half has zero flipped inputs. At zero, we may not be able to fix it
8029         // with that half. We also bias towards fixing the B half because that
8030         // will more commonly be the high half, and we have to bias one way.
8031         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8032                                                        ArrayRef<int> Inputs) {
8033           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8034           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8035                                          PinnedIdx ^ 1) != Inputs.end();
8036           // Determine whether the free index is in the flipped dword or the
8037           // unflipped dword based on where the pinned index is. We use this bit
8038           // in an xor to conditionally select the adjacent dword.
8039           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8040           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8041                                              FixFreeIdx) != Inputs.end();
8042           if (IsFixIdxInput == IsFixFreeIdxInput)
8043             FixFreeIdx += 1;
8044           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8045                                         FixFreeIdx) != Inputs.end();
8046           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8047                  "We need to be changing the number of flipped inputs!");
8048           int PSHUFHalfMask[] = {0, 1, 2, 3};
8049           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8050           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8051                           MVT::v8i16, V,
8052                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8053
8054           for (int &M : Mask)
8055             if (M != -1 && M == FixIdx)
8056               M = FixFreeIdx;
8057             else if (M != -1 && M == FixFreeIdx)
8058               M = FixIdx;
8059         };
8060         if (NumFlippedBToBInputs != 0) {
8061           int BPinnedIdx =
8062               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8063           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8064         } else {
8065           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8066           int APinnedIdx =
8067               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8068           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8069         }
8070       }
8071     }
8072
8073     int PSHUFDMask[] = {0, 1, 2, 3};
8074     PSHUFDMask[ADWord] = BDWord;
8075     PSHUFDMask[BDWord] = ADWord;
8076     V = DAG.getNode(ISD::BITCAST, DL, VT,
8077                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8078                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8079                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8080                                                            DAG)));
8081
8082     // Adjust the mask to match the new locations of A and B.
8083     for (int &M : Mask)
8084       if (M != -1 && M/2 == ADWord)
8085         M = 2 * BDWord + M % 2;
8086       else if (M != -1 && M/2 == BDWord)
8087         M = 2 * ADWord + M % 2;
8088
8089     // Recurse back into this routine to re-compute state now that this isn't
8090     // a 3 and 1 problem.
8091     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8092                                                      DAG);
8093   };
8094   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8095     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8096   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8097     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8098
8099   // At this point there are at most two inputs to the low and high halves from
8100   // each half. That means the inputs can always be grouped into dwords and
8101   // those dwords can then be moved to the correct half with a dword shuffle.
8102   // We use at most one low and one high word shuffle to collect these paired
8103   // inputs into dwords, and finally a dword shuffle to place them.
8104   int PSHUFLMask[4] = {-1, -1, -1, -1};
8105   int PSHUFHMask[4] = {-1, -1, -1, -1};
8106   int PSHUFDMask[4] = {-1, -1, -1, -1};
8107
8108   // First fix the masks for all the inputs that are staying in their
8109   // original halves. This will then dictate the targets of the cross-half
8110   // shuffles.
8111   auto fixInPlaceInputs =
8112       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8113                     MutableArrayRef<int> SourceHalfMask,
8114                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8115     if (InPlaceInputs.empty())
8116       return;
8117     if (InPlaceInputs.size() == 1) {
8118       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8119           InPlaceInputs[0] - HalfOffset;
8120       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8121       return;
8122     }
8123     if (IncomingInputs.empty()) {
8124       // Just fix all of the in place inputs.
8125       for (int Input : InPlaceInputs) {
8126         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8127         PSHUFDMask[Input / 2] = Input / 2;
8128       }
8129       return;
8130     }
8131
8132     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8133     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8134         InPlaceInputs[0] - HalfOffset;
8135     // Put the second input next to the first so that they are packed into
8136     // a dword. We find the adjacent index by toggling the low bit.
8137     int AdjIndex = InPlaceInputs[0] ^ 1;
8138     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8139     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8140     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8141   };
8142   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8143   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8144
8145   // Now gather the cross-half inputs and place them into a free dword of
8146   // their target half.
8147   // FIXME: This operation could almost certainly be simplified dramatically to
8148   // look more like the 3-1 fixing operation.
8149   auto moveInputsToRightHalf = [&PSHUFDMask](
8150       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8151       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8152       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8153       int DestOffset) {
8154     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8155       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8156     };
8157     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8158                                                int Word) {
8159       int LowWord = Word & ~1;
8160       int HighWord = Word | 1;
8161       return isWordClobbered(SourceHalfMask, LowWord) ||
8162              isWordClobbered(SourceHalfMask, HighWord);
8163     };
8164
8165     if (IncomingInputs.empty())
8166       return;
8167
8168     if (ExistingInputs.empty()) {
8169       // Map any dwords with inputs from them into the right half.
8170       for (int Input : IncomingInputs) {
8171         // If the source half mask maps over the inputs, turn those into
8172         // swaps and use the swapped lane.
8173         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8174           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8175             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8176                 Input - SourceOffset;
8177             // We have to swap the uses in our half mask in one sweep.
8178             for (int &M : HalfMask)
8179               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8180                 M = Input;
8181               else if (M == Input)
8182                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8183           } else {
8184             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8185                        Input - SourceOffset &&
8186                    "Previous placement doesn't match!");
8187           }
8188           // Note that this correctly re-maps both when we do a swap and when
8189           // we observe the other side of the swap above. We rely on that to
8190           // avoid swapping the members of the input list directly.
8191           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8192         }
8193
8194         // Map the input's dword into the correct half.
8195         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8196           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8197         else
8198           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8199                      Input / 2 &&
8200                  "Previous placement doesn't match!");
8201       }
8202
8203       // And just directly shift any other-half mask elements to be same-half
8204       // as we will have mirrored the dword containing the element into the
8205       // same position within that half.
8206       for (int &M : HalfMask)
8207         if (M >= SourceOffset && M < SourceOffset + 4) {
8208           M = M - SourceOffset + DestOffset;
8209           assert(M >= 0 && "This should never wrap below zero!");
8210         }
8211       return;
8212     }
8213
8214     // Ensure we have the input in a viable dword of its current half. This
8215     // is particularly tricky because the original position may be clobbered
8216     // by inputs being moved and *staying* in that half.
8217     if (IncomingInputs.size() == 1) {
8218       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8219         int InputFixed = std::find(std::begin(SourceHalfMask),
8220                                    std::end(SourceHalfMask), -1) -
8221                          std::begin(SourceHalfMask) + SourceOffset;
8222         SourceHalfMask[InputFixed - SourceOffset] =
8223             IncomingInputs[0] - SourceOffset;
8224         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8225                      InputFixed);
8226         IncomingInputs[0] = InputFixed;
8227       }
8228     } else if (IncomingInputs.size() == 2) {
8229       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8230           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8231         // We have two non-adjacent or clobbered inputs we need to extract from
8232         // the source half. To do this, we need to map them into some adjacent
8233         // dword slot in the source mask.
8234         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8235                               IncomingInputs[1] - SourceOffset};
8236
8237         // If there is a free slot in the source half mask adjacent to one of
8238         // the inputs, place the other input in it. We use (Index XOR 1) to
8239         // compute an adjacent index.
8240         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8241             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8242           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8243           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8244           InputsFixed[1] = InputsFixed[0] ^ 1;
8245         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8246                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8247           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8248           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8249           InputsFixed[0] = InputsFixed[1] ^ 1;
8250         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8251                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8252           // The two inputs are in the same DWord but it is clobbered and the
8253           // adjacent DWord isn't used at all. Move both inputs to the free
8254           // slot.
8255           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8256           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8257           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8258           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8259         } else {
8260           // The only way we hit this point is if there is no clobbering
8261           // (because there are no off-half inputs to this half) and there is no
8262           // free slot adjacent to one of the inputs. In this case, we have to
8263           // swap an input with a non-input.
8264           for (int i = 0; i < 4; ++i)
8265             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8266                    "We can't handle any clobbers here!");
8267           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8268                  "Cannot have adjacent inputs here!");
8269
8270           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8271           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8272
8273           // We also have to update the final source mask in this case because
8274           // it may need to undo the above swap.
8275           for (int &M : FinalSourceHalfMask)
8276             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8277               M = InputsFixed[1] + SourceOffset;
8278             else if (M == InputsFixed[1] + SourceOffset)
8279               M = (InputsFixed[0] ^ 1) + SourceOffset;
8280
8281           InputsFixed[1] = InputsFixed[0] ^ 1;
8282         }
8283
8284         // Point everything at the fixed inputs.
8285         for (int &M : HalfMask)
8286           if (M == IncomingInputs[0])
8287             M = InputsFixed[0] + SourceOffset;
8288           else if (M == IncomingInputs[1])
8289             M = InputsFixed[1] + SourceOffset;
8290
8291         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8292         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8293       }
8294     } else {
8295       llvm_unreachable("Unhandled input size!");
8296     }
8297
8298     // Now hoist the DWord down to the right half.
8299     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8300     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8301     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8302     for (int &M : HalfMask)
8303       for (int Input : IncomingInputs)
8304         if (M == Input)
8305           M = FreeDWord * 2 + Input % 2;
8306   };
8307   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8308                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8309   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8310                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8311
8312   // Now enact all the shuffles we've computed to move the inputs into their
8313   // target half.
8314   if (!isNoopShuffleMask(PSHUFLMask))
8315     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8316                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8317   if (!isNoopShuffleMask(PSHUFHMask))
8318     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8319                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8320   if (!isNoopShuffleMask(PSHUFDMask))
8321     V = DAG.getNode(ISD::BITCAST, DL, VT,
8322                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8323                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8324                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8325                                                            DAG)));
8326
8327   // At this point, each half should contain all its inputs, and we can then
8328   // just shuffle them into their final position.
8329   assert(std::count_if(LoMask.begin(), LoMask.end(),
8330                        [](int M) { return M >= 4; }) == 0 &&
8331          "Failed to lift all the high half inputs to the low mask!");
8332   assert(std::count_if(HiMask.begin(), HiMask.end(),
8333                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8334          "Failed to lift all the low half inputs to the high mask!");
8335
8336   // Do a half shuffle for the low mask.
8337   if (!isNoopShuffleMask(LoMask))
8338     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8339                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8340
8341   // Do a half shuffle with the high mask after shifting its values down.
8342   for (int &M : HiMask)
8343     if (M >= 0)
8344       M -= 4;
8345   if (!isNoopShuffleMask(HiMask))
8346     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8347                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8348
8349   return V;
8350 }
8351
8352 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8353 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8354                                           SDValue V2, ArrayRef<int> Mask,
8355                                           SelectionDAG &DAG, bool &V1InUse,
8356                                           bool &V2InUse) {
8357   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8358   SDValue V1Mask[16];
8359   SDValue V2Mask[16];
8360   V1InUse = false;
8361   V2InUse = false;
8362
8363   int Size = Mask.size();
8364   int Scale = 16 / Size;
8365   for (int i = 0; i < 16; ++i) {
8366     if (Mask[i / Scale] == -1) {
8367       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8368     } else {
8369       const int ZeroMask = 0x80;
8370       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8371                                           : ZeroMask;
8372       int V2Idx = Mask[i / Scale] < Size
8373                       ? ZeroMask
8374                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8375       if (Zeroable[i / Scale])
8376         V1Idx = V2Idx = ZeroMask;
8377       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8378       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8379       V1InUse |= (ZeroMask != V1Idx);
8380       V2InUse |= (ZeroMask != V2Idx);
8381     }
8382   }
8383
8384   if (V1InUse)
8385     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8386                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8387                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8388   if (V2InUse)
8389     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8390                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8391                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8392
8393   // If we need shuffled inputs from both, blend the two.
8394   SDValue V;
8395   if (V1InUse && V2InUse)
8396     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8397   else
8398     V = V1InUse ? V1 : V2;
8399
8400   // Cast the result back to the correct type.
8401   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8402 }
8403
8404 /// \brief Generic lowering of 8-lane i16 shuffles.
8405 ///
8406 /// This handles both single-input shuffles and combined shuffle/blends with
8407 /// two inputs. The single input shuffles are immediately delegated to
8408 /// a dedicated lowering routine.
8409 ///
8410 /// The blends are lowered in one of three fundamental ways. If there are few
8411 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8412 /// of the input is significantly cheaper when lowered as an interleaving of
8413 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8414 /// halves of the inputs separately (making them have relatively few inputs)
8415 /// and then concatenate them.
8416 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8417                                        const X86Subtarget *Subtarget,
8418                                        SelectionDAG &DAG) {
8419   SDLoc DL(Op);
8420   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8421   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8422   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8423   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8424   ArrayRef<int> OrigMask = SVOp->getMask();
8425   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8426                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8427   MutableArrayRef<int> Mask(MaskStorage);
8428
8429   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8430
8431   // Whenever we can lower this as a zext, that instruction is strictly faster
8432   // than any alternative.
8433   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8434           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8435     return ZExt;
8436
8437   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8438   (void)isV1;
8439   auto isV2 = [](int M) { return M >= 8; };
8440
8441   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8442
8443   if (NumV2Inputs == 0) {
8444     // Check for being able to broadcast a single element.
8445     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8446                                                           Mask, Subtarget, DAG))
8447       return Broadcast;
8448
8449     // Try to use shift instructions.
8450     if (SDValue Shift =
8451             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8452       return Shift;
8453
8454     // Use dedicated unpack instructions for masks that match their pattern.
8455     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8456       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8457     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8458       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8459
8460     // Try to use byte rotation instructions.
8461     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8462                                                         Mask, Subtarget, DAG))
8463       return Rotate;
8464
8465     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8466                                                      Subtarget, DAG);
8467   }
8468
8469   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8470          "All single-input shuffles should be canonicalized to be V1-input "
8471          "shuffles.");
8472
8473   // Try to use shift instructions.
8474   if (SDValue Shift =
8475           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8476     return Shift;
8477
8478   // There are special ways we can lower some single-element blends.
8479   if (NumV2Inputs == 1)
8480     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8481                                                          Mask, Subtarget, DAG))
8482       return V;
8483
8484   // We have different paths for blend lowering, but they all must use the
8485   // *exact* same predicate.
8486   bool IsBlendSupported = Subtarget->hasSSE41();
8487   if (IsBlendSupported)
8488     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8489                                                   Subtarget, DAG))
8490       return Blend;
8491
8492   if (SDValue Masked =
8493           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8494     return Masked;
8495
8496   // Use dedicated unpack instructions for masks that match their pattern.
8497   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8498     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8499   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8500     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8501
8502   // Try to use byte rotation instructions.
8503   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8504           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8505     return Rotate;
8506
8507   if (SDValue BitBlend =
8508           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8509     return BitBlend;
8510
8511   if (SDValue Unpack =
8512           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8513     return Unpack;
8514
8515   // If we can't directly blend but can use PSHUFB, that will be better as it
8516   // can both shuffle and set up the inefficient blend.
8517   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8518     bool V1InUse, V2InUse;
8519     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8520                                       V1InUse, V2InUse);
8521   }
8522
8523   // We can always bit-blend if we have to so the fallback strategy is to
8524   // decompose into single-input permutes and blends.
8525   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8526                                                       Mask, DAG);
8527 }
8528
8529 /// \brief Check whether a compaction lowering can be done by dropping even
8530 /// elements and compute how many times even elements must be dropped.
8531 ///
8532 /// This handles shuffles which take every Nth element where N is a power of
8533 /// two. Example shuffle masks:
8534 ///
8535 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8536 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8537 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8538 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8539 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8540 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8541 ///
8542 /// Any of these lanes can of course be undef.
8543 ///
8544 /// This routine only supports N <= 3.
8545 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8546 /// for larger N.
8547 ///
8548 /// \returns N above, or the number of times even elements must be dropped if
8549 /// there is such a number. Otherwise returns zero.
8550 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8551   // Figure out whether we're looping over two inputs or just one.
8552   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8553
8554   // The modulus for the shuffle vector entries is based on whether this is
8555   // a single input or not.
8556   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8557   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8558          "We should only be called with masks with a power-of-2 size!");
8559
8560   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8561
8562   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8563   // and 2^3 simultaneously. This is because we may have ambiguity with
8564   // partially undef inputs.
8565   bool ViableForN[3] = {true, true, true};
8566
8567   for (int i = 0, e = Mask.size(); i < e; ++i) {
8568     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8569     // want.
8570     if (Mask[i] == -1)
8571       continue;
8572
8573     bool IsAnyViable = false;
8574     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8575       if (ViableForN[j]) {
8576         uint64_t N = j + 1;
8577
8578         // The shuffle mask must be equal to (i * 2^N) % M.
8579         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8580           IsAnyViable = true;
8581         else
8582           ViableForN[j] = false;
8583       }
8584     // Early exit if we exhaust the possible powers of two.
8585     if (!IsAnyViable)
8586       break;
8587   }
8588
8589   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8590     if (ViableForN[j])
8591       return j + 1;
8592
8593   // Return 0 as there is no viable power of two.
8594   return 0;
8595 }
8596
8597 /// \brief Generic lowering of v16i8 shuffles.
8598 ///
8599 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8600 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8601 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8602 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8603 /// back together.
8604 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8605                                        const X86Subtarget *Subtarget,
8606                                        SelectionDAG &DAG) {
8607   SDLoc DL(Op);
8608   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8609   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8610   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8611   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8612   ArrayRef<int> Mask = SVOp->getMask();
8613   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8614
8615   // Try to use shift instructions.
8616   if (SDValue Shift =
8617           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8618     return Shift;
8619
8620   // Try to use byte rotation instructions.
8621   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8622           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8623     return Rotate;
8624
8625   // Try to use a zext lowering.
8626   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8627           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8628     return ZExt;
8629
8630   int NumV2Elements =
8631       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8632
8633   // For single-input shuffles, there are some nicer lowering tricks we can use.
8634   if (NumV2Elements == 0) {
8635     // Check for being able to broadcast a single element.
8636     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8637                                                           Mask, Subtarget, DAG))
8638       return Broadcast;
8639
8640     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8641     // Notably, this handles splat and partial-splat shuffles more efficiently.
8642     // However, it only makes sense if the pre-duplication shuffle simplifies
8643     // things significantly. Currently, this means we need to be able to
8644     // express the pre-duplication shuffle as an i16 shuffle.
8645     //
8646     // FIXME: We should check for other patterns which can be widened into an
8647     // i16 shuffle as well.
8648     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8649       for (int i = 0; i < 16; i += 2)
8650         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8651           return false;
8652
8653       return true;
8654     };
8655     auto tryToWidenViaDuplication = [&]() -> SDValue {
8656       if (!canWidenViaDuplication(Mask))
8657         return SDValue();
8658       SmallVector<int, 4> LoInputs;
8659       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8660                    [](int M) { return M >= 0 && M < 8; });
8661       std::sort(LoInputs.begin(), LoInputs.end());
8662       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8663                      LoInputs.end());
8664       SmallVector<int, 4> HiInputs;
8665       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8666                    [](int M) { return M >= 8; });
8667       std::sort(HiInputs.begin(), HiInputs.end());
8668       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8669                      HiInputs.end());
8670
8671       bool TargetLo = LoInputs.size() >= HiInputs.size();
8672       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8673       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8674
8675       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8676       SmallDenseMap<int, int, 8> LaneMap;
8677       for (int I : InPlaceInputs) {
8678         PreDupI16Shuffle[I/2] = I/2;
8679         LaneMap[I] = I;
8680       }
8681       int j = TargetLo ? 0 : 4, je = j + 4;
8682       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8683         // Check if j is already a shuffle of this input. This happens when
8684         // there are two adjacent bytes after we move the low one.
8685         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8686           // If we haven't yet mapped the input, search for a slot into which
8687           // we can map it.
8688           while (j < je && PreDupI16Shuffle[j] != -1)
8689             ++j;
8690
8691           if (j == je)
8692             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8693             return SDValue();
8694
8695           // Map this input with the i16 shuffle.
8696           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8697         }
8698
8699         // Update the lane map based on the mapping we ended up with.
8700         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8701       }
8702       V1 = DAG.getNode(
8703           ISD::BITCAST, DL, MVT::v16i8,
8704           DAG.getVectorShuffle(MVT::v8i16, DL,
8705                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8706                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8707
8708       // Unpack the bytes to form the i16s that will be shuffled into place.
8709       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8710                        MVT::v16i8, V1, V1);
8711
8712       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8713       for (int i = 0; i < 16; ++i)
8714         if (Mask[i] != -1) {
8715           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8716           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8717           if (PostDupI16Shuffle[i / 2] == -1)
8718             PostDupI16Shuffle[i / 2] = MappedMask;
8719           else
8720             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8721                    "Conflicting entrties in the original shuffle!");
8722         }
8723       return DAG.getNode(
8724           ISD::BITCAST, DL, MVT::v16i8,
8725           DAG.getVectorShuffle(MVT::v8i16, DL,
8726                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8727                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8728     };
8729     if (SDValue V = tryToWidenViaDuplication())
8730       return V;
8731   }
8732
8733   // Use dedicated unpack instructions for masks that match their pattern.
8734   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8735                                          0, 16, 1, 17, 2, 18, 3, 19,
8736                                          // High half.
8737                                          4, 20, 5, 21, 6, 22, 7, 23}))
8738     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8739   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8740                                          8, 24, 9, 25, 10, 26, 11, 27,
8741                                          // High half.
8742                                          12, 28, 13, 29, 14, 30, 15, 31}))
8743     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8744
8745   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8746   // with PSHUFB. It is important to do this before we attempt to generate any
8747   // blends but after all of the single-input lowerings. If the single input
8748   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8749   // want to preserve that and we can DAG combine any longer sequences into
8750   // a PSHUFB in the end. But once we start blending from multiple inputs,
8751   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8752   // and there are *very* few patterns that would actually be faster than the
8753   // PSHUFB approach because of its ability to zero lanes.
8754   //
8755   // FIXME: The only exceptions to the above are blends which are exact
8756   // interleavings with direct instructions supporting them. We currently don't
8757   // handle those well here.
8758   if (Subtarget->hasSSSE3()) {
8759     bool V1InUse = false;
8760     bool V2InUse = false;
8761
8762     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8763                                                 DAG, V1InUse, V2InUse);
8764
8765     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8766     // do so. This avoids using them to handle blends-with-zero which is
8767     // important as a single pshufb is significantly faster for that.
8768     if (V1InUse && V2InUse) {
8769       if (Subtarget->hasSSE41())
8770         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8771                                                       Mask, Subtarget, DAG))
8772           return Blend;
8773
8774       // We can use an unpack to do the blending rather than an or in some
8775       // cases. Even though the or may be (very minorly) more efficient, we
8776       // preference this lowering because there are common cases where part of
8777       // the complexity of the shuffles goes away when we do the final blend as
8778       // an unpack.
8779       // FIXME: It might be worth trying to detect if the unpack-feeding
8780       // shuffles will both be pshufb, in which case we shouldn't bother with
8781       // this.
8782       if (SDValue Unpack =
8783               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8784         return Unpack;
8785     }
8786
8787     return PSHUFB;
8788   }
8789
8790   // There are special ways we can lower some single-element blends.
8791   if (NumV2Elements == 1)
8792     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8793                                                          Mask, Subtarget, DAG))
8794       return V;
8795
8796   if (SDValue BitBlend =
8797           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8798     return BitBlend;
8799
8800   // Check whether a compaction lowering can be done. This handles shuffles
8801   // which take every Nth element for some even N. See the helper function for
8802   // details.
8803   //
8804   // We special case these as they can be particularly efficiently handled with
8805   // the PACKUSB instruction on x86 and they show up in common patterns of
8806   // rearranging bytes to truncate wide elements.
8807   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8808     // NumEvenDrops is the power of two stride of the elements. Another way of
8809     // thinking about it is that we need to drop the even elements this many
8810     // times to get the original input.
8811     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8812
8813     // First we need to zero all the dropped bytes.
8814     assert(NumEvenDrops <= 3 &&
8815            "No support for dropping even elements more than 3 times.");
8816     // We use the mask type to pick which bytes are preserved based on how many
8817     // elements are dropped.
8818     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8819     SDValue ByteClearMask =
8820         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8821                     DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8822     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8823     if (!IsSingleInput)
8824       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8825
8826     // Now pack things back together.
8827     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8828     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8829     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8830     for (int i = 1; i < NumEvenDrops; ++i) {
8831       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8832       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8833     }
8834
8835     return Result;
8836   }
8837
8838   // Handle multi-input cases by blending single-input shuffles.
8839   if (NumV2Elements > 0)
8840     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8841                                                       Mask, DAG);
8842
8843   // The fallback path for single-input shuffles widens this into two v8i16
8844   // vectors with unpacks, shuffles those, and then pulls them back together
8845   // with a pack.
8846   SDValue V = V1;
8847
8848   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8849   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8850   for (int i = 0; i < 16; ++i)
8851     if (Mask[i] >= 0)
8852       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8853
8854   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8855
8856   SDValue VLoHalf, VHiHalf;
8857   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8858   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8859   // i16s.
8860   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8861                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8862       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8863                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8864     // Use a mask to drop the high bytes.
8865     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8866     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8867                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8868
8869     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8870     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8871
8872     // Squash the masks to point directly into VLoHalf.
8873     for (int &M : LoBlendMask)
8874       if (M >= 0)
8875         M /= 2;
8876     for (int &M : HiBlendMask)
8877       if (M >= 0)
8878         M /= 2;
8879   } else {
8880     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8881     // VHiHalf so that we can blend them as i16s.
8882     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8883                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8884     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8885                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8886   }
8887
8888   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8889   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8890
8891   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8892 }
8893
8894 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8895 ///
8896 /// This routine breaks down the specific type of 128-bit shuffle and
8897 /// dispatches to the lowering routines accordingly.
8898 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8899                                         MVT VT, const X86Subtarget *Subtarget,
8900                                         SelectionDAG &DAG) {
8901   switch (VT.SimpleTy) {
8902   case MVT::v2i64:
8903     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8904   case MVT::v2f64:
8905     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8906   case MVT::v4i32:
8907     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8908   case MVT::v4f32:
8909     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8910   case MVT::v8i16:
8911     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8912   case MVT::v16i8:
8913     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8914
8915   default:
8916     llvm_unreachable("Unimplemented!");
8917   }
8918 }
8919
8920 /// \brief Helper function to test whether a shuffle mask could be
8921 /// simplified by widening the elements being shuffled.
8922 ///
8923 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8924 /// leaves it in an unspecified state.
8925 ///
8926 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8927 /// shuffle masks. The latter have the special property of a '-2' representing
8928 /// a zero-ed lane of a vector.
8929 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8930                                     SmallVectorImpl<int> &WidenedMask) {
8931   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8932     // If both elements are undef, its trivial.
8933     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8934       WidenedMask.push_back(SM_SentinelUndef);
8935       continue;
8936     }
8937
8938     // Check for an undef mask and a mask value properly aligned to fit with
8939     // a pair of values. If we find such a case, use the non-undef mask's value.
8940     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8941       WidenedMask.push_back(Mask[i + 1] / 2);
8942       continue;
8943     }
8944     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8945       WidenedMask.push_back(Mask[i] / 2);
8946       continue;
8947     }
8948
8949     // When zeroing, we need to spread the zeroing across both lanes to widen.
8950     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8951       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8952           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8953         WidenedMask.push_back(SM_SentinelZero);
8954         continue;
8955       }
8956       return false;
8957     }
8958
8959     // Finally check if the two mask values are adjacent and aligned with
8960     // a pair.
8961     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8962       WidenedMask.push_back(Mask[i] / 2);
8963       continue;
8964     }
8965
8966     // Otherwise we can't safely widen the elements used in this shuffle.
8967     return false;
8968   }
8969   assert(WidenedMask.size() == Mask.size() / 2 &&
8970          "Incorrect size of mask after widening the elements!");
8971
8972   return true;
8973 }
8974
8975 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8976 ///
8977 /// This routine just extracts two subvectors, shuffles them independently, and
8978 /// then concatenates them back together. This should work effectively with all
8979 /// AVX vector shuffle types.
8980 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8981                                           SDValue V2, ArrayRef<int> Mask,
8982                                           SelectionDAG &DAG) {
8983   assert(VT.getSizeInBits() >= 256 &&
8984          "Only for 256-bit or wider vector shuffles!");
8985   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8986   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8987
8988   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8989   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8990
8991   int NumElements = VT.getVectorNumElements();
8992   int SplitNumElements = NumElements / 2;
8993   MVT ScalarVT = VT.getScalarType();
8994   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8995
8996   // Rather than splitting build-vectors, just build two narrower build
8997   // vectors. This helps shuffling with splats and zeros.
8998   auto SplitVector = [&](SDValue V) {
8999     while (V.getOpcode() == ISD::BITCAST)
9000       V = V->getOperand(0);
9001
9002     MVT OrigVT = V.getSimpleValueType();
9003     int OrigNumElements = OrigVT.getVectorNumElements();
9004     int OrigSplitNumElements = OrigNumElements / 2;
9005     MVT OrigScalarVT = OrigVT.getScalarType();
9006     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9007
9008     SDValue LoV, HiV;
9009
9010     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9011     if (!BV) {
9012       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9013                         DAG.getIntPtrConstant(0, DL));
9014       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9015                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9016     } else {
9017
9018       SmallVector<SDValue, 16> LoOps, HiOps;
9019       for (int i = 0; i < OrigSplitNumElements; ++i) {
9020         LoOps.push_back(BV->getOperand(i));
9021         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9022       }
9023       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9024       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9025     }
9026     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9027                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9028   };
9029
9030   SDValue LoV1, HiV1, LoV2, HiV2;
9031   std::tie(LoV1, HiV1) = SplitVector(V1);
9032   std::tie(LoV2, HiV2) = SplitVector(V2);
9033
9034   // Now create two 4-way blends of these half-width vectors.
9035   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9036     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9037     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9038     for (int i = 0; i < SplitNumElements; ++i) {
9039       int M = HalfMask[i];
9040       if (M >= NumElements) {
9041         if (M >= NumElements + SplitNumElements)
9042           UseHiV2 = true;
9043         else
9044           UseLoV2 = true;
9045         V2BlendMask.push_back(M - NumElements);
9046         V1BlendMask.push_back(-1);
9047         BlendMask.push_back(SplitNumElements + i);
9048       } else if (M >= 0) {
9049         if (M >= SplitNumElements)
9050           UseHiV1 = true;
9051         else
9052           UseLoV1 = true;
9053         V2BlendMask.push_back(-1);
9054         V1BlendMask.push_back(M);
9055         BlendMask.push_back(i);
9056       } else {
9057         V2BlendMask.push_back(-1);
9058         V1BlendMask.push_back(-1);
9059         BlendMask.push_back(-1);
9060       }
9061     }
9062
9063     // Because the lowering happens after all combining takes place, we need to
9064     // manually combine these blend masks as much as possible so that we create
9065     // a minimal number of high-level vector shuffle nodes.
9066
9067     // First try just blending the halves of V1 or V2.
9068     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9069       return DAG.getUNDEF(SplitVT);
9070     if (!UseLoV2 && !UseHiV2)
9071       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9072     if (!UseLoV1 && !UseHiV1)
9073       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9074
9075     SDValue V1Blend, V2Blend;
9076     if (UseLoV1 && UseHiV1) {
9077       V1Blend =
9078         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9079     } else {
9080       // We only use half of V1 so map the usage down into the final blend mask.
9081       V1Blend = UseLoV1 ? LoV1 : HiV1;
9082       for (int i = 0; i < SplitNumElements; ++i)
9083         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9084           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9085     }
9086     if (UseLoV2 && UseHiV2) {
9087       V2Blend =
9088         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9089     } else {
9090       // We only use half of V2 so map the usage down into the final blend mask.
9091       V2Blend = UseLoV2 ? LoV2 : HiV2;
9092       for (int i = 0; i < SplitNumElements; ++i)
9093         if (BlendMask[i] >= SplitNumElements)
9094           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9095     }
9096     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9097   };
9098   SDValue Lo = HalfBlend(LoMask);
9099   SDValue Hi = HalfBlend(HiMask);
9100   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9101 }
9102
9103 /// \brief Either split a vector in halves or decompose the shuffles and the
9104 /// blend.
9105 ///
9106 /// This is provided as a good fallback for many lowerings of non-single-input
9107 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9108 /// between splitting the shuffle into 128-bit components and stitching those
9109 /// back together vs. extracting the single-input shuffles and blending those
9110 /// results.
9111 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9112                                                 SDValue V2, ArrayRef<int> Mask,
9113                                                 SelectionDAG &DAG) {
9114   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9115                                             "lower single-input shuffles as it "
9116                                             "could then recurse on itself.");
9117   int Size = Mask.size();
9118
9119   // If this can be modeled as a broadcast of two elements followed by a blend,
9120   // prefer that lowering. This is especially important because broadcasts can
9121   // often fold with memory operands.
9122   auto DoBothBroadcast = [&] {
9123     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9124     for (int M : Mask)
9125       if (M >= Size) {
9126         if (V2BroadcastIdx == -1)
9127           V2BroadcastIdx = M - Size;
9128         else if (M - Size != V2BroadcastIdx)
9129           return false;
9130       } else if (M >= 0) {
9131         if (V1BroadcastIdx == -1)
9132           V1BroadcastIdx = M;
9133         else if (M != V1BroadcastIdx)
9134           return false;
9135       }
9136     return true;
9137   };
9138   if (DoBothBroadcast())
9139     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9140                                                       DAG);
9141
9142   // If the inputs all stem from a single 128-bit lane of each input, then we
9143   // split them rather than blending because the split will decompose to
9144   // unusually few instructions.
9145   int LaneCount = VT.getSizeInBits() / 128;
9146   int LaneSize = Size / LaneCount;
9147   SmallBitVector LaneInputs[2];
9148   LaneInputs[0].resize(LaneCount, false);
9149   LaneInputs[1].resize(LaneCount, false);
9150   for (int i = 0; i < Size; ++i)
9151     if (Mask[i] >= 0)
9152       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9153   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9154     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9155
9156   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9157   // that the decomposed single-input shuffles don't end up here.
9158   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9159 }
9160
9161 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9162 /// a permutation and blend of those lanes.
9163 ///
9164 /// This essentially blends the out-of-lane inputs to each lane into the lane
9165 /// from a permuted copy of the vector. This lowering strategy results in four
9166 /// instructions in the worst case for a single-input cross lane shuffle which
9167 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9168 /// of. Special cases for each particular shuffle pattern should be handled
9169 /// prior to trying this lowering.
9170 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9171                                                        SDValue V1, SDValue V2,
9172                                                        ArrayRef<int> Mask,
9173                                                        SelectionDAG &DAG) {
9174   // FIXME: This should probably be generalized for 512-bit vectors as well.
9175   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9176   int LaneSize = Mask.size() / 2;
9177
9178   // If there are only inputs from one 128-bit lane, splitting will in fact be
9179   // less expensive. The flags track whether the given lane contains an element
9180   // that crosses to another lane.
9181   bool LaneCrossing[2] = {false, false};
9182   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9183     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9184       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9185   if (!LaneCrossing[0] || !LaneCrossing[1])
9186     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9187
9188   if (isSingleInputShuffleMask(Mask)) {
9189     SmallVector<int, 32> FlippedBlendMask;
9190     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9191       FlippedBlendMask.push_back(
9192           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9193                                   ? Mask[i]
9194                                   : Mask[i] % LaneSize +
9195                                         (i / LaneSize) * LaneSize + Size));
9196
9197     // Flip the vector, and blend the results which should now be in-lane. The
9198     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9199     // 5 for the high source. The value 3 selects the high half of source 2 and
9200     // the value 2 selects the low half of source 2. We only use source 2 to
9201     // allow folding it into a memory operand.
9202     unsigned PERMMask = 3 | 2 << 4;
9203     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9204                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9205     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9206   }
9207
9208   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9209   // will be handled by the above logic and a blend of the results, much like
9210   // other patterns in AVX.
9211   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9212 }
9213
9214 /// \brief Handle lowering 2-lane 128-bit shuffles.
9215 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9216                                         SDValue V2, ArrayRef<int> Mask,
9217                                         const X86Subtarget *Subtarget,
9218                                         SelectionDAG &DAG) {
9219   // TODO: If minimizing size and one of the inputs is a zero vector and the
9220   // the zero vector has only one use, we could use a VPERM2X128 to save the
9221   // instruction bytes needed to explicitly generate the zero vector.
9222
9223   // Blends are faster and handle all the non-lane-crossing cases.
9224   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9225                                                 Subtarget, DAG))
9226     return Blend;
9227
9228   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9229   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9230
9231   // If either input operand is a zero vector, use VPERM2X128 because its mask
9232   // allows us to replace the zero input with an implicit zero.
9233   if (!IsV1Zero && !IsV2Zero) {
9234     // Check for patterns which can be matched with a single insert of a 128-bit
9235     // subvector.
9236     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9237     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9238       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9239                                    VT.getVectorNumElements() / 2);
9240       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9241                                 DAG.getIntPtrConstant(0, DL));
9242       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9243                                 OnlyUsesV1 ? V1 : V2,
9244                                 DAG.getIntPtrConstant(0, DL));
9245       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9246     }
9247   }
9248
9249   // Otherwise form a 128-bit permutation. After accounting for undefs,
9250   // convert the 64-bit shuffle mask selection values into 128-bit
9251   // selection bits by dividing the indexes by 2 and shifting into positions
9252   // defined by a vperm2*128 instruction's immediate control byte.
9253
9254   // The immediate permute control byte looks like this:
9255   //    [1:0] - select 128 bits from sources for low half of destination
9256   //    [2]   - ignore
9257   //    [3]   - zero low half of destination
9258   //    [5:4] - select 128 bits from sources for high half of destination
9259   //    [6]   - ignore
9260   //    [7]   - zero high half of destination
9261
9262   int MaskLO = Mask[0];
9263   if (MaskLO == SM_SentinelUndef)
9264     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9265
9266   int MaskHI = Mask[2];
9267   if (MaskHI == SM_SentinelUndef)
9268     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9269
9270   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9271
9272   // If either input is a zero vector, replace it with an undef input.
9273   // Shuffle mask values <  4 are selecting elements of V1.
9274   // Shuffle mask values >= 4 are selecting elements of V2.
9275   // Adjust each half of the permute mask by clearing the half that was
9276   // selecting the zero vector and setting the zero mask bit.
9277   if (IsV1Zero) {
9278     V1 = DAG.getUNDEF(VT);
9279     if (MaskLO < 4)
9280       PermMask = (PermMask & 0xf0) | 0x08;
9281     if (MaskHI < 4)
9282       PermMask = (PermMask & 0x0f) | 0x80;
9283   }
9284   if (IsV2Zero) {
9285     V2 = DAG.getUNDEF(VT);
9286     if (MaskLO >= 4)
9287       PermMask = (PermMask & 0xf0) | 0x08;
9288     if (MaskHI >= 4)
9289       PermMask = (PermMask & 0x0f) | 0x80;
9290   }
9291
9292   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9293                      DAG.getConstant(PermMask, DL, MVT::i8));
9294 }
9295
9296 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9297 /// shuffling each lane.
9298 ///
9299 /// This will only succeed when the result of fixing the 128-bit lanes results
9300 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9301 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9302 /// the lane crosses early and then use simpler shuffles within each lane.
9303 ///
9304 /// FIXME: It might be worthwhile at some point to support this without
9305 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9306 /// in x86 only floating point has interesting non-repeating shuffles, and even
9307 /// those are still *marginally* more expensive.
9308 static SDValue lowerVectorShuffleByMerging128BitLanes(
9309     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9310     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9311   assert(!isSingleInputShuffleMask(Mask) &&
9312          "This is only useful with multiple inputs.");
9313
9314   int Size = Mask.size();
9315   int LaneSize = 128 / VT.getScalarSizeInBits();
9316   int NumLanes = Size / LaneSize;
9317   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9318
9319   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9320   // check whether the in-128-bit lane shuffles share a repeating pattern.
9321   SmallVector<int, 4> Lanes;
9322   Lanes.resize(NumLanes, -1);
9323   SmallVector<int, 4> InLaneMask;
9324   InLaneMask.resize(LaneSize, -1);
9325   for (int i = 0; i < Size; ++i) {
9326     if (Mask[i] < 0)
9327       continue;
9328
9329     int j = i / LaneSize;
9330
9331     if (Lanes[j] < 0) {
9332       // First entry we've seen for this lane.
9333       Lanes[j] = Mask[i] / LaneSize;
9334     } else if (Lanes[j] != Mask[i] / LaneSize) {
9335       // This doesn't match the lane selected previously!
9336       return SDValue();
9337     }
9338
9339     // Check that within each lane we have a consistent shuffle mask.
9340     int k = i % LaneSize;
9341     if (InLaneMask[k] < 0) {
9342       InLaneMask[k] = Mask[i] % LaneSize;
9343     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9344       // This doesn't fit a repeating in-lane mask.
9345       return SDValue();
9346     }
9347   }
9348
9349   // First shuffle the lanes into place.
9350   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9351                                 VT.getSizeInBits() / 64);
9352   SmallVector<int, 8> LaneMask;
9353   LaneMask.resize(NumLanes * 2, -1);
9354   for (int i = 0; i < NumLanes; ++i)
9355     if (Lanes[i] >= 0) {
9356       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9357       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9358     }
9359
9360   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9361   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9362   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9363
9364   // Cast it back to the type we actually want.
9365   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9366
9367   // Now do a simple shuffle that isn't lane crossing.
9368   SmallVector<int, 8> NewMask;
9369   NewMask.resize(Size, -1);
9370   for (int i = 0; i < Size; ++i)
9371     if (Mask[i] >= 0)
9372       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9373   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9374          "Must not introduce lane crosses at this point!");
9375
9376   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9377 }
9378
9379 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9380 /// given mask.
9381 ///
9382 /// This returns true if the elements from a particular input are already in the
9383 /// slot required by the given mask and require no permutation.
9384 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9385   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9386   int Size = Mask.size();
9387   for (int i = 0; i < Size; ++i)
9388     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9389       return false;
9390
9391   return true;
9392 }
9393
9394 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9395 ///
9396 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9397 /// isn't available.
9398 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9399                                        const X86Subtarget *Subtarget,
9400                                        SelectionDAG &DAG) {
9401   SDLoc DL(Op);
9402   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9403   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9404   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9405   ArrayRef<int> Mask = SVOp->getMask();
9406   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9407
9408   SmallVector<int, 4> WidenedMask;
9409   if (canWidenShuffleElements(Mask, WidenedMask))
9410     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9411                                     DAG);
9412
9413   if (isSingleInputShuffleMask(Mask)) {
9414     // Check for being able to broadcast a single element.
9415     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9416                                                           Mask, Subtarget, DAG))
9417       return Broadcast;
9418
9419     // Use low duplicate instructions for masks that match their pattern.
9420     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9421       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9422
9423     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9424       // Non-half-crossing single input shuffles can be lowerid with an
9425       // interleaved permutation.
9426       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9427                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9428       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9429                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9430     }
9431
9432     // With AVX2 we have direct support for this permutation.
9433     if (Subtarget->hasAVX2())
9434       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9435                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9436
9437     // Otherwise, fall back.
9438     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9439                                                    DAG);
9440   }
9441
9442   // X86 has dedicated unpack instructions that can handle specific blend
9443   // operations: UNPCKH and UNPCKL.
9444   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9445     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9446   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9447     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9448   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9449     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9450   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9451     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9452
9453   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9454                                                 Subtarget, DAG))
9455     return Blend;
9456
9457   // Check if the blend happens to exactly fit that of SHUFPD.
9458   if ((Mask[0] == -1 || Mask[0] < 2) &&
9459       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9460       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9461       (Mask[3] == -1 || Mask[3] >= 6)) {
9462     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9463                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9464     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9465                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9466   }
9467   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9468       (Mask[1] == -1 || Mask[1] < 2) &&
9469       (Mask[2] == -1 || Mask[2] >= 6) &&
9470       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9471     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9472                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9473     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9474                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9475   }
9476
9477   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9478   // shuffle. However, if we have AVX2 and either inputs are already in place,
9479   // we will be able to shuffle even across lanes the other input in a single
9480   // instruction so skip this pattern.
9481   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9482                                  isShuffleMaskInputInPlace(1, Mask))))
9483     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9484             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9485       return Result;
9486
9487   // If we have AVX2 then we always want to lower with a blend because an v4 we
9488   // can fully permute the elements.
9489   if (Subtarget->hasAVX2())
9490     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9491                                                       Mask, DAG);
9492
9493   // Otherwise fall back on generic lowering.
9494   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9495 }
9496
9497 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9498 ///
9499 /// This routine is only called when we have AVX2 and thus a reasonable
9500 /// instruction set for v4i64 shuffling..
9501 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9502                                        const X86Subtarget *Subtarget,
9503                                        SelectionDAG &DAG) {
9504   SDLoc DL(Op);
9505   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9506   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9507   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9508   ArrayRef<int> Mask = SVOp->getMask();
9509   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9510   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9511
9512   SmallVector<int, 4> WidenedMask;
9513   if (canWidenShuffleElements(Mask, WidenedMask))
9514     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9515                                     DAG);
9516
9517   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9518                                                 Subtarget, DAG))
9519     return Blend;
9520
9521   // Check for being able to broadcast a single element.
9522   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9523                                                         Mask, Subtarget, DAG))
9524     return Broadcast;
9525
9526   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9527   // use lower latency instructions that will operate on both 128-bit lanes.
9528   SmallVector<int, 2> RepeatedMask;
9529   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9530     if (isSingleInputShuffleMask(Mask)) {
9531       int PSHUFDMask[] = {-1, -1, -1, -1};
9532       for (int i = 0; i < 2; ++i)
9533         if (RepeatedMask[i] >= 0) {
9534           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9535           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9536         }
9537       return DAG.getNode(
9538           ISD::BITCAST, DL, MVT::v4i64,
9539           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9540                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9541                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9542     }
9543   }
9544
9545   // AVX2 provides a direct instruction for permuting a single input across
9546   // lanes.
9547   if (isSingleInputShuffleMask(Mask))
9548     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9549                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9550
9551   // Try to use shift instructions.
9552   if (SDValue Shift =
9553           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9554     return Shift;
9555
9556   // Use dedicated unpack instructions for masks that match their pattern.
9557   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9558     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9559   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9560     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9561   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9562     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9563   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9564     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9565
9566   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9567   // shuffle. However, if we have AVX2 and either inputs are already in place,
9568   // we will be able to shuffle even across lanes the other input in a single
9569   // instruction so skip this pattern.
9570   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9571                                  isShuffleMaskInputInPlace(1, Mask))))
9572     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9573             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9574       return Result;
9575
9576   // Otherwise fall back on generic blend lowering.
9577   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9578                                                     Mask, DAG);
9579 }
9580
9581 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9582 ///
9583 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9584 /// isn't available.
9585 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9586                                        const X86Subtarget *Subtarget,
9587                                        SelectionDAG &DAG) {
9588   SDLoc DL(Op);
9589   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9590   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9591   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9592   ArrayRef<int> Mask = SVOp->getMask();
9593   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9594
9595   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9596                                                 Subtarget, DAG))
9597     return Blend;
9598
9599   // Check for being able to broadcast a single element.
9600   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9601                                                         Mask, Subtarget, DAG))
9602     return Broadcast;
9603
9604   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9605   // options to efficiently lower the shuffle.
9606   SmallVector<int, 4> RepeatedMask;
9607   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9608     assert(RepeatedMask.size() == 4 &&
9609            "Repeated masks must be half the mask width!");
9610
9611     // Use even/odd duplicate instructions for masks that match their pattern.
9612     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9613       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9614     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9615       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9616
9617     if (isSingleInputShuffleMask(Mask))
9618       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9619                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9620
9621     // Use dedicated unpack instructions for masks that match their pattern.
9622     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9623       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9624     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9625       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9626     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9627       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9628     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9629       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9630
9631     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9632     // have already handled any direct blends. We also need to squash the
9633     // repeated mask into a simulated v4f32 mask.
9634     for (int i = 0; i < 4; ++i)
9635       if (RepeatedMask[i] >= 8)
9636         RepeatedMask[i] -= 4;
9637     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9638   }
9639
9640   // If we have a single input shuffle with different shuffle patterns in the
9641   // two 128-bit lanes use the variable mask to VPERMILPS.
9642   if (isSingleInputShuffleMask(Mask)) {
9643     SDValue VPermMask[8];
9644     for (int i = 0; i < 8; ++i)
9645       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9646                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9647     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9648       return DAG.getNode(
9649           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9650           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9651
9652     if (Subtarget->hasAVX2())
9653       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9654                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9655                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9656                                                  MVT::v8i32, VPermMask)),
9657                          V1);
9658
9659     // Otherwise, fall back.
9660     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9661                                                    DAG);
9662   }
9663
9664   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9665   // shuffle.
9666   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9667           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9668     return Result;
9669
9670   // If we have AVX2 then we always want to lower with a blend because at v8 we
9671   // can fully permute the elements.
9672   if (Subtarget->hasAVX2())
9673     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9674                                                       Mask, DAG);
9675
9676   // Otherwise fall back on generic lowering.
9677   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9678 }
9679
9680 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9681 ///
9682 /// This routine is only called when we have AVX2 and thus a reasonable
9683 /// instruction set for v8i32 shuffling..
9684 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9685                                        const X86Subtarget *Subtarget,
9686                                        SelectionDAG &DAG) {
9687   SDLoc DL(Op);
9688   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9689   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9690   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9691   ArrayRef<int> Mask = SVOp->getMask();
9692   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9693   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9694
9695   // Whenever we can lower this as a zext, that instruction is strictly faster
9696   // than any alternative. It also allows us to fold memory operands into the
9697   // shuffle in many cases.
9698   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9699                                                          Mask, Subtarget, DAG))
9700     return ZExt;
9701
9702   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9703                                                 Subtarget, DAG))
9704     return Blend;
9705
9706   // Check for being able to broadcast a single element.
9707   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9708                                                         Mask, Subtarget, DAG))
9709     return Broadcast;
9710
9711   // If the shuffle mask is repeated in each 128-bit lane we can use more
9712   // efficient instructions that mirror the shuffles across the two 128-bit
9713   // lanes.
9714   SmallVector<int, 4> RepeatedMask;
9715   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9716     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9717     if (isSingleInputShuffleMask(Mask))
9718       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9719                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9720
9721     // Use dedicated unpack instructions for masks that match their pattern.
9722     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9723       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9724     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9725       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9726     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9727       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9728     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9729       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9730   }
9731
9732   // Try to use shift instructions.
9733   if (SDValue Shift =
9734           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9735     return Shift;
9736
9737   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9738           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9739     return Rotate;
9740
9741   // If the shuffle patterns aren't repeated but it is a single input, directly
9742   // generate a cross-lane VPERMD instruction.
9743   if (isSingleInputShuffleMask(Mask)) {
9744     SDValue VPermMask[8];
9745     for (int i = 0; i < 8; ++i)
9746       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9747                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9748     return DAG.getNode(
9749         X86ISD::VPERMV, DL, MVT::v8i32,
9750         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9751   }
9752
9753   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9754   // shuffle.
9755   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9756           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9757     return Result;
9758
9759   // Otherwise fall back on generic blend lowering.
9760   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9761                                                     Mask, DAG);
9762 }
9763
9764 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9765 ///
9766 /// This routine is only called when we have AVX2 and thus a reasonable
9767 /// instruction set for v16i16 shuffling..
9768 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9769                                         const X86Subtarget *Subtarget,
9770                                         SelectionDAG &DAG) {
9771   SDLoc DL(Op);
9772   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9773   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9774   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9775   ArrayRef<int> Mask = SVOp->getMask();
9776   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9777   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9778
9779   // Whenever we can lower this as a zext, that instruction is strictly faster
9780   // than any alternative. It also allows us to fold memory operands into the
9781   // shuffle in many cases.
9782   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9783                                                          Mask, Subtarget, DAG))
9784     return ZExt;
9785
9786   // Check for being able to broadcast a single element.
9787   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9788                                                         Mask, Subtarget, DAG))
9789     return Broadcast;
9790
9791   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9792                                                 Subtarget, DAG))
9793     return Blend;
9794
9795   // Use dedicated unpack instructions for masks that match their pattern.
9796   if (isShuffleEquivalent(V1, V2, Mask,
9797                           {// First 128-bit lane:
9798                            0, 16, 1, 17, 2, 18, 3, 19,
9799                            // Second 128-bit lane:
9800                            8, 24, 9, 25, 10, 26, 11, 27}))
9801     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9802   if (isShuffleEquivalent(V1, V2, Mask,
9803                           {// First 128-bit lane:
9804                            4, 20, 5, 21, 6, 22, 7, 23,
9805                            // Second 128-bit lane:
9806                            12, 28, 13, 29, 14, 30, 15, 31}))
9807     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9808
9809   // Try to use shift instructions.
9810   if (SDValue Shift =
9811           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9812     return Shift;
9813
9814   // Try to use byte rotation instructions.
9815   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9816           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9817     return Rotate;
9818
9819   if (isSingleInputShuffleMask(Mask)) {
9820     // There are no generalized cross-lane shuffle operations available on i16
9821     // element types.
9822     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9823       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9824                                                      Mask, DAG);
9825
9826     SmallVector<int, 8> RepeatedMask;
9827     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9828       // As this is a single-input shuffle, the repeated mask should be
9829       // a strictly valid v8i16 mask that we can pass through to the v8i16
9830       // lowering to handle even the v16 case.
9831       return lowerV8I16GeneralSingleInputVectorShuffle(
9832           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9833     }
9834
9835     SDValue PSHUFBMask[32];
9836     for (int i = 0; i < 16; ++i) {
9837       if (Mask[i] == -1) {
9838         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9839         continue;
9840       }
9841
9842       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9843       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9844       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9845       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9846     }
9847     return DAG.getNode(
9848         ISD::BITCAST, DL, MVT::v16i16,
9849         DAG.getNode(
9850             X86ISD::PSHUFB, DL, MVT::v32i8,
9851             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9852             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9853   }
9854
9855   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9856   // shuffle.
9857   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9858           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9859     return Result;
9860
9861   // Otherwise fall back on generic lowering.
9862   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9863 }
9864
9865 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9866 ///
9867 /// This routine is only called when we have AVX2 and thus a reasonable
9868 /// instruction set for v32i8 shuffling..
9869 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9870                                        const X86Subtarget *Subtarget,
9871                                        SelectionDAG &DAG) {
9872   SDLoc DL(Op);
9873   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9874   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9875   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9876   ArrayRef<int> Mask = SVOp->getMask();
9877   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9878   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9879
9880   // Whenever we can lower this as a zext, that instruction is strictly faster
9881   // than any alternative. It also allows us to fold memory operands into the
9882   // shuffle in many cases.
9883   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9884                                                          Mask, Subtarget, DAG))
9885     return ZExt;
9886
9887   // Check for being able to broadcast a single element.
9888   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9889                                                         Mask, Subtarget, DAG))
9890     return Broadcast;
9891
9892   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9893                                                 Subtarget, DAG))
9894     return Blend;
9895
9896   // Use dedicated unpack instructions for masks that match their pattern.
9897   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9898   // 256-bit lanes.
9899   if (isShuffleEquivalent(
9900           V1, V2, Mask,
9901           {// First 128-bit lane:
9902            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9903            // Second 128-bit lane:
9904            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9905     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9906   if (isShuffleEquivalent(
9907           V1, V2, Mask,
9908           {// First 128-bit lane:
9909            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9910            // Second 128-bit lane:
9911            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9912     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9913
9914   // Try to use shift instructions.
9915   if (SDValue Shift =
9916           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9917     return Shift;
9918
9919   // Try to use byte rotation instructions.
9920   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9921           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9922     return Rotate;
9923
9924   if (isSingleInputShuffleMask(Mask)) {
9925     // There are no generalized cross-lane shuffle operations available on i8
9926     // element types.
9927     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9928       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9929                                                      Mask, DAG);
9930
9931     SDValue PSHUFBMask[32];
9932     for (int i = 0; i < 32; ++i)
9933       PSHUFBMask[i] =
9934           Mask[i] < 0
9935               ? DAG.getUNDEF(MVT::i8)
9936               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9937                                 MVT::i8);
9938
9939     return DAG.getNode(
9940         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9941         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9942   }
9943
9944   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9945   // shuffle.
9946   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9947           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9948     return Result;
9949
9950   // Otherwise fall back on generic lowering.
9951   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9952 }
9953
9954 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9955 ///
9956 /// This routine either breaks down the specific type of a 256-bit x86 vector
9957 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9958 /// together based on the available instructions.
9959 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9960                                         MVT VT, const X86Subtarget *Subtarget,
9961                                         SelectionDAG &DAG) {
9962   SDLoc DL(Op);
9963   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9964   ArrayRef<int> Mask = SVOp->getMask();
9965
9966   // If we have a single input to the zero element, insert that into V1 if we
9967   // can do so cheaply.
9968   int NumElts = VT.getVectorNumElements();
9969   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9970     return M >= NumElts;
9971   });
9972
9973   if (NumV2Elements == 1 && Mask[0] >= NumElts)
9974     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9975                               DL, VT, V1, V2, Mask, Subtarget, DAG))
9976       return Insertion;
9977
9978   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9979   // check for those subtargets here and avoid much of the subtarget querying in
9980   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9981   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9982   // floating point types there eventually, just immediately cast everything to
9983   // a float and operate entirely in that domain.
9984   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9985     int ElementBits = VT.getScalarSizeInBits();
9986     if (ElementBits < 32)
9987       // No floating point type available, decompose into 128-bit vectors.
9988       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9989
9990     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9991                                 VT.getVectorNumElements());
9992     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9993     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9994     return DAG.getNode(ISD::BITCAST, DL, VT,
9995                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9996   }
9997
9998   switch (VT.SimpleTy) {
9999   case MVT::v4f64:
10000     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10001   case MVT::v4i64:
10002     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10003   case MVT::v8f32:
10004     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10005   case MVT::v8i32:
10006     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10007   case MVT::v16i16:
10008     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10009   case MVT::v32i8:
10010     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10011
10012   default:
10013     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10014   }
10015 }
10016
10017 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10018 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10019                                        const X86Subtarget *Subtarget,
10020                                        SelectionDAG &DAG) {
10021   SDLoc DL(Op);
10022   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10023   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10024   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10025   ArrayRef<int> Mask = SVOp->getMask();
10026   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10027
10028   // X86 has dedicated unpack instructions that can handle specific blend
10029   // operations: UNPCKH and UNPCKL.
10030   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10031     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10032   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10033     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10034
10035   // FIXME: Implement direct support for this type!
10036   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10037 }
10038
10039 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10040 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10041                                        const X86Subtarget *Subtarget,
10042                                        SelectionDAG &DAG) {
10043   SDLoc DL(Op);
10044   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10045   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10046   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10047   ArrayRef<int> Mask = SVOp->getMask();
10048   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10049
10050   // Use dedicated unpack instructions for masks that match their pattern.
10051   if (isShuffleEquivalent(V1, V2, Mask,
10052                           {// First 128-bit lane.
10053                            0, 16, 1, 17, 4, 20, 5, 21,
10054                            // Second 128-bit lane.
10055                            8, 24, 9, 25, 12, 28, 13, 29}))
10056     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10057   if (isShuffleEquivalent(V1, V2, Mask,
10058                           {// First 128-bit lane.
10059                            2, 18, 3, 19, 6, 22, 7, 23,
10060                            // Second 128-bit lane.
10061                            10, 26, 11, 27, 14, 30, 15, 31}))
10062     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10063
10064   // FIXME: Implement direct support for this type!
10065   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10066 }
10067
10068 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10069 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10070                                        const X86Subtarget *Subtarget,
10071                                        SelectionDAG &DAG) {
10072   SDLoc DL(Op);
10073   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10074   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10075   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10076   ArrayRef<int> Mask = SVOp->getMask();
10077   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10078
10079   // X86 has dedicated unpack instructions that can handle specific blend
10080   // operations: UNPCKH and UNPCKL.
10081   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10082     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10083   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10084     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10085
10086   // FIXME: Implement direct support for this type!
10087   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10088 }
10089
10090 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10091 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10092                                        const X86Subtarget *Subtarget,
10093                                        SelectionDAG &DAG) {
10094   SDLoc DL(Op);
10095   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10096   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10097   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10098   ArrayRef<int> Mask = SVOp->getMask();
10099   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10100
10101   // Use dedicated unpack instructions for masks that match their pattern.
10102   if (isShuffleEquivalent(V1, V2, Mask,
10103                           {// First 128-bit lane.
10104                            0, 16, 1, 17, 4, 20, 5, 21,
10105                            // Second 128-bit lane.
10106                            8, 24, 9, 25, 12, 28, 13, 29}))
10107     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10108   if (isShuffleEquivalent(V1, V2, Mask,
10109                           {// First 128-bit lane.
10110                            2, 18, 3, 19, 6, 22, 7, 23,
10111                            // Second 128-bit lane.
10112                            10, 26, 11, 27, 14, 30, 15, 31}))
10113     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10114
10115   // FIXME: Implement direct support for this type!
10116   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10117 }
10118
10119 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10120 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10121                                         const X86Subtarget *Subtarget,
10122                                         SelectionDAG &DAG) {
10123   SDLoc DL(Op);
10124   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10125   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10126   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10127   ArrayRef<int> Mask = SVOp->getMask();
10128   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10129   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10130
10131   // FIXME: Implement direct support for this type!
10132   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10133 }
10134
10135 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10136 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10137                                        const X86Subtarget *Subtarget,
10138                                        SelectionDAG &DAG) {
10139   SDLoc DL(Op);
10140   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10141   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10142   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10143   ArrayRef<int> Mask = SVOp->getMask();
10144   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10145   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10146
10147   // FIXME: Implement direct support for this type!
10148   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10149 }
10150
10151 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10152 ///
10153 /// This routine either breaks down the specific type of a 512-bit x86 vector
10154 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10155 /// together based on the available instructions.
10156 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10157                                         MVT VT, const X86Subtarget *Subtarget,
10158                                         SelectionDAG &DAG) {
10159   SDLoc DL(Op);
10160   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10161   ArrayRef<int> Mask = SVOp->getMask();
10162   assert(Subtarget->hasAVX512() &&
10163          "Cannot lower 512-bit vectors w/ basic ISA!");
10164
10165   // Check for being able to broadcast a single element.
10166   if (SDValue Broadcast =
10167           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10168     return Broadcast;
10169
10170   // Dispatch to each element type for lowering. If we don't have supprot for
10171   // specific element type shuffles at 512 bits, immediately split them and
10172   // lower them. Each lowering routine of a given type is allowed to assume that
10173   // the requisite ISA extensions for that element type are available.
10174   switch (VT.SimpleTy) {
10175   case MVT::v8f64:
10176     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10177   case MVT::v16f32:
10178     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10179   case MVT::v8i64:
10180     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10181   case MVT::v16i32:
10182     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10183   case MVT::v32i16:
10184     if (Subtarget->hasBWI())
10185       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10186     break;
10187   case MVT::v64i8:
10188     if (Subtarget->hasBWI())
10189       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10190     break;
10191
10192   default:
10193     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10194   }
10195
10196   // Otherwise fall back on splitting.
10197   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10198 }
10199
10200 /// \brief Top-level lowering for x86 vector shuffles.
10201 ///
10202 /// This handles decomposition, canonicalization, and lowering of all x86
10203 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10204 /// above in helper routines. The canonicalization attempts to widen shuffles
10205 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10206 /// s.t. only one of the two inputs needs to be tested, etc.
10207 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10208                                   SelectionDAG &DAG) {
10209   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10210   ArrayRef<int> Mask = SVOp->getMask();
10211   SDValue V1 = Op.getOperand(0);
10212   SDValue V2 = Op.getOperand(1);
10213   MVT VT = Op.getSimpleValueType();
10214   int NumElements = VT.getVectorNumElements();
10215   SDLoc dl(Op);
10216
10217   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10218
10219   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10220   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10221   if (V1IsUndef && V2IsUndef)
10222     return DAG.getUNDEF(VT);
10223
10224   // When we create a shuffle node we put the UNDEF node to second operand,
10225   // but in some cases the first operand may be transformed to UNDEF.
10226   // In this case we should just commute the node.
10227   if (V1IsUndef)
10228     return DAG.getCommutedVectorShuffle(*SVOp);
10229
10230   // Check for non-undef masks pointing at an undef vector and make the masks
10231   // undef as well. This makes it easier to match the shuffle based solely on
10232   // the mask.
10233   if (V2IsUndef)
10234     for (int M : Mask)
10235       if (M >= NumElements) {
10236         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10237         for (int &M : NewMask)
10238           if (M >= NumElements)
10239             M = -1;
10240         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10241       }
10242
10243   // We actually see shuffles that are entirely re-arrangements of a set of
10244   // zero inputs. This mostly happens while decomposing complex shuffles into
10245   // simple ones. Directly lower these as a buildvector of zeros.
10246   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10247   if (Zeroable.all())
10248     return getZeroVector(VT, Subtarget, DAG, dl);
10249
10250   // Try to collapse shuffles into using a vector type with fewer elements but
10251   // wider element types. We cap this to not form integers or floating point
10252   // elements wider than 64 bits, but it might be interesting to form i128
10253   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10254   SmallVector<int, 16> WidenedMask;
10255   if (VT.getScalarSizeInBits() < 64 &&
10256       canWidenShuffleElements(Mask, WidenedMask)) {
10257     MVT NewEltVT = VT.isFloatingPoint()
10258                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10259                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10260     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10261     // Make sure that the new vector type is legal. For example, v2f64 isn't
10262     // legal on SSE1.
10263     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10264       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10265       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10266       return DAG.getNode(ISD::BITCAST, dl, VT,
10267                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10268     }
10269   }
10270
10271   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10272   for (int M : SVOp->getMask())
10273     if (M < 0)
10274       ++NumUndefElements;
10275     else if (M < NumElements)
10276       ++NumV1Elements;
10277     else
10278       ++NumV2Elements;
10279
10280   // Commute the shuffle as needed such that more elements come from V1 than
10281   // V2. This allows us to match the shuffle pattern strictly on how many
10282   // elements come from V1 without handling the symmetric cases.
10283   if (NumV2Elements > NumV1Elements)
10284     return DAG.getCommutedVectorShuffle(*SVOp);
10285
10286   // When the number of V1 and V2 elements are the same, try to minimize the
10287   // number of uses of V2 in the low half of the vector. When that is tied,
10288   // ensure that the sum of indices for V1 is equal to or lower than the sum
10289   // indices for V2. When those are equal, try to ensure that the number of odd
10290   // indices for V1 is lower than the number of odd indices for V2.
10291   if (NumV1Elements == NumV2Elements) {
10292     int LowV1Elements = 0, LowV2Elements = 0;
10293     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10294       if (M >= NumElements)
10295         ++LowV2Elements;
10296       else if (M >= 0)
10297         ++LowV1Elements;
10298     if (LowV2Elements > LowV1Elements) {
10299       return DAG.getCommutedVectorShuffle(*SVOp);
10300     } else if (LowV2Elements == LowV1Elements) {
10301       int SumV1Indices = 0, SumV2Indices = 0;
10302       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10303         if (SVOp->getMask()[i] >= NumElements)
10304           SumV2Indices += i;
10305         else if (SVOp->getMask()[i] >= 0)
10306           SumV1Indices += i;
10307       if (SumV2Indices < SumV1Indices) {
10308         return DAG.getCommutedVectorShuffle(*SVOp);
10309       } else if (SumV2Indices == SumV1Indices) {
10310         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10311         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10312           if (SVOp->getMask()[i] >= NumElements)
10313             NumV2OddIndices += i % 2;
10314           else if (SVOp->getMask()[i] >= 0)
10315             NumV1OddIndices += i % 2;
10316         if (NumV2OddIndices < NumV1OddIndices)
10317           return DAG.getCommutedVectorShuffle(*SVOp);
10318       }
10319     }
10320   }
10321
10322   // For each vector width, delegate to a specialized lowering routine.
10323   if (VT.getSizeInBits() == 128)
10324     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10325
10326   if (VT.getSizeInBits() == 256)
10327     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10328
10329   // Force AVX-512 vectors to be scalarized for now.
10330   // FIXME: Implement AVX-512 support!
10331   if (VT.getSizeInBits() == 512)
10332     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10333
10334   llvm_unreachable("Unimplemented!");
10335 }
10336
10337 // This function assumes its argument is a BUILD_VECTOR of constants or
10338 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10339 // true.
10340 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10341                                     unsigned &MaskValue) {
10342   MaskValue = 0;
10343   unsigned NumElems = BuildVector->getNumOperands();
10344   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10345   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10346   unsigned NumElemsInLane = NumElems / NumLanes;
10347
10348   // Blend for v16i16 should be symetric for the both lanes.
10349   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10350     SDValue EltCond = BuildVector->getOperand(i);
10351     SDValue SndLaneEltCond =
10352         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10353
10354     int Lane1Cond = -1, Lane2Cond = -1;
10355     if (isa<ConstantSDNode>(EltCond))
10356       Lane1Cond = !isZero(EltCond);
10357     if (isa<ConstantSDNode>(SndLaneEltCond))
10358       Lane2Cond = !isZero(SndLaneEltCond);
10359
10360     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10361       // Lane1Cond != 0, means we want the first argument.
10362       // Lane1Cond == 0, means we want the second argument.
10363       // The encoding of this argument is 0 for the first argument, 1
10364       // for the second. Therefore, invert the condition.
10365       MaskValue |= !Lane1Cond << i;
10366     else if (Lane1Cond < 0)
10367       MaskValue |= !Lane2Cond << i;
10368     else
10369       return false;
10370   }
10371   return true;
10372 }
10373
10374 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10375 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10376                                            const X86Subtarget *Subtarget,
10377                                            SelectionDAG &DAG) {
10378   SDValue Cond = Op.getOperand(0);
10379   SDValue LHS = Op.getOperand(1);
10380   SDValue RHS = Op.getOperand(2);
10381   SDLoc dl(Op);
10382   MVT VT = Op.getSimpleValueType();
10383
10384   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10385     return SDValue();
10386   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10387
10388   // Only non-legal VSELECTs reach this lowering, convert those into generic
10389   // shuffles and re-use the shuffle lowering path for blends.
10390   SmallVector<int, 32> Mask;
10391   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10392     SDValue CondElt = CondBV->getOperand(i);
10393     Mask.push_back(
10394         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10395   }
10396   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10397 }
10398
10399 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10400   // A vselect where all conditions and data are constants can be optimized into
10401   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10402   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10403       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10404       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10405     return SDValue();
10406
10407   // Try to lower this to a blend-style vector shuffle. This can handle all
10408   // constant condition cases.
10409   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10410     return BlendOp;
10411
10412   // Variable blends are only legal from SSE4.1 onward.
10413   if (!Subtarget->hasSSE41())
10414     return SDValue();
10415
10416   // Only some types will be legal on some subtargets. If we can emit a legal
10417   // VSELECT-matching blend, return Op, and but if we need to expand, return
10418   // a null value.
10419   switch (Op.getSimpleValueType().SimpleTy) {
10420   default:
10421     // Most of the vector types have blends past SSE4.1.
10422     return Op;
10423
10424   case MVT::v32i8:
10425     // The byte blends for AVX vectors were introduced only in AVX2.
10426     if (Subtarget->hasAVX2())
10427       return Op;
10428
10429     return SDValue();
10430
10431   case MVT::v8i16:
10432   case MVT::v16i16:
10433     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10434     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10435       return Op;
10436
10437     // FIXME: We should custom lower this by fixing the condition and using i8
10438     // blends.
10439     return SDValue();
10440   }
10441 }
10442
10443 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10444   MVT VT = Op.getSimpleValueType();
10445   SDLoc dl(Op);
10446
10447   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10448     return SDValue();
10449
10450   if (VT.getSizeInBits() == 8) {
10451     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10452                                   Op.getOperand(0), Op.getOperand(1));
10453     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10454                                   DAG.getValueType(VT));
10455     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10456   }
10457
10458   if (VT.getSizeInBits() == 16) {
10459     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10460     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10461     if (Idx == 0)
10462       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10463                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10464                                      DAG.getNode(ISD::BITCAST, dl,
10465                                                  MVT::v4i32,
10466                                                  Op.getOperand(0)),
10467                                      Op.getOperand(1)));
10468     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10469                                   Op.getOperand(0), Op.getOperand(1));
10470     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10471                                   DAG.getValueType(VT));
10472     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10473   }
10474
10475   if (VT == MVT::f32) {
10476     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10477     // the result back to FR32 register. It's only worth matching if the
10478     // result has a single use which is a store or a bitcast to i32.  And in
10479     // the case of a store, it's not worth it if the index is a constant 0,
10480     // because a MOVSSmr can be used instead, which is smaller and faster.
10481     if (!Op.hasOneUse())
10482       return SDValue();
10483     SDNode *User = *Op.getNode()->use_begin();
10484     if ((User->getOpcode() != ISD::STORE ||
10485          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10486           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10487         (User->getOpcode() != ISD::BITCAST ||
10488          User->getValueType(0) != MVT::i32))
10489       return SDValue();
10490     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10491                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10492                                               Op.getOperand(0)),
10493                                               Op.getOperand(1));
10494     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10495   }
10496
10497   if (VT == MVT::i32 || VT == MVT::i64) {
10498     // ExtractPS/pextrq works with constant index.
10499     if (isa<ConstantSDNode>(Op.getOperand(1)))
10500       return Op;
10501   }
10502   return SDValue();
10503 }
10504
10505 /// Extract one bit from mask vector, like v16i1 or v8i1.
10506 /// AVX-512 feature.
10507 SDValue
10508 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10509   SDValue Vec = Op.getOperand(0);
10510   SDLoc dl(Vec);
10511   MVT VecVT = Vec.getSimpleValueType();
10512   SDValue Idx = Op.getOperand(1);
10513   MVT EltVT = Op.getSimpleValueType();
10514
10515   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10516   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10517          "Unexpected vector type in ExtractBitFromMaskVector");
10518
10519   // variable index can't be handled in mask registers,
10520   // extend vector to VR512
10521   if (!isa<ConstantSDNode>(Idx)) {
10522     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10523     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10524     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10525                               ExtVT.getVectorElementType(), Ext, Idx);
10526     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10527   }
10528
10529   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10530   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10531   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10532     rc = getRegClassFor(MVT::v16i1);
10533   unsigned MaxSift = rc->getSize()*8 - 1;
10534   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10535                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10536   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10537                     DAG.getConstant(MaxSift, dl, MVT::i8));
10538   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10539                        DAG.getIntPtrConstant(0, dl));
10540 }
10541
10542 SDValue
10543 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10544                                            SelectionDAG &DAG) const {
10545   SDLoc dl(Op);
10546   SDValue Vec = Op.getOperand(0);
10547   MVT VecVT = Vec.getSimpleValueType();
10548   SDValue Idx = Op.getOperand(1);
10549
10550   if (Op.getSimpleValueType() == MVT::i1)
10551     return ExtractBitFromMaskVector(Op, DAG);
10552
10553   if (!isa<ConstantSDNode>(Idx)) {
10554     if (VecVT.is512BitVector() ||
10555         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10556          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10557
10558       MVT MaskEltVT =
10559         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10560       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10561                                     MaskEltVT.getSizeInBits());
10562
10563       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10564       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10565                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10566                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10567       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10568       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10569                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10570     }
10571     return SDValue();
10572   }
10573
10574   // If this is a 256-bit vector result, first extract the 128-bit vector and
10575   // then extract the element from the 128-bit vector.
10576   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10577
10578     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10579     // Get the 128-bit vector.
10580     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10581     MVT EltVT = VecVT.getVectorElementType();
10582
10583     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10584
10585     //if (IdxVal >= NumElems/2)
10586     //  IdxVal -= NumElems/2;
10587     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10588     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10589                        DAG.getConstant(IdxVal, dl, MVT::i32));
10590   }
10591
10592   assert(VecVT.is128BitVector() && "Unexpected vector length");
10593
10594   if (Subtarget->hasSSE41()) {
10595     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10596     if (Res.getNode())
10597       return Res;
10598   }
10599
10600   MVT VT = Op.getSimpleValueType();
10601   // TODO: handle v16i8.
10602   if (VT.getSizeInBits() == 16) {
10603     SDValue Vec = Op.getOperand(0);
10604     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10605     if (Idx == 0)
10606       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10607                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10608                                      DAG.getNode(ISD::BITCAST, dl,
10609                                                  MVT::v4i32, Vec),
10610                                      Op.getOperand(1)));
10611     // Transform it so it match pextrw which produces a 32-bit result.
10612     MVT EltVT = MVT::i32;
10613     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10614                                   Op.getOperand(0), Op.getOperand(1));
10615     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10616                                   DAG.getValueType(VT));
10617     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10618   }
10619
10620   if (VT.getSizeInBits() == 32) {
10621     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10622     if (Idx == 0)
10623       return Op;
10624
10625     // SHUFPS the element to the lowest double word, then movss.
10626     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10627     MVT VVT = Op.getOperand(0).getSimpleValueType();
10628     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10629                                        DAG.getUNDEF(VVT), Mask);
10630     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10631                        DAG.getIntPtrConstant(0, dl));
10632   }
10633
10634   if (VT.getSizeInBits() == 64) {
10635     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10636     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10637     //        to match extract_elt for f64.
10638     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10639     if (Idx == 0)
10640       return Op;
10641
10642     // UNPCKHPD the element to the lowest double word, then movsd.
10643     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10644     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10645     int Mask[2] = { 1, -1 };
10646     MVT VVT = Op.getOperand(0).getSimpleValueType();
10647     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10648                                        DAG.getUNDEF(VVT), Mask);
10649     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10650                        DAG.getIntPtrConstant(0, dl));
10651   }
10652
10653   return SDValue();
10654 }
10655
10656 /// Insert one bit to mask vector, like v16i1 or v8i1.
10657 /// AVX-512 feature.
10658 SDValue
10659 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10660   SDLoc dl(Op);
10661   SDValue Vec = Op.getOperand(0);
10662   SDValue Elt = Op.getOperand(1);
10663   SDValue Idx = Op.getOperand(2);
10664   MVT VecVT = Vec.getSimpleValueType();
10665
10666   if (!isa<ConstantSDNode>(Idx)) {
10667     // Non constant index. Extend source and destination,
10668     // insert element and then truncate the result.
10669     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10670     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10671     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10672       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10673       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10674     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10675   }
10676
10677   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10678   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10679   if (Vec.getOpcode() == ISD::UNDEF)
10680     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10681                        DAG.getConstant(IdxVal, dl, MVT::i8));
10682   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10683   unsigned MaxSift = rc->getSize()*8 - 1;
10684   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10685                     DAG.getConstant(MaxSift, dl, MVT::i8));
10686   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10687                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10688   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10689 }
10690
10691 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10692                                                   SelectionDAG &DAG) const {
10693   MVT VT = Op.getSimpleValueType();
10694   MVT EltVT = VT.getVectorElementType();
10695
10696   if (EltVT == MVT::i1)
10697     return InsertBitToMaskVector(Op, DAG);
10698
10699   SDLoc dl(Op);
10700   SDValue N0 = Op.getOperand(0);
10701   SDValue N1 = Op.getOperand(1);
10702   SDValue N2 = Op.getOperand(2);
10703   if (!isa<ConstantSDNode>(N2))
10704     return SDValue();
10705   auto *N2C = cast<ConstantSDNode>(N2);
10706   unsigned IdxVal = N2C->getZExtValue();
10707
10708   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10709   // into that, and then insert the subvector back into the result.
10710   if (VT.is256BitVector() || VT.is512BitVector()) {
10711     // With a 256-bit vector, we can insert into the zero element efficiently
10712     // using a blend if we have AVX or AVX2 and the right data type.
10713     if (VT.is256BitVector() && IdxVal == 0) {
10714       // TODO: It is worthwhile to cast integer to floating point and back
10715       // and incur a domain crossing penalty if that's what we'll end up
10716       // doing anyway after extracting to a 128-bit vector.
10717       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10718           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10719         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10720         N2 = DAG.getIntPtrConstant(1, dl);
10721         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10722       }
10723     }
10724
10725     // Get the desired 128-bit vector chunk.
10726     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10727
10728     // Insert the element into the desired chunk.
10729     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10730     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10731
10732     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10733                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10734
10735     // Insert the changed part back into the bigger vector
10736     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10737   }
10738   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10739
10740   if (Subtarget->hasSSE41()) {
10741     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10742       unsigned Opc;
10743       if (VT == MVT::v8i16) {
10744         Opc = X86ISD::PINSRW;
10745       } else {
10746         assert(VT == MVT::v16i8);
10747         Opc = X86ISD::PINSRB;
10748       }
10749
10750       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10751       // argument.
10752       if (N1.getValueType() != MVT::i32)
10753         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10754       if (N2.getValueType() != MVT::i32)
10755         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10756       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10757     }
10758
10759     if (EltVT == MVT::f32) {
10760       // Bits [7:6] of the constant are the source select. This will always be
10761       //   zero here. The DAG Combiner may combine an extract_elt index into
10762       //   these bits. For example (insert (extract, 3), 2) could be matched by
10763       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10764       // Bits [5:4] of the constant are the destination select. This is the
10765       //   value of the incoming immediate.
10766       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10767       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10768
10769       const Function *F = DAG.getMachineFunction().getFunction();
10770       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10771       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10772         // If this is an insertion of 32-bits into the low 32-bits of
10773         // a vector, we prefer to generate a blend with immediate rather
10774         // than an insertps. Blends are simpler operations in hardware and so
10775         // will always have equal or better performance than insertps.
10776         // But if optimizing for size and there's a load folding opportunity,
10777         // generate insertps because blendps does not have a 32-bit memory
10778         // operand form.
10779         N2 = DAG.getIntPtrConstant(1, dl);
10780         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10781         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10782       }
10783       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10784       // Create this as a scalar to vector..
10785       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10786       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10787     }
10788
10789     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10790       // PINSR* works with constant index.
10791       return Op;
10792     }
10793   }
10794
10795   if (EltVT == MVT::i8)
10796     return SDValue();
10797
10798   if (EltVT.getSizeInBits() == 16) {
10799     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10800     // as its second argument.
10801     if (N1.getValueType() != MVT::i32)
10802       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10803     if (N2.getValueType() != MVT::i32)
10804       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10805     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10806   }
10807   return SDValue();
10808 }
10809
10810 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10811   SDLoc dl(Op);
10812   MVT OpVT = Op.getSimpleValueType();
10813
10814   // If this is a 256-bit vector result, first insert into a 128-bit
10815   // vector and then insert into the 256-bit vector.
10816   if (!OpVT.is128BitVector()) {
10817     // Insert into a 128-bit vector.
10818     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10819     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10820                                  OpVT.getVectorNumElements() / SizeFactor);
10821
10822     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10823
10824     // Insert the 128-bit vector.
10825     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10826   }
10827
10828   if (OpVT == MVT::v1i64 &&
10829       Op.getOperand(0).getValueType() == MVT::i64)
10830     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10831
10832   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10833   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10834   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10835                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10836 }
10837
10838 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10839 // a simple subregister reference or explicit instructions to grab
10840 // upper bits of a vector.
10841 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10842                                       SelectionDAG &DAG) {
10843   SDLoc dl(Op);
10844   SDValue In =  Op.getOperand(0);
10845   SDValue Idx = Op.getOperand(1);
10846   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10847   MVT ResVT   = Op.getSimpleValueType();
10848   MVT InVT    = In.getSimpleValueType();
10849
10850   if (Subtarget->hasFp256()) {
10851     if (ResVT.is128BitVector() &&
10852         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10853         isa<ConstantSDNode>(Idx)) {
10854       return Extract128BitVector(In, IdxVal, DAG, dl);
10855     }
10856     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10857         isa<ConstantSDNode>(Idx)) {
10858       return Extract256BitVector(In, IdxVal, DAG, dl);
10859     }
10860   }
10861   return SDValue();
10862 }
10863
10864 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10865 // simple superregister reference or explicit instructions to insert
10866 // the upper bits of a vector.
10867 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10868                                      SelectionDAG &DAG) {
10869   if (!Subtarget->hasAVX())
10870     return SDValue();
10871
10872   SDLoc dl(Op);
10873   SDValue Vec = Op.getOperand(0);
10874   SDValue SubVec = Op.getOperand(1);
10875   SDValue Idx = Op.getOperand(2);
10876
10877   if (!isa<ConstantSDNode>(Idx))
10878     return SDValue();
10879
10880   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10881   MVT OpVT = Op.getSimpleValueType();
10882   MVT SubVecVT = SubVec.getSimpleValueType();
10883
10884   // Fold two 16-byte subvector loads into one 32-byte load:
10885   // (insert_subvector (insert_subvector undef, (load addr), 0),
10886   //                   (load addr + 16), Elts/2)
10887   // --> load32 addr
10888   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10889       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10890       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10891       !Subtarget->isUnalignedMem32Slow()) {
10892     SDValue SubVec2 = Vec.getOperand(1);
10893     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10894       if (Idx2->getZExtValue() == 0) {
10895         SDValue Ops[] = { SubVec2, SubVec };
10896         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10897         if (LD.getNode())
10898           return LD;
10899       }
10900     }
10901   }
10902
10903   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10904       SubVecVT.is128BitVector())
10905     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10906
10907   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10908     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10909
10910   if (OpVT.getVectorElementType() == MVT::i1) {
10911     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10912       return Op;
10913     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10914     SDValue Undef = DAG.getUNDEF(OpVT);
10915     unsigned NumElems = OpVT.getVectorNumElements();
10916     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10917
10918     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10919       // Zero upper bits of the Vec
10920       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10921       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10922
10923       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10924                                  SubVec, ZeroIdx);
10925       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10926       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10927     }
10928     if (IdxVal == 0) {
10929       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10930                                  SubVec, ZeroIdx);
10931       // Zero upper bits of the Vec2
10932       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10933       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10934       // Zero lower bits of the Vec
10935       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10936       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10937       // Merge them together
10938       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10939     }
10940   }
10941   return SDValue();
10942 }
10943
10944 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10945 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10946 // one of the above mentioned nodes. It has to be wrapped because otherwise
10947 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10948 // be used to form addressing mode. These wrapped nodes will be selected
10949 // into MOV32ri.
10950 SDValue
10951 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10952   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10953
10954   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10955   // global base reg.
10956   unsigned char OpFlag = 0;
10957   unsigned WrapperKind = X86ISD::Wrapper;
10958   CodeModel::Model M = DAG.getTarget().getCodeModel();
10959
10960   if (Subtarget->isPICStyleRIPRel() &&
10961       (M == CodeModel::Small || M == CodeModel::Kernel))
10962     WrapperKind = X86ISD::WrapperRIP;
10963   else if (Subtarget->isPICStyleGOT())
10964     OpFlag = X86II::MO_GOTOFF;
10965   else if (Subtarget->isPICStyleStubPIC())
10966     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10967
10968   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10969                                              CP->getAlignment(),
10970                                              CP->getOffset(), OpFlag);
10971   SDLoc DL(CP);
10972   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10973   // With PIC, the address is actually $g + Offset.
10974   if (OpFlag) {
10975     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10976                          DAG.getNode(X86ISD::GlobalBaseReg,
10977                                      SDLoc(), getPointerTy()),
10978                          Result);
10979   }
10980
10981   return Result;
10982 }
10983
10984 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10985   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10986
10987   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10988   // global base reg.
10989   unsigned char OpFlag = 0;
10990   unsigned WrapperKind = X86ISD::Wrapper;
10991   CodeModel::Model M = DAG.getTarget().getCodeModel();
10992
10993   if (Subtarget->isPICStyleRIPRel() &&
10994       (M == CodeModel::Small || M == CodeModel::Kernel))
10995     WrapperKind = X86ISD::WrapperRIP;
10996   else if (Subtarget->isPICStyleGOT())
10997     OpFlag = X86II::MO_GOTOFF;
10998   else if (Subtarget->isPICStyleStubPIC())
10999     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11000
11001   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11002                                           OpFlag);
11003   SDLoc DL(JT);
11004   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11005
11006   // With PIC, the address is actually $g + Offset.
11007   if (OpFlag)
11008     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11009                          DAG.getNode(X86ISD::GlobalBaseReg,
11010                                      SDLoc(), getPointerTy()),
11011                          Result);
11012
11013   return Result;
11014 }
11015
11016 SDValue
11017 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11018   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11019
11020   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11021   // global base reg.
11022   unsigned char OpFlag = 0;
11023   unsigned WrapperKind = X86ISD::Wrapper;
11024   CodeModel::Model M = DAG.getTarget().getCodeModel();
11025
11026   if (Subtarget->isPICStyleRIPRel() &&
11027       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11028     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11029       OpFlag = X86II::MO_GOTPCREL;
11030     WrapperKind = X86ISD::WrapperRIP;
11031   } else if (Subtarget->isPICStyleGOT()) {
11032     OpFlag = X86II::MO_GOT;
11033   } else if (Subtarget->isPICStyleStubPIC()) {
11034     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11035   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11036     OpFlag = X86II::MO_DARWIN_NONLAZY;
11037   }
11038
11039   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11040
11041   SDLoc DL(Op);
11042   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11043
11044   // With PIC, the address is actually $g + Offset.
11045   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11046       !Subtarget->is64Bit()) {
11047     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11048                          DAG.getNode(X86ISD::GlobalBaseReg,
11049                                      SDLoc(), getPointerTy()),
11050                          Result);
11051   }
11052
11053   // For symbols that require a load from a stub to get the address, emit the
11054   // load.
11055   if (isGlobalStubReference(OpFlag))
11056     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11057                          MachinePointerInfo::getGOT(), false, false, false, 0);
11058
11059   return Result;
11060 }
11061
11062 SDValue
11063 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11064   // Create the TargetBlockAddressAddress node.
11065   unsigned char OpFlags =
11066     Subtarget->ClassifyBlockAddressReference();
11067   CodeModel::Model M = DAG.getTarget().getCodeModel();
11068   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11069   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11070   SDLoc dl(Op);
11071   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11072                                              OpFlags);
11073
11074   if (Subtarget->isPICStyleRIPRel() &&
11075       (M == CodeModel::Small || M == CodeModel::Kernel))
11076     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11077   else
11078     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11079
11080   // With PIC, the address is actually $g + Offset.
11081   if (isGlobalRelativeToPICBase(OpFlags)) {
11082     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11083                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11084                          Result);
11085   }
11086
11087   return Result;
11088 }
11089
11090 SDValue
11091 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11092                                       int64_t Offset, SelectionDAG &DAG) const {
11093   // Create the TargetGlobalAddress node, folding in the constant
11094   // offset if it is legal.
11095   unsigned char OpFlags =
11096       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11097   CodeModel::Model M = DAG.getTarget().getCodeModel();
11098   SDValue Result;
11099   if (OpFlags == X86II::MO_NO_FLAG &&
11100       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11101     // A direct static reference to a global.
11102     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11103     Offset = 0;
11104   } else {
11105     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11106   }
11107
11108   if (Subtarget->isPICStyleRIPRel() &&
11109       (M == CodeModel::Small || M == CodeModel::Kernel))
11110     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11111   else
11112     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11113
11114   // With PIC, the address is actually $g + Offset.
11115   if (isGlobalRelativeToPICBase(OpFlags)) {
11116     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11117                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11118                          Result);
11119   }
11120
11121   // For globals that require a load from a stub to get the address, emit the
11122   // load.
11123   if (isGlobalStubReference(OpFlags))
11124     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11125                          MachinePointerInfo::getGOT(), false, false, false, 0);
11126
11127   // If there was a non-zero offset that we didn't fold, create an explicit
11128   // addition for it.
11129   if (Offset != 0)
11130     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11131                          DAG.getConstant(Offset, dl, getPointerTy()));
11132
11133   return Result;
11134 }
11135
11136 SDValue
11137 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11138   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11139   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11140   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11141 }
11142
11143 static SDValue
11144 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11145            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11146            unsigned char OperandFlags, bool LocalDynamic = false) {
11147   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11148   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11149   SDLoc dl(GA);
11150   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11151                                            GA->getValueType(0),
11152                                            GA->getOffset(),
11153                                            OperandFlags);
11154
11155   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11156                                            : X86ISD::TLSADDR;
11157
11158   if (InFlag) {
11159     SDValue Ops[] = { Chain,  TGA, *InFlag };
11160     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11161   } else {
11162     SDValue Ops[]  = { Chain, TGA };
11163     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11164   }
11165
11166   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11167   MFI->setAdjustsStack(true);
11168   MFI->setHasCalls(true);
11169
11170   SDValue Flag = Chain.getValue(1);
11171   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11172 }
11173
11174 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11175 static SDValue
11176 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11177                                 const EVT PtrVT) {
11178   SDValue InFlag;
11179   SDLoc dl(GA);  // ? function entry point might be better
11180   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11181                                    DAG.getNode(X86ISD::GlobalBaseReg,
11182                                                SDLoc(), PtrVT), InFlag);
11183   InFlag = Chain.getValue(1);
11184
11185   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11186 }
11187
11188 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11189 static SDValue
11190 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11191                                 const EVT PtrVT) {
11192   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11193                     X86::RAX, X86II::MO_TLSGD);
11194 }
11195
11196 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11197                                            SelectionDAG &DAG,
11198                                            const EVT PtrVT,
11199                                            bool is64Bit) {
11200   SDLoc dl(GA);
11201
11202   // Get the start address of the TLS block for this module.
11203   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11204       .getInfo<X86MachineFunctionInfo>();
11205   MFI->incNumLocalDynamicTLSAccesses();
11206
11207   SDValue Base;
11208   if (is64Bit) {
11209     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11210                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11211   } else {
11212     SDValue InFlag;
11213     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11214         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11215     InFlag = Chain.getValue(1);
11216     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11217                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11218   }
11219
11220   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11221   // of Base.
11222
11223   // Build x@dtpoff.
11224   unsigned char OperandFlags = X86II::MO_DTPOFF;
11225   unsigned WrapperKind = X86ISD::Wrapper;
11226   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11227                                            GA->getValueType(0),
11228                                            GA->getOffset(), OperandFlags);
11229   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11230
11231   // Add x@dtpoff with the base.
11232   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11233 }
11234
11235 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11236 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11237                                    const EVT PtrVT, TLSModel::Model model,
11238                                    bool is64Bit, bool isPIC) {
11239   SDLoc dl(GA);
11240
11241   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11242   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11243                                                          is64Bit ? 257 : 256));
11244
11245   SDValue ThreadPointer =
11246       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11247                   MachinePointerInfo(Ptr), false, false, false, 0);
11248
11249   unsigned char OperandFlags = 0;
11250   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11251   // initialexec.
11252   unsigned WrapperKind = X86ISD::Wrapper;
11253   if (model == TLSModel::LocalExec) {
11254     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11255   } else if (model == TLSModel::InitialExec) {
11256     if (is64Bit) {
11257       OperandFlags = X86II::MO_GOTTPOFF;
11258       WrapperKind = X86ISD::WrapperRIP;
11259     } else {
11260       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11261     }
11262   } else {
11263     llvm_unreachable("Unexpected model");
11264   }
11265
11266   // emit "addl x@ntpoff,%eax" (local exec)
11267   // or "addl x@indntpoff,%eax" (initial exec)
11268   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11269   SDValue TGA =
11270       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11271                                  GA->getOffset(), OperandFlags);
11272   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11273
11274   if (model == TLSModel::InitialExec) {
11275     if (isPIC && !is64Bit) {
11276       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11277                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11278                            Offset);
11279     }
11280
11281     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11282                          MachinePointerInfo::getGOT(), false, false, false, 0);
11283   }
11284
11285   // The address of the thread local variable is the add of the thread
11286   // pointer with the offset of the variable.
11287   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11288 }
11289
11290 SDValue
11291 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11292
11293   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11294   const GlobalValue *GV = GA->getGlobal();
11295
11296   if (Subtarget->isTargetELF()) {
11297     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11298
11299     switch (model) {
11300       case TLSModel::GeneralDynamic:
11301         if (Subtarget->is64Bit())
11302           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11303         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11304       case TLSModel::LocalDynamic:
11305         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11306                                            Subtarget->is64Bit());
11307       case TLSModel::InitialExec:
11308       case TLSModel::LocalExec:
11309         return LowerToTLSExecModel(
11310             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11311             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11312     }
11313     llvm_unreachable("Unknown TLS model.");
11314   }
11315
11316   if (Subtarget->isTargetDarwin()) {
11317     // Darwin only has one model of TLS.  Lower to that.
11318     unsigned char OpFlag = 0;
11319     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11320                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11321
11322     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11323     // global base reg.
11324     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11325                  !Subtarget->is64Bit();
11326     if (PIC32)
11327       OpFlag = X86II::MO_TLVP_PIC_BASE;
11328     else
11329       OpFlag = X86II::MO_TLVP;
11330     SDLoc DL(Op);
11331     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11332                                                 GA->getValueType(0),
11333                                                 GA->getOffset(), OpFlag);
11334     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11335
11336     // With PIC32, the address is actually $g + Offset.
11337     if (PIC32)
11338       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11339                            DAG.getNode(X86ISD::GlobalBaseReg,
11340                                        SDLoc(), getPointerTy()),
11341                            Offset);
11342
11343     // Lowering the machine isd will make sure everything is in the right
11344     // location.
11345     SDValue Chain = DAG.getEntryNode();
11346     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11347     SDValue Args[] = { Chain, Offset };
11348     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11349
11350     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11351     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11352     MFI->setAdjustsStack(true);
11353
11354     // And our return value (tls address) is in the standard call return value
11355     // location.
11356     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11357     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11358                               Chain.getValue(1));
11359   }
11360
11361   if (Subtarget->isTargetKnownWindowsMSVC() ||
11362       Subtarget->isTargetWindowsGNU()) {
11363     // Just use the implicit TLS architecture
11364     // Need to generate someting similar to:
11365     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11366     //                                  ; from TEB
11367     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11368     //   mov     rcx, qword [rdx+rcx*8]
11369     //   mov     eax, .tls$:tlsvar
11370     //   [rax+rcx] contains the address
11371     // Windows 64bit: gs:0x58
11372     // Windows 32bit: fs:__tls_array
11373
11374     SDLoc dl(GA);
11375     SDValue Chain = DAG.getEntryNode();
11376
11377     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11378     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11379     // use its literal value of 0x2C.
11380     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11381                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11382                                                              256)
11383                                         : Type::getInt32PtrTy(*DAG.getContext(),
11384                                                               257));
11385
11386     SDValue TlsArray =
11387         Subtarget->is64Bit()
11388             ? DAG.getIntPtrConstant(0x58, dl)
11389             : (Subtarget->isTargetWindowsGNU()
11390                    ? DAG.getIntPtrConstant(0x2C, dl)
11391                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11392
11393     SDValue ThreadPointer =
11394         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11395                     MachinePointerInfo(Ptr), false, false, false, 0);
11396
11397     // Load the _tls_index variable
11398     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11399     if (Subtarget->is64Bit())
11400       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11401                            IDX, MachinePointerInfo(), MVT::i32,
11402                            false, false, false, 0);
11403     else
11404       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11405                         false, false, false, 0);
11406
11407     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11408                                     getPointerTy());
11409     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11410
11411     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11412     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11413                       false, false, false, 0);
11414
11415     // Get the offset of start of .tls section
11416     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11417                                              GA->getValueType(0),
11418                                              GA->getOffset(), X86II::MO_SECREL);
11419     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11420
11421     // The address of the thread local variable is the add of the thread
11422     // pointer with the offset of the variable.
11423     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11424   }
11425
11426   llvm_unreachable("TLS not implemented for this target.");
11427 }
11428
11429 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11430 /// and take a 2 x i32 value to shift plus a shift amount.
11431 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11432   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11433   MVT VT = Op.getSimpleValueType();
11434   unsigned VTBits = VT.getSizeInBits();
11435   SDLoc dl(Op);
11436   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11437   SDValue ShOpLo = Op.getOperand(0);
11438   SDValue ShOpHi = Op.getOperand(1);
11439   SDValue ShAmt  = Op.getOperand(2);
11440   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11441   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11442   // during isel.
11443   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11444                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11445   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11446                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11447                        : DAG.getConstant(0, dl, VT);
11448
11449   SDValue Tmp2, Tmp3;
11450   if (Op.getOpcode() == ISD::SHL_PARTS) {
11451     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11452     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11453   } else {
11454     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11455     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11456   }
11457
11458   // If the shift amount is larger or equal than the width of a part we can't
11459   // rely on the results of shld/shrd. Insert a test and select the appropriate
11460   // values for large shift amounts.
11461   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11462                                 DAG.getConstant(VTBits, dl, MVT::i8));
11463   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11464                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11465
11466   SDValue Hi, Lo;
11467   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11468   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11469   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11470
11471   if (Op.getOpcode() == ISD::SHL_PARTS) {
11472     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11473     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11474   } else {
11475     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11476     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11477   }
11478
11479   SDValue Ops[2] = { Lo, Hi };
11480   return DAG.getMergeValues(Ops, dl);
11481 }
11482
11483 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11484                                            SelectionDAG &DAG) const {
11485   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11486   SDLoc dl(Op);
11487
11488   if (SrcVT.isVector()) {
11489     if (SrcVT.getVectorElementType() == MVT::i1) {
11490       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11491       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11492                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11493                                      Op.getOperand(0)));
11494     }
11495     return SDValue();
11496   }
11497
11498   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11499          "Unknown SINT_TO_FP to lower!");
11500
11501   // These are really Legal; return the operand so the caller accepts it as
11502   // Legal.
11503   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11504     return Op;
11505   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11506       Subtarget->is64Bit()) {
11507     return Op;
11508   }
11509
11510   unsigned Size = SrcVT.getSizeInBits()/8;
11511   MachineFunction &MF = DAG.getMachineFunction();
11512   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11513   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11514   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11515                                StackSlot,
11516                                MachinePointerInfo::getFixedStack(SSFI),
11517                                false, false, 0);
11518   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11519 }
11520
11521 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11522                                      SDValue StackSlot,
11523                                      SelectionDAG &DAG) const {
11524   // Build the FILD
11525   SDLoc DL(Op);
11526   SDVTList Tys;
11527   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11528   if (useSSE)
11529     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11530   else
11531     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11532
11533   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11534
11535   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11536   MachineMemOperand *MMO;
11537   if (FI) {
11538     int SSFI = FI->getIndex();
11539     MMO =
11540       DAG.getMachineFunction()
11541       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11542                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11543   } else {
11544     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11545     StackSlot = StackSlot.getOperand(1);
11546   }
11547   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11548   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11549                                            X86ISD::FILD, DL,
11550                                            Tys, Ops, SrcVT, MMO);
11551
11552   if (useSSE) {
11553     Chain = Result.getValue(1);
11554     SDValue InFlag = Result.getValue(2);
11555
11556     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11557     // shouldn't be necessary except that RFP cannot be live across
11558     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11559     MachineFunction &MF = DAG.getMachineFunction();
11560     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11561     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11562     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11563     Tys = DAG.getVTList(MVT::Other);
11564     SDValue Ops[] = {
11565       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11566     };
11567     MachineMemOperand *MMO =
11568       DAG.getMachineFunction()
11569       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11570                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11571
11572     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11573                                     Ops, Op.getValueType(), MMO);
11574     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11575                          MachinePointerInfo::getFixedStack(SSFI),
11576                          false, false, false, 0);
11577   }
11578
11579   return Result;
11580 }
11581
11582 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11583 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11584                                                SelectionDAG &DAG) const {
11585   // This algorithm is not obvious. Here it is what we're trying to output:
11586   /*
11587      movq       %rax,  %xmm0
11588      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11589      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11590      #ifdef __SSE3__
11591        haddpd   %xmm0, %xmm0
11592      #else
11593        pshufd   $0x4e, %xmm0, %xmm1
11594        addpd    %xmm1, %xmm0
11595      #endif
11596   */
11597
11598   SDLoc dl(Op);
11599   LLVMContext *Context = DAG.getContext();
11600
11601   // Build some magic constants.
11602   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11603   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11604   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11605
11606   SmallVector<Constant*,2> CV1;
11607   CV1.push_back(
11608     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11609                                       APInt(64, 0x4330000000000000ULL))));
11610   CV1.push_back(
11611     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11612                                       APInt(64, 0x4530000000000000ULL))));
11613   Constant *C1 = ConstantVector::get(CV1);
11614   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11615
11616   // Load the 64-bit value into an XMM register.
11617   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11618                             Op.getOperand(0));
11619   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11620                               MachinePointerInfo::getConstantPool(),
11621                               false, false, false, 16);
11622   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11623                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11624                               CLod0);
11625
11626   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11627                               MachinePointerInfo::getConstantPool(),
11628                               false, false, false, 16);
11629   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11630   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11631   SDValue Result;
11632
11633   if (Subtarget->hasSSE3()) {
11634     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11635     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11636   } else {
11637     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11638     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11639                                            S2F, 0x4E, DAG);
11640     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11641                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11642                          Sub);
11643   }
11644
11645   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11646                      DAG.getIntPtrConstant(0, dl));
11647 }
11648
11649 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11650 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11651                                                SelectionDAG &DAG) const {
11652   SDLoc dl(Op);
11653   // FP constant to bias correct the final result.
11654   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11655                                    MVT::f64);
11656
11657   // Load the 32-bit value into an XMM register.
11658   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11659                              Op.getOperand(0));
11660
11661   // Zero out the upper parts of the register.
11662   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11663
11664   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11665                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11666                      DAG.getIntPtrConstant(0, dl));
11667
11668   // Or the load with the bias.
11669   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11670                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11671                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11672                                                    MVT::v2f64, Load)),
11673                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11674                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11675                                                    MVT::v2f64, Bias)));
11676   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11677                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11678                    DAG.getIntPtrConstant(0, dl));
11679
11680   // Subtract the bias.
11681   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11682
11683   // Handle final rounding.
11684   EVT DestVT = Op.getValueType();
11685
11686   if (DestVT.bitsLT(MVT::f64))
11687     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11688                        DAG.getIntPtrConstant(0, dl));
11689   if (DestVT.bitsGT(MVT::f64))
11690     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11691
11692   // Handle final rounding.
11693   return Sub;
11694 }
11695
11696 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11697                                      const X86Subtarget &Subtarget) {
11698   // The algorithm is the following:
11699   // #ifdef __SSE4_1__
11700   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11701   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11702   //                                 (uint4) 0x53000000, 0xaa);
11703   // #else
11704   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11705   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11706   // #endif
11707   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11708   //     return (float4) lo + fhi;
11709
11710   SDLoc DL(Op);
11711   SDValue V = Op->getOperand(0);
11712   EVT VecIntVT = V.getValueType();
11713   bool Is128 = VecIntVT == MVT::v4i32;
11714   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11715   // If we convert to something else than the supported type, e.g., to v4f64,
11716   // abort early.
11717   if (VecFloatVT != Op->getValueType(0))
11718     return SDValue();
11719
11720   unsigned NumElts = VecIntVT.getVectorNumElements();
11721   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11722          "Unsupported custom type");
11723   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11724
11725   // In the #idef/#else code, we have in common:
11726   // - The vector of constants:
11727   // -- 0x4b000000
11728   // -- 0x53000000
11729   // - A shift:
11730   // -- v >> 16
11731
11732   // Create the splat vector for 0x4b000000.
11733   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11734   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11735                            CstLow, CstLow, CstLow, CstLow};
11736   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11737                                   makeArrayRef(&CstLowArray[0], NumElts));
11738   // Create the splat vector for 0x53000000.
11739   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11740   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11741                             CstHigh, CstHigh, CstHigh, CstHigh};
11742   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11743                                    makeArrayRef(&CstHighArray[0], NumElts));
11744
11745   // Create the right shift.
11746   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11747   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11748                              CstShift, CstShift, CstShift, CstShift};
11749   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11750                                     makeArrayRef(&CstShiftArray[0], NumElts));
11751   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11752
11753   SDValue Low, High;
11754   if (Subtarget.hasSSE41()) {
11755     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11756     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11757     SDValue VecCstLowBitcast =
11758         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11759     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11760     // Low will be bitcasted right away, so do not bother bitcasting back to its
11761     // original type.
11762     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11763                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11764     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11765     //                                 (uint4) 0x53000000, 0xaa);
11766     SDValue VecCstHighBitcast =
11767         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11768     SDValue VecShiftBitcast =
11769         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11770     // High will be bitcasted right away, so do not bother bitcasting back to
11771     // its original type.
11772     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11773                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11774   } else {
11775     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11776     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11777                                      CstMask, CstMask, CstMask);
11778     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11779     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11780     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11781
11782     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11783     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11784   }
11785
11786   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11787   SDValue CstFAdd = DAG.getConstantFP(
11788       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11789   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11790                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11791   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11792                                    makeArrayRef(&CstFAddArray[0], NumElts));
11793
11794   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11795   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11796   SDValue FHigh =
11797       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11798   //     return (float4) lo + fhi;
11799   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11800   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11801 }
11802
11803 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11804                                                SelectionDAG &DAG) const {
11805   SDValue N0 = Op.getOperand(0);
11806   MVT SVT = N0.getSimpleValueType();
11807   SDLoc dl(Op);
11808
11809   switch (SVT.SimpleTy) {
11810   default:
11811     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11812   case MVT::v4i8:
11813   case MVT::v4i16:
11814   case MVT::v8i8:
11815   case MVT::v8i16: {
11816     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11817     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11818                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11819   }
11820   case MVT::v4i32:
11821   case MVT::v8i32:
11822     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11823   case MVT::v16i8:
11824   case MVT::v16i16:
11825     if (Subtarget->hasAVX512())
11826       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11827                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11828   }
11829   llvm_unreachable(nullptr);
11830 }
11831
11832 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11833                                            SelectionDAG &DAG) const {
11834   SDValue N0 = Op.getOperand(0);
11835   SDLoc dl(Op);
11836
11837   if (Op.getValueType().isVector())
11838     return lowerUINT_TO_FP_vec(Op, DAG);
11839
11840   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11841   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11842   // the optimization here.
11843   if (DAG.SignBitIsZero(N0))
11844     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11845
11846   MVT SrcVT = N0.getSimpleValueType();
11847   MVT DstVT = Op.getSimpleValueType();
11848   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11849     return LowerUINT_TO_FP_i64(Op, DAG);
11850   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11851     return LowerUINT_TO_FP_i32(Op, DAG);
11852   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11853     return SDValue();
11854
11855   // Make a 64-bit buffer, and use it to build an FILD.
11856   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11857   if (SrcVT == MVT::i32) {
11858     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11859     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11860                                      getPointerTy(), StackSlot, WordOff);
11861     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11862                                   StackSlot, MachinePointerInfo(),
11863                                   false, false, 0);
11864     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11865                                   OffsetSlot, MachinePointerInfo(),
11866                                   false, false, 0);
11867     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11868     return Fild;
11869   }
11870
11871   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11872   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11873                                StackSlot, MachinePointerInfo(),
11874                                false, false, 0);
11875   // For i64 source, we need to add the appropriate power of 2 if the input
11876   // was negative.  This is the same as the optimization in
11877   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11878   // we must be careful to do the computation in x87 extended precision, not
11879   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11880   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11881   MachineMemOperand *MMO =
11882     DAG.getMachineFunction()
11883     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11884                           MachineMemOperand::MOLoad, 8, 8);
11885
11886   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11887   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11888   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11889                                          MVT::i64, MMO);
11890
11891   APInt FF(32, 0x5F800000ULL);
11892
11893   // Check whether the sign bit is set.
11894   SDValue SignSet = DAG.getSetCC(dl,
11895                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11896                                  Op.getOperand(0),
11897                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11898
11899   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11900   SDValue FudgePtr = DAG.getConstantPool(
11901                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11902                                          getPointerTy());
11903
11904   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11905   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11906   SDValue Four = DAG.getIntPtrConstant(4, dl);
11907   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11908                                Zero, Four);
11909   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11910
11911   // Load the value out, extending it from f32 to f80.
11912   // FIXME: Avoid the extend by constructing the right constant pool?
11913   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11914                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11915                                  MVT::f32, false, false, false, 4);
11916   // Extend everything to 80 bits to force it to be done on x87.
11917   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11918   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11919                      DAG.getIntPtrConstant(0, dl));
11920 }
11921
11922 std::pair<SDValue,SDValue>
11923 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11924                                     bool IsSigned, bool IsReplace) const {
11925   SDLoc DL(Op);
11926
11927   EVT DstTy = Op.getValueType();
11928
11929   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11930     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11931     DstTy = MVT::i64;
11932   }
11933
11934   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11935          DstTy.getSimpleVT() >= MVT::i16 &&
11936          "Unknown FP_TO_INT to lower!");
11937
11938   // These are really Legal.
11939   if (DstTy == MVT::i32 &&
11940       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11941     return std::make_pair(SDValue(), SDValue());
11942   if (Subtarget->is64Bit() &&
11943       DstTy == MVT::i64 &&
11944       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11945     return std::make_pair(SDValue(), SDValue());
11946
11947   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11948   // stack slot, or into the FTOL runtime function.
11949   MachineFunction &MF = DAG.getMachineFunction();
11950   unsigned MemSize = DstTy.getSizeInBits()/8;
11951   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11952   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11953
11954   unsigned Opc;
11955   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11956     Opc = X86ISD::WIN_FTOL;
11957   else
11958     switch (DstTy.getSimpleVT().SimpleTy) {
11959     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11960     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11961     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11962     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11963     }
11964
11965   SDValue Chain = DAG.getEntryNode();
11966   SDValue Value = Op.getOperand(0);
11967   EVT TheVT = Op.getOperand(0).getValueType();
11968   // FIXME This causes a redundant load/store if the SSE-class value is already
11969   // in memory, such as if it is on the callstack.
11970   if (isScalarFPTypeInSSEReg(TheVT)) {
11971     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11972     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11973                          MachinePointerInfo::getFixedStack(SSFI),
11974                          false, false, 0);
11975     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11976     SDValue Ops[] = {
11977       Chain, StackSlot, DAG.getValueType(TheVT)
11978     };
11979
11980     MachineMemOperand *MMO =
11981       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11982                               MachineMemOperand::MOLoad, MemSize, MemSize);
11983     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11984     Chain = Value.getValue(1);
11985     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11986     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11987   }
11988
11989   MachineMemOperand *MMO =
11990     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11991                             MachineMemOperand::MOStore, MemSize, MemSize);
11992
11993   if (Opc != X86ISD::WIN_FTOL) {
11994     // Build the FP_TO_INT*_IN_MEM
11995     SDValue Ops[] = { Chain, Value, StackSlot };
11996     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11997                                            Ops, DstTy, MMO);
11998     return std::make_pair(FIST, StackSlot);
11999   } else {
12000     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12001       DAG.getVTList(MVT::Other, MVT::Glue),
12002       Chain, Value);
12003     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12004       MVT::i32, ftol.getValue(1));
12005     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12006       MVT::i32, eax.getValue(2));
12007     SDValue Ops[] = { eax, edx };
12008     SDValue pair = IsReplace
12009       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12010       : DAG.getMergeValues(Ops, DL);
12011     return std::make_pair(pair, SDValue());
12012   }
12013 }
12014
12015 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12016                               const X86Subtarget *Subtarget) {
12017   MVT VT = Op->getSimpleValueType(0);
12018   SDValue In = Op->getOperand(0);
12019   MVT InVT = In.getSimpleValueType();
12020   SDLoc dl(Op);
12021
12022   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12023     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12024
12025   // Optimize vectors in AVX mode:
12026   //
12027   //   v8i16 -> v8i32
12028   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12029   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12030   //   Concat upper and lower parts.
12031   //
12032   //   v4i32 -> v4i64
12033   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12034   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12035   //   Concat upper and lower parts.
12036   //
12037
12038   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12039       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12040       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12041     return SDValue();
12042
12043   if (Subtarget->hasInt256())
12044     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12045
12046   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12047   SDValue Undef = DAG.getUNDEF(InVT);
12048   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12049   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12050   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12051
12052   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12053                              VT.getVectorNumElements()/2);
12054
12055   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12056   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12057
12058   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12059 }
12060
12061 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12062                                         SelectionDAG &DAG) {
12063   MVT VT = Op->getSimpleValueType(0);
12064   SDValue In = Op->getOperand(0);
12065   MVT InVT = In.getSimpleValueType();
12066   SDLoc DL(Op);
12067   unsigned int NumElts = VT.getVectorNumElements();
12068   if (NumElts != 8 && NumElts != 16)
12069     return SDValue();
12070
12071   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12072     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12073
12074   assert(InVT.getVectorElementType() == MVT::i1);
12075   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12076   SDValue One =
12077    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12078   SDValue Zero =
12079    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12080
12081   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12082   if (VT.is512BitVector())
12083     return V;
12084   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12085 }
12086
12087 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12088                                SelectionDAG &DAG) {
12089   if (Subtarget->hasFp256()) {
12090     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12091     if (Res.getNode())
12092       return Res;
12093   }
12094
12095   return SDValue();
12096 }
12097
12098 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12099                                 SelectionDAG &DAG) {
12100   SDLoc DL(Op);
12101   MVT VT = Op.getSimpleValueType();
12102   SDValue In = Op.getOperand(0);
12103   MVT SVT = In.getSimpleValueType();
12104
12105   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12106     return LowerZERO_EXTEND_AVX512(Op, DAG);
12107
12108   if (Subtarget->hasFp256()) {
12109     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12110     if (Res.getNode())
12111       return Res;
12112   }
12113
12114   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12115          VT.getVectorNumElements() != SVT.getVectorNumElements());
12116   return SDValue();
12117 }
12118
12119 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12120   SDLoc DL(Op);
12121   MVT VT = Op.getSimpleValueType();
12122   SDValue In = Op.getOperand(0);
12123   MVT InVT = In.getSimpleValueType();
12124
12125   if (VT == MVT::i1) {
12126     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12127            "Invalid scalar TRUNCATE operation");
12128     if (InVT.getSizeInBits() >= 32)
12129       return SDValue();
12130     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12131     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12132   }
12133   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12134          "Invalid TRUNCATE operation");
12135
12136   // move vector to mask - truncate solution for SKX
12137   if (VT.getVectorElementType() == MVT::i1) {
12138     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12139         Subtarget->hasBWI())
12140       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12141     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12142         && InVT.getScalarSizeInBits() <= 16 &&
12143         Subtarget->hasBWI() && Subtarget->hasVLX())
12144       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12145     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12146         Subtarget->hasDQI())
12147       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12148     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12149         && InVT.getScalarSizeInBits() >= 32 &&
12150         Subtarget->hasDQI() && Subtarget->hasVLX())
12151       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12152   }
12153   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12154     if (VT.getVectorElementType().getSizeInBits() >=8)
12155       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12156
12157     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12158     unsigned NumElts = InVT.getVectorNumElements();
12159     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12160     if (InVT.getSizeInBits() < 512) {
12161       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12162       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12163       InVT = ExtVT;
12164     }
12165
12166     SDValue OneV =
12167      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12168     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12169     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12170   }
12171
12172   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12173     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12174     if (Subtarget->hasInt256()) {
12175       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12176       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12177       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12178                                 ShufMask);
12179       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12180                          DAG.getIntPtrConstant(0, DL));
12181     }
12182
12183     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12184                                DAG.getIntPtrConstant(0, DL));
12185     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12186                                DAG.getIntPtrConstant(2, DL));
12187     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12188     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12189     static const int ShufMask[] = {0, 2, 4, 6};
12190     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12191   }
12192
12193   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12194     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12195     if (Subtarget->hasInt256()) {
12196       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12197
12198       SmallVector<SDValue,32> pshufbMask;
12199       for (unsigned i = 0; i < 2; ++i) {
12200         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12201         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12202         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12203         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12204         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12205         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12206         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12207         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12208         for (unsigned j = 0; j < 8; ++j)
12209           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12210       }
12211       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12212       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12213       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12214
12215       static const int ShufMask[] = {0,  2,  -1,  -1};
12216       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12217                                 &ShufMask[0]);
12218       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12219                        DAG.getIntPtrConstant(0, DL));
12220       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12221     }
12222
12223     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12224                                DAG.getIntPtrConstant(0, DL));
12225
12226     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12227                                DAG.getIntPtrConstant(4, DL));
12228
12229     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12230     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12231
12232     // The PSHUFB mask:
12233     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12234                                    -1, -1, -1, -1, -1, -1, -1, -1};
12235
12236     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12237     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12238     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12239
12240     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12241     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12242
12243     // The MOVLHPS Mask:
12244     static const int ShufMask2[] = {0, 1, 4, 5};
12245     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12246     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12247   }
12248
12249   // Handle truncation of V256 to V128 using shuffles.
12250   if (!VT.is128BitVector() || !InVT.is256BitVector())
12251     return SDValue();
12252
12253   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12254
12255   unsigned NumElems = VT.getVectorNumElements();
12256   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12257
12258   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12259   // Prepare truncation shuffle mask
12260   for (unsigned i = 0; i != NumElems; ++i)
12261     MaskVec[i] = i * 2;
12262   SDValue V = DAG.getVectorShuffle(NVT, DL,
12263                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12264                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12265   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12266                      DAG.getIntPtrConstant(0, DL));
12267 }
12268
12269 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12270                                            SelectionDAG &DAG) const {
12271   assert(!Op.getSimpleValueType().isVector());
12272
12273   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12274     /*IsSigned=*/ true, /*IsReplace=*/ false);
12275   SDValue FIST = Vals.first, StackSlot = Vals.second;
12276   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12277   if (!FIST.getNode()) return Op;
12278
12279   if (StackSlot.getNode())
12280     // Load the result.
12281     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12282                        FIST, StackSlot, MachinePointerInfo(),
12283                        false, false, false, 0);
12284
12285   // The node is the result.
12286   return FIST;
12287 }
12288
12289 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12290                                            SelectionDAG &DAG) const {
12291   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12292     /*IsSigned=*/ false, /*IsReplace=*/ false);
12293   SDValue FIST = Vals.first, StackSlot = Vals.second;
12294   assert(FIST.getNode() && "Unexpected failure");
12295
12296   if (StackSlot.getNode())
12297     // Load the result.
12298     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12299                        FIST, StackSlot, MachinePointerInfo(),
12300                        false, false, false, 0);
12301
12302   // The node is the result.
12303   return FIST;
12304 }
12305
12306 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12307   SDLoc DL(Op);
12308   MVT VT = Op.getSimpleValueType();
12309   SDValue In = Op.getOperand(0);
12310   MVT SVT = In.getSimpleValueType();
12311
12312   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12313
12314   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12315                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12316                                  In, DAG.getUNDEF(SVT)));
12317 }
12318
12319 /// The only differences between FABS and FNEG are the mask and the logic op.
12320 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12321 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12322   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12323          "Wrong opcode for lowering FABS or FNEG.");
12324
12325   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12326
12327   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12328   // into an FNABS. We'll lower the FABS after that if it is still in use.
12329   if (IsFABS)
12330     for (SDNode *User : Op->uses())
12331       if (User->getOpcode() == ISD::FNEG)
12332         return Op;
12333
12334   SDValue Op0 = Op.getOperand(0);
12335   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12336
12337   SDLoc dl(Op);
12338   MVT VT = Op.getSimpleValueType();
12339   // Assume scalar op for initialization; update for vector if needed.
12340   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12341   // generate a 16-byte vector constant and logic op even for the scalar case.
12342   // Using a 16-byte mask allows folding the load of the mask with
12343   // the logic op, so it can save (~4 bytes) on code size.
12344   MVT EltVT = VT;
12345   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12346   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12347   // decide if we should generate a 16-byte constant mask when we only need 4 or
12348   // 8 bytes for the scalar case.
12349   if (VT.isVector()) {
12350     EltVT = VT.getVectorElementType();
12351     NumElts = VT.getVectorNumElements();
12352   }
12353
12354   unsigned EltBits = EltVT.getSizeInBits();
12355   LLVMContext *Context = DAG.getContext();
12356   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12357   APInt MaskElt =
12358     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12359   Constant *C = ConstantInt::get(*Context, MaskElt);
12360   C = ConstantVector::getSplat(NumElts, C);
12361   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12362   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12363   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12364   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12365                              MachinePointerInfo::getConstantPool(),
12366                              false, false, false, Alignment);
12367
12368   if (VT.isVector()) {
12369     // For a vector, cast operands to a vector type, perform the logic op,
12370     // and cast the result back to the original value type.
12371     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12372     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12373     SDValue Operand = IsFNABS ?
12374       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12375       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12376     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12377     return DAG.getNode(ISD::BITCAST, dl, VT,
12378                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12379   }
12380
12381   // If not vector, then scalar.
12382   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12383   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12384   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12385 }
12386
12387 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12389   LLVMContext *Context = DAG.getContext();
12390   SDValue Op0 = Op.getOperand(0);
12391   SDValue Op1 = Op.getOperand(1);
12392   SDLoc dl(Op);
12393   MVT VT = Op.getSimpleValueType();
12394   MVT SrcVT = Op1.getSimpleValueType();
12395
12396   // If second operand is smaller, extend it first.
12397   if (SrcVT.bitsLT(VT)) {
12398     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12399     SrcVT = VT;
12400   }
12401   // And if it is bigger, shrink it first.
12402   if (SrcVT.bitsGT(VT)) {
12403     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12404     SrcVT = VT;
12405   }
12406
12407   // At this point the operands and the result should have the same
12408   // type, and that won't be f80 since that is not custom lowered.
12409
12410   const fltSemantics &Sem =
12411       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12412   const unsigned SizeInBits = VT.getSizeInBits();
12413
12414   SmallVector<Constant *, 4> CV(
12415       VT == MVT::f64 ? 2 : 4,
12416       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12417
12418   // First, clear all bits but the sign bit from the second operand (sign).
12419   CV[0] = ConstantFP::get(*Context,
12420                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12421   Constant *C = ConstantVector::get(CV);
12422   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12423   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12424                               MachinePointerInfo::getConstantPool(),
12425                               false, false, false, 16);
12426   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12427
12428   // Next, clear the sign bit from the first operand (magnitude).
12429   // If it's a constant, we can clear it here.
12430   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12431     APFloat APF = Op0CN->getValueAPF();
12432     // If the magnitude is a positive zero, the sign bit alone is enough.
12433     if (APF.isPosZero())
12434       return SignBit;
12435     APF.clearSign();
12436     CV[0] = ConstantFP::get(*Context, APF);
12437   } else {
12438     CV[0] = ConstantFP::get(
12439         *Context,
12440         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12441   }
12442   C = ConstantVector::get(CV);
12443   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12444   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12445                             MachinePointerInfo::getConstantPool(),
12446                             false, false, false, 16);
12447   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12448   if (!isa<ConstantFPSDNode>(Op0))
12449     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12450
12451   // OR the magnitude value with the sign bit.
12452   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12453 }
12454
12455 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12456   SDValue N0 = Op.getOperand(0);
12457   SDLoc dl(Op);
12458   MVT VT = Op.getSimpleValueType();
12459
12460   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12461   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12462                                   DAG.getConstant(1, dl, VT));
12463   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12464 }
12465
12466 // Check whether an OR'd tree is PTEST-able.
12467 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12468                                       SelectionDAG &DAG) {
12469   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12470
12471   if (!Subtarget->hasSSE41())
12472     return SDValue();
12473
12474   if (!Op->hasOneUse())
12475     return SDValue();
12476
12477   SDNode *N = Op.getNode();
12478   SDLoc DL(N);
12479
12480   SmallVector<SDValue, 8> Opnds;
12481   DenseMap<SDValue, unsigned> VecInMap;
12482   SmallVector<SDValue, 8> VecIns;
12483   EVT VT = MVT::Other;
12484
12485   // Recognize a special case where a vector is casted into wide integer to
12486   // test all 0s.
12487   Opnds.push_back(N->getOperand(0));
12488   Opnds.push_back(N->getOperand(1));
12489
12490   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12491     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12492     // BFS traverse all OR'd operands.
12493     if (I->getOpcode() == ISD::OR) {
12494       Opnds.push_back(I->getOperand(0));
12495       Opnds.push_back(I->getOperand(1));
12496       // Re-evaluate the number of nodes to be traversed.
12497       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12498       continue;
12499     }
12500
12501     // Quit if a non-EXTRACT_VECTOR_ELT
12502     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12503       return SDValue();
12504
12505     // Quit if without a constant index.
12506     SDValue Idx = I->getOperand(1);
12507     if (!isa<ConstantSDNode>(Idx))
12508       return SDValue();
12509
12510     SDValue ExtractedFromVec = I->getOperand(0);
12511     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12512     if (M == VecInMap.end()) {
12513       VT = ExtractedFromVec.getValueType();
12514       // Quit if not 128/256-bit vector.
12515       if (!VT.is128BitVector() && !VT.is256BitVector())
12516         return SDValue();
12517       // Quit if not the same type.
12518       if (VecInMap.begin() != VecInMap.end() &&
12519           VT != VecInMap.begin()->first.getValueType())
12520         return SDValue();
12521       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12522       VecIns.push_back(ExtractedFromVec);
12523     }
12524     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12525   }
12526
12527   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12528          "Not extracted from 128-/256-bit vector.");
12529
12530   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12531
12532   for (DenseMap<SDValue, unsigned>::const_iterator
12533         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12534     // Quit if not all elements are used.
12535     if (I->second != FullMask)
12536       return SDValue();
12537   }
12538
12539   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12540
12541   // Cast all vectors into TestVT for PTEST.
12542   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12543     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12544
12545   // If more than one full vectors are evaluated, OR them first before PTEST.
12546   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12547     // Each iteration will OR 2 nodes and append the result until there is only
12548     // 1 node left, i.e. the final OR'd value of all vectors.
12549     SDValue LHS = VecIns[Slot];
12550     SDValue RHS = VecIns[Slot + 1];
12551     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12552   }
12553
12554   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12555                      VecIns.back(), VecIns.back());
12556 }
12557
12558 /// \brief return true if \c Op has a use that doesn't just read flags.
12559 static bool hasNonFlagsUse(SDValue Op) {
12560   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12561        ++UI) {
12562     SDNode *User = *UI;
12563     unsigned UOpNo = UI.getOperandNo();
12564     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12565       // Look pass truncate.
12566       UOpNo = User->use_begin().getOperandNo();
12567       User = *User->use_begin();
12568     }
12569
12570     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12571         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12572       return true;
12573   }
12574   return false;
12575 }
12576
12577 /// Emit nodes that will be selected as "test Op0,Op0", or something
12578 /// equivalent.
12579 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12580                                     SelectionDAG &DAG) const {
12581   if (Op.getValueType() == MVT::i1) {
12582     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12583     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12584                        DAG.getConstant(0, dl, MVT::i8));
12585   }
12586   // CF and OF aren't always set the way we want. Determine which
12587   // of these we need.
12588   bool NeedCF = false;
12589   bool NeedOF = false;
12590   switch (X86CC) {
12591   default: break;
12592   case X86::COND_A: case X86::COND_AE:
12593   case X86::COND_B: case X86::COND_BE:
12594     NeedCF = true;
12595     break;
12596   case X86::COND_G: case X86::COND_GE:
12597   case X86::COND_L: case X86::COND_LE:
12598   case X86::COND_O: case X86::COND_NO: {
12599     // Check if we really need to set the
12600     // Overflow flag. If NoSignedWrap is present
12601     // that is not actually needed.
12602     switch (Op->getOpcode()) {
12603     case ISD::ADD:
12604     case ISD::SUB:
12605     case ISD::MUL:
12606     case ISD::SHL: {
12607       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12608       if (BinNode->Flags.hasNoSignedWrap())
12609         break;
12610     }
12611     default:
12612       NeedOF = true;
12613       break;
12614     }
12615     break;
12616   }
12617   }
12618   // See if we can use the EFLAGS value from the operand instead of
12619   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12620   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12621   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12622     // Emit a CMP with 0, which is the TEST pattern.
12623     //if (Op.getValueType() == MVT::i1)
12624     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12625     //                     DAG.getConstant(0, MVT::i1));
12626     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12627                        DAG.getConstant(0, dl, Op.getValueType()));
12628   }
12629   unsigned Opcode = 0;
12630   unsigned NumOperands = 0;
12631
12632   // Truncate operations may prevent the merge of the SETCC instruction
12633   // and the arithmetic instruction before it. Attempt to truncate the operands
12634   // of the arithmetic instruction and use a reduced bit-width instruction.
12635   bool NeedTruncation = false;
12636   SDValue ArithOp = Op;
12637   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12638     SDValue Arith = Op->getOperand(0);
12639     // Both the trunc and the arithmetic op need to have one user each.
12640     if (Arith->hasOneUse())
12641       switch (Arith.getOpcode()) {
12642         default: break;
12643         case ISD::ADD:
12644         case ISD::SUB:
12645         case ISD::AND:
12646         case ISD::OR:
12647         case ISD::XOR: {
12648           NeedTruncation = true;
12649           ArithOp = Arith;
12650         }
12651       }
12652   }
12653
12654   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12655   // which may be the result of a CAST.  We use the variable 'Op', which is the
12656   // non-casted variable when we check for possible users.
12657   switch (ArithOp.getOpcode()) {
12658   case ISD::ADD:
12659     // Due to an isel shortcoming, be conservative if this add is likely to be
12660     // selected as part of a load-modify-store instruction. When the root node
12661     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12662     // uses of other nodes in the match, such as the ADD in this case. This
12663     // leads to the ADD being left around and reselected, with the result being
12664     // two adds in the output.  Alas, even if none our users are stores, that
12665     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12666     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12667     // climbing the DAG back to the root, and it doesn't seem to be worth the
12668     // effort.
12669     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12670          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12671       if (UI->getOpcode() != ISD::CopyToReg &&
12672           UI->getOpcode() != ISD::SETCC &&
12673           UI->getOpcode() != ISD::STORE)
12674         goto default_case;
12675
12676     if (ConstantSDNode *C =
12677         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12678       // An add of one will be selected as an INC.
12679       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12680         Opcode = X86ISD::INC;
12681         NumOperands = 1;
12682         break;
12683       }
12684
12685       // An add of negative one (subtract of one) will be selected as a DEC.
12686       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12687         Opcode = X86ISD::DEC;
12688         NumOperands = 1;
12689         break;
12690       }
12691     }
12692
12693     // Otherwise use a regular EFLAGS-setting add.
12694     Opcode = X86ISD::ADD;
12695     NumOperands = 2;
12696     break;
12697   case ISD::SHL:
12698   case ISD::SRL:
12699     // If we have a constant logical shift that's only used in a comparison
12700     // against zero turn it into an equivalent AND. This allows turning it into
12701     // a TEST instruction later.
12702     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12703         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12704       EVT VT = Op.getValueType();
12705       unsigned BitWidth = VT.getSizeInBits();
12706       unsigned ShAmt = Op->getConstantOperandVal(1);
12707       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12708         break;
12709       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12710                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12711                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12712       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12713         break;
12714       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12715                                 DAG.getConstant(Mask, dl, VT));
12716       DAG.ReplaceAllUsesWith(Op, New);
12717       Op = New;
12718     }
12719     break;
12720
12721   case ISD::AND:
12722     // If the primary and result isn't used, don't bother using X86ISD::AND,
12723     // because a TEST instruction will be better.
12724     if (!hasNonFlagsUse(Op))
12725       break;
12726     // FALL THROUGH
12727   case ISD::SUB:
12728   case ISD::OR:
12729   case ISD::XOR:
12730     // Due to the ISEL shortcoming noted above, be conservative if this op is
12731     // likely to be selected as part of a load-modify-store instruction.
12732     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12733            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12734       if (UI->getOpcode() == ISD::STORE)
12735         goto default_case;
12736
12737     // Otherwise use a regular EFLAGS-setting instruction.
12738     switch (ArithOp.getOpcode()) {
12739     default: llvm_unreachable("unexpected operator!");
12740     case ISD::SUB: Opcode = X86ISD::SUB; break;
12741     case ISD::XOR: Opcode = X86ISD::XOR; break;
12742     case ISD::AND: Opcode = X86ISD::AND; break;
12743     case ISD::OR: {
12744       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12745         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12746         if (EFLAGS.getNode())
12747           return EFLAGS;
12748       }
12749       Opcode = X86ISD::OR;
12750       break;
12751     }
12752     }
12753
12754     NumOperands = 2;
12755     break;
12756   case X86ISD::ADD:
12757   case X86ISD::SUB:
12758   case X86ISD::INC:
12759   case X86ISD::DEC:
12760   case X86ISD::OR:
12761   case X86ISD::XOR:
12762   case X86ISD::AND:
12763     return SDValue(Op.getNode(), 1);
12764   default:
12765   default_case:
12766     break;
12767   }
12768
12769   // If we found that truncation is beneficial, perform the truncation and
12770   // update 'Op'.
12771   if (NeedTruncation) {
12772     EVT VT = Op.getValueType();
12773     SDValue WideVal = Op->getOperand(0);
12774     EVT WideVT = WideVal.getValueType();
12775     unsigned ConvertedOp = 0;
12776     // Use a target machine opcode to prevent further DAGCombine
12777     // optimizations that may separate the arithmetic operations
12778     // from the setcc node.
12779     switch (WideVal.getOpcode()) {
12780       default: break;
12781       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12782       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12783       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12784       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12785       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12786     }
12787
12788     if (ConvertedOp) {
12789       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12790       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12791         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12792         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12793         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12794       }
12795     }
12796   }
12797
12798   if (Opcode == 0)
12799     // Emit a CMP with 0, which is the TEST pattern.
12800     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12801                        DAG.getConstant(0, dl, Op.getValueType()));
12802
12803   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12804   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12805
12806   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12807   DAG.ReplaceAllUsesWith(Op, New);
12808   return SDValue(New.getNode(), 1);
12809 }
12810
12811 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12812 /// equivalent.
12813 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12814                                    SDLoc dl, SelectionDAG &DAG) const {
12815   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12816     if (C->getAPIntValue() == 0)
12817       return EmitTest(Op0, X86CC, dl, DAG);
12818
12819      if (Op0.getValueType() == MVT::i1)
12820        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12821   }
12822
12823   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12824        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12825     // Do the comparison at i32 if it's smaller, besides the Atom case.
12826     // This avoids subregister aliasing issues. Keep the smaller reference
12827     // if we're optimizing for size, however, as that'll allow better folding
12828     // of memory operations.
12829     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12830         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12831             Attribute::MinSize) &&
12832         !Subtarget->isAtom()) {
12833       unsigned ExtendOp =
12834           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12835       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12836       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12837     }
12838     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12839     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12840     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12841                               Op0, Op1);
12842     return SDValue(Sub.getNode(), 1);
12843   }
12844   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12845 }
12846
12847 /// Convert a comparison if required by the subtarget.
12848 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12849                                                  SelectionDAG &DAG) const {
12850   // If the subtarget does not support the FUCOMI instruction, floating-point
12851   // comparisons have to be converted.
12852   if (Subtarget->hasCMov() ||
12853       Cmp.getOpcode() != X86ISD::CMP ||
12854       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12855       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12856     return Cmp;
12857
12858   // The instruction selector will select an FUCOM instruction instead of
12859   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12860   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12861   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12862   SDLoc dl(Cmp);
12863   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12864   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12865   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12866                             DAG.getConstant(8, dl, MVT::i8));
12867   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12868   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12869 }
12870
12871 /// The minimum architected relative accuracy is 2^-12. We need one
12872 /// Newton-Raphson step to have a good float result (24 bits of precision).
12873 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12874                                             DAGCombinerInfo &DCI,
12875                                             unsigned &RefinementSteps,
12876                                             bool &UseOneConstNR) const {
12877   // FIXME: We should use instruction latency models to calculate the cost of
12878   // each potential sequence, but this is very hard to do reliably because
12879   // at least Intel's Core* chips have variable timing based on the number of
12880   // significant digits in the divisor and/or sqrt operand.
12881   if (!Subtarget->useSqrtEst())
12882     return SDValue();
12883
12884   EVT VT = Op.getValueType();
12885
12886   // SSE1 has rsqrtss and rsqrtps.
12887   // TODO: Add support for AVX512 (v16f32).
12888   // It is likely not profitable to do this for f64 because a double-precision
12889   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12890   // instructions: convert to single, rsqrtss, convert back to double, refine
12891   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12892   // along with FMA, this could be a throughput win.
12893   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12894       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12895     RefinementSteps = 1;
12896     UseOneConstNR = false;
12897     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12898   }
12899   return SDValue();
12900 }
12901
12902 /// The minimum architected relative accuracy is 2^-12. We need one
12903 /// Newton-Raphson step to have a good float result (24 bits of precision).
12904 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12905                                             DAGCombinerInfo &DCI,
12906                                             unsigned &RefinementSteps) const {
12907   // FIXME: We should use instruction latency models to calculate the cost of
12908   // each potential sequence, but this is very hard to do reliably because
12909   // at least Intel's Core* chips have variable timing based on the number of
12910   // significant digits in the divisor.
12911   if (!Subtarget->useReciprocalEst())
12912     return SDValue();
12913
12914   EVT VT = Op.getValueType();
12915
12916   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12917   // TODO: Add support for AVX512 (v16f32).
12918   // It is likely not profitable to do this for f64 because a double-precision
12919   // reciprocal estimate with refinement on x86 prior to FMA requires
12920   // 15 instructions: convert to single, rcpss, convert back to double, refine
12921   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12922   // along with FMA, this could be a throughput win.
12923   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12924       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12925     RefinementSteps = ReciprocalEstimateRefinementSteps;
12926     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12927   }
12928   return SDValue();
12929 }
12930
12931 /// If we have at least two divisions that use the same divisor, convert to
12932 /// multplication by a reciprocal. This may need to be adjusted for a given
12933 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12934 /// This is because we still need one division to calculate the reciprocal and
12935 /// then we need two multiplies by that reciprocal as replacements for the
12936 /// original divisions.
12937 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12938   return NumUsers > 1;
12939 }
12940
12941 static bool isAllOnes(SDValue V) {
12942   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12943   return C && C->isAllOnesValue();
12944 }
12945
12946 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12947 /// if it's possible.
12948 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12949                                      SDLoc dl, SelectionDAG &DAG) const {
12950   SDValue Op0 = And.getOperand(0);
12951   SDValue Op1 = And.getOperand(1);
12952   if (Op0.getOpcode() == ISD::TRUNCATE)
12953     Op0 = Op0.getOperand(0);
12954   if (Op1.getOpcode() == ISD::TRUNCATE)
12955     Op1 = Op1.getOperand(0);
12956
12957   SDValue LHS, RHS;
12958   if (Op1.getOpcode() == ISD::SHL)
12959     std::swap(Op0, Op1);
12960   if (Op0.getOpcode() == ISD::SHL) {
12961     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12962       if (And00C->getZExtValue() == 1) {
12963         // If we looked past a truncate, check that it's only truncating away
12964         // known zeros.
12965         unsigned BitWidth = Op0.getValueSizeInBits();
12966         unsigned AndBitWidth = And.getValueSizeInBits();
12967         if (BitWidth > AndBitWidth) {
12968           APInt Zeros, Ones;
12969           DAG.computeKnownBits(Op0, Zeros, Ones);
12970           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12971             return SDValue();
12972         }
12973         LHS = Op1;
12974         RHS = Op0.getOperand(1);
12975       }
12976   } else if (Op1.getOpcode() == ISD::Constant) {
12977     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12978     uint64_t AndRHSVal = AndRHS->getZExtValue();
12979     SDValue AndLHS = Op0;
12980
12981     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12982       LHS = AndLHS.getOperand(0);
12983       RHS = AndLHS.getOperand(1);
12984     }
12985
12986     // Use BT if the immediate can't be encoded in a TEST instruction.
12987     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12988       LHS = AndLHS;
12989       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
12990     }
12991   }
12992
12993   if (LHS.getNode()) {
12994     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12995     // instruction.  Since the shift amount is in-range-or-undefined, we know
12996     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12997     // the encoding for the i16 version is larger than the i32 version.
12998     // Also promote i16 to i32 for performance / code size reason.
12999     if (LHS.getValueType() == MVT::i8 ||
13000         LHS.getValueType() == MVT::i16)
13001       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13002
13003     // If the operand types disagree, extend the shift amount to match.  Since
13004     // BT ignores high bits (like shifts) we can use anyextend.
13005     if (LHS.getValueType() != RHS.getValueType())
13006       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13007
13008     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13009     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13010     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13011                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13012   }
13013
13014   return SDValue();
13015 }
13016
13017 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13018 /// mask CMPs.
13019 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13020                               SDValue &Op1) {
13021   unsigned SSECC;
13022   bool Swap = false;
13023
13024   // SSE Condition code mapping:
13025   //  0 - EQ
13026   //  1 - LT
13027   //  2 - LE
13028   //  3 - UNORD
13029   //  4 - NEQ
13030   //  5 - NLT
13031   //  6 - NLE
13032   //  7 - ORD
13033   switch (SetCCOpcode) {
13034   default: llvm_unreachable("Unexpected SETCC condition");
13035   case ISD::SETOEQ:
13036   case ISD::SETEQ:  SSECC = 0; break;
13037   case ISD::SETOGT:
13038   case ISD::SETGT:  Swap = true; // Fallthrough
13039   case ISD::SETLT:
13040   case ISD::SETOLT: SSECC = 1; break;
13041   case ISD::SETOGE:
13042   case ISD::SETGE:  Swap = true; // Fallthrough
13043   case ISD::SETLE:
13044   case ISD::SETOLE: SSECC = 2; break;
13045   case ISD::SETUO:  SSECC = 3; break;
13046   case ISD::SETUNE:
13047   case ISD::SETNE:  SSECC = 4; break;
13048   case ISD::SETULE: Swap = true; // Fallthrough
13049   case ISD::SETUGE: SSECC = 5; break;
13050   case ISD::SETULT: Swap = true; // Fallthrough
13051   case ISD::SETUGT: SSECC = 6; break;
13052   case ISD::SETO:   SSECC = 7; break;
13053   case ISD::SETUEQ:
13054   case ISD::SETONE: SSECC = 8; break;
13055   }
13056   if (Swap)
13057     std::swap(Op0, Op1);
13058
13059   return SSECC;
13060 }
13061
13062 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13063 // ones, and then concatenate the result back.
13064 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13065   MVT VT = Op.getSimpleValueType();
13066
13067   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13068          "Unsupported value type for operation");
13069
13070   unsigned NumElems = VT.getVectorNumElements();
13071   SDLoc dl(Op);
13072   SDValue CC = Op.getOperand(2);
13073
13074   // Extract the LHS vectors
13075   SDValue LHS = Op.getOperand(0);
13076   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13077   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13078
13079   // Extract the RHS vectors
13080   SDValue RHS = Op.getOperand(1);
13081   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13082   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13083
13084   // Issue the operation on the smaller types and concatenate the result back
13085   MVT EltVT = VT.getVectorElementType();
13086   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13087   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13088                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13089                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13090 }
13091
13092 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13093   SDValue Op0 = Op.getOperand(0);
13094   SDValue Op1 = Op.getOperand(1);
13095   SDValue CC = Op.getOperand(2);
13096   MVT VT = Op.getSimpleValueType();
13097   SDLoc dl(Op);
13098
13099   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13100          "Unexpected type for boolean compare operation");
13101   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13102   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13103                                DAG.getConstant(-1, dl, VT));
13104   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13105                                DAG.getConstant(-1, dl, VT));
13106   switch (SetCCOpcode) {
13107   default: llvm_unreachable("Unexpected SETCC condition");
13108   case ISD::SETNE:
13109     // (x != y) -> ~(x ^ y)
13110     return DAG.getNode(ISD::XOR, dl, VT,
13111                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13112                        DAG.getConstant(-1, dl, VT));
13113   case ISD::SETEQ:
13114     // (x == y) -> (x ^ y)
13115     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13116   case ISD::SETUGT:
13117   case ISD::SETGT:
13118     // (x > y) -> (x & ~y)
13119     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13120   case ISD::SETULT:
13121   case ISD::SETLT:
13122     // (x < y) -> (~x & y)
13123     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13124   case ISD::SETULE:
13125   case ISD::SETLE:
13126     // (x <= y) -> (~x | y)
13127     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13128   case ISD::SETUGE:
13129   case ISD::SETGE:
13130     // (x >=y) -> (x | ~y)
13131     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13132   }
13133 }
13134
13135 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13136                                      const X86Subtarget *Subtarget) {
13137   SDValue Op0 = Op.getOperand(0);
13138   SDValue Op1 = Op.getOperand(1);
13139   SDValue CC = Op.getOperand(2);
13140   MVT VT = Op.getSimpleValueType();
13141   SDLoc dl(Op);
13142
13143   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13144          Op.getValueType().getScalarType() == MVT::i1 &&
13145          "Cannot set masked compare for this operation");
13146
13147   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13148   unsigned  Opc = 0;
13149   bool Unsigned = false;
13150   bool Swap = false;
13151   unsigned SSECC;
13152   switch (SetCCOpcode) {
13153   default: llvm_unreachable("Unexpected SETCC condition");
13154   case ISD::SETNE:  SSECC = 4; break;
13155   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13156   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13157   case ISD::SETLT:  Swap = true; //fall-through
13158   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13159   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13160   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13161   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13162   case ISD::SETULE: Unsigned = true; //fall-through
13163   case ISD::SETLE:  SSECC = 2; break;
13164   }
13165
13166   if (Swap)
13167     std::swap(Op0, Op1);
13168   if (Opc)
13169     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13170   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13171   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13172                      DAG.getConstant(SSECC, dl, MVT::i8));
13173 }
13174
13175 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13176 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13177 /// return an empty value.
13178 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13179 {
13180   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13181   if (!BV)
13182     return SDValue();
13183
13184   MVT VT = Op1.getSimpleValueType();
13185   MVT EVT = VT.getVectorElementType();
13186   unsigned n = VT.getVectorNumElements();
13187   SmallVector<SDValue, 8> ULTOp1;
13188
13189   for (unsigned i = 0; i < n; ++i) {
13190     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13191     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13192       return SDValue();
13193
13194     // Avoid underflow.
13195     APInt Val = Elt->getAPIntValue();
13196     if (Val == 0)
13197       return SDValue();
13198
13199     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13200   }
13201
13202   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13203 }
13204
13205 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13206                            SelectionDAG &DAG) {
13207   SDValue Op0 = Op.getOperand(0);
13208   SDValue Op1 = Op.getOperand(1);
13209   SDValue CC = Op.getOperand(2);
13210   MVT VT = Op.getSimpleValueType();
13211   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13212   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13213   SDLoc dl(Op);
13214
13215   if (isFP) {
13216 #ifndef NDEBUG
13217     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13218     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13219 #endif
13220
13221     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13222     unsigned Opc = X86ISD::CMPP;
13223     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13224       assert(VT.getVectorNumElements() <= 16);
13225       Opc = X86ISD::CMPM;
13226     }
13227     // In the two special cases we can't handle, emit two comparisons.
13228     if (SSECC == 8) {
13229       unsigned CC0, CC1;
13230       unsigned CombineOpc;
13231       if (SetCCOpcode == ISD::SETUEQ) {
13232         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13233       } else {
13234         assert(SetCCOpcode == ISD::SETONE);
13235         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13236       }
13237
13238       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13239                                  DAG.getConstant(CC0, dl, MVT::i8));
13240       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13241                                  DAG.getConstant(CC1, dl, MVT::i8));
13242       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13243     }
13244     // Handle all other FP comparisons here.
13245     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13246                        DAG.getConstant(SSECC, dl, MVT::i8));
13247   }
13248
13249   // Break 256-bit integer vector compare into smaller ones.
13250   if (VT.is256BitVector() && !Subtarget->hasInt256())
13251     return Lower256IntVSETCC(Op, DAG);
13252
13253   EVT OpVT = Op1.getValueType();
13254   if (OpVT.getVectorElementType() == MVT::i1)
13255     return LowerBoolVSETCC_AVX512(Op, DAG);
13256
13257   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13258   if (Subtarget->hasAVX512()) {
13259     if (Op1.getValueType().is512BitVector() ||
13260         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13261         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13262       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13263
13264     // In AVX-512 architecture setcc returns mask with i1 elements,
13265     // But there is no compare instruction for i8 and i16 elements in KNL.
13266     // We are not talking about 512-bit operands in this case, these
13267     // types are illegal.
13268     if (MaskResult &&
13269         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13270          OpVT.getVectorElementType().getSizeInBits() >= 8))
13271       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13272                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13273   }
13274
13275   // We are handling one of the integer comparisons here.  Since SSE only has
13276   // GT and EQ comparisons for integer, swapping operands and multiple
13277   // operations may be required for some comparisons.
13278   unsigned Opc;
13279   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13280   bool Subus = false;
13281
13282   switch (SetCCOpcode) {
13283   default: llvm_unreachable("Unexpected SETCC condition");
13284   case ISD::SETNE:  Invert = true;
13285   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13286   case ISD::SETLT:  Swap = true;
13287   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13288   case ISD::SETGE:  Swap = true;
13289   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13290                     Invert = true; break;
13291   case ISD::SETULT: Swap = true;
13292   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13293                     FlipSigns = true; break;
13294   case ISD::SETUGE: Swap = true;
13295   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13296                     FlipSigns = true; Invert = true; break;
13297   }
13298
13299   // Special case: Use min/max operations for SETULE/SETUGE
13300   MVT VET = VT.getVectorElementType();
13301   bool hasMinMax =
13302        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13303     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13304
13305   if (hasMinMax) {
13306     switch (SetCCOpcode) {
13307     default: break;
13308     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13309     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13310     }
13311
13312     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13313   }
13314
13315   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13316   if (!MinMax && hasSubus) {
13317     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13318     // Op0 u<= Op1:
13319     //   t = psubus Op0, Op1
13320     //   pcmpeq t, <0..0>
13321     switch (SetCCOpcode) {
13322     default: break;
13323     case ISD::SETULT: {
13324       // If the comparison is against a constant we can turn this into a
13325       // setule.  With psubus, setule does not require a swap.  This is
13326       // beneficial because the constant in the register is no longer
13327       // destructed as the destination so it can be hoisted out of a loop.
13328       // Only do this pre-AVX since vpcmp* is no longer destructive.
13329       if (Subtarget->hasAVX())
13330         break;
13331       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13332       if (ULEOp1.getNode()) {
13333         Op1 = ULEOp1;
13334         Subus = true; Invert = false; Swap = false;
13335       }
13336       break;
13337     }
13338     // Psubus is better than flip-sign because it requires no inversion.
13339     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13340     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13341     }
13342
13343     if (Subus) {
13344       Opc = X86ISD::SUBUS;
13345       FlipSigns = false;
13346     }
13347   }
13348
13349   if (Swap)
13350     std::swap(Op0, Op1);
13351
13352   // Check that the operation in question is available (most are plain SSE2,
13353   // but PCMPGTQ and PCMPEQQ have different requirements).
13354   if (VT == MVT::v2i64) {
13355     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13356       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13357
13358       // First cast everything to the right type.
13359       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13360       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13361
13362       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13363       // bits of the inputs before performing those operations. The lower
13364       // compare is always unsigned.
13365       SDValue SB;
13366       if (FlipSigns) {
13367         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13368       } else {
13369         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13370         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13371         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13372                          Sign, Zero, Sign, Zero);
13373       }
13374       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13375       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13376
13377       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13378       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13379       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13380
13381       // Create masks for only the low parts/high parts of the 64 bit integers.
13382       static const int MaskHi[] = { 1, 1, 3, 3 };
13383       static const int MaskLo[] = { 0, 0, 2, 2 };
13384       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13385       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13386       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13387
13388       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13389       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13390
13391       if (Invert)
13392         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13393
13394       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13395     }
13396
13397     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13398       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13399       // pcmpeqd + pshufd + pand.
13400       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13401
13402       // First cast everything to the right type.
13403       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13404       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13405
13406       // Do the compare.
13407       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13408
13409       // Make sure the lower and upper halves are both all-ones.
13410       static const int Mask[] = { 1, 0, 3, 2 };
13411       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13412       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13413
13414       if (Invert)
13415         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13416
13417       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13418     }
13419   }
13420
13421   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13422   // bits of the inputs before performing those operations.
13423   if (FlipSigns) {
13424     EVT EltVT = VT.getVectorElementType();
13425     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13426                                  VT);
13427     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13428     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13429   }
13430
13431   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13432
13433   // If the logical-not of the result is required, perform that now.
13434   if (Invert)
13435     Result = DAG.getNOT(dl, Result, VT);
13436
13437   if (MinMax)
13438     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13439
13440   if (Subus)
13441     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13442                          getZeroVector(VT, Subtarget, DAG, dl));
13443
13444   return Result;
13445 }
13446
13447 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13448
13449   MVT VT = Op.getSimpleValueType();
13450
13451   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13452
13453   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13454          && "SetCC type must be 8-bit or 1-bit integer");
13455   SDValue Op0 = Op.getOperand(0);
13456   SDValue Op1 = Op.getOperand(1);
13457   SDLoc dl(Op);
13458   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13459
13460   // Optimize to BT if possible.
13461   // Lower (X & (1 << N)) == 0 to BT(X, N).
13462   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13463   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13464   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13465       Op1.getOpcode() == ISD::Constant &&
13466       cast<ConstantSDNode>(Op1)->isNullValue() &&
13467       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13468     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13469     if (NewSetCC.getNode()) {
13470       if (VT == MVT::i1)
13471         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13472       return NewSetCC;
13473     }
13474   }
13475
13476   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13477   // these.
13478   if (Op1.getOpcode() == ISD::Constant &&
13479       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13480        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13481       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13482
13483     // If the input is a setcc, then reuse the input setcc or use a new one with
13484     // the inverted condition.
13485     if (Op0.getOpcode() == X86ISD::SETCC) {
13486       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13487       bool Invert = (CC == ISD::SETNE) ^
13488         cast<ConstantSDNode>(Op1)->isNullValue();
13489       if (!Invert)
13490         return Op0;
13491
13492       CCode = X86::GetOppositeBranchCondition(CCode);
13493       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13494                                   DAG.getConstant(CCode, dl, MVT::i8),
13495                                   Op0.getOperand(1));
13496       if (VT == MVT::i1)
13497         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13498       return SetCC;
13499     }
13500   }
13501   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13502       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13503       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13504
13505     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13506     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13507   }
13508
13509   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13510   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13511   if (X86CC == X86::COND_INVALID)
13512     return SDValue();
13513
13514   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13515   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13516   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13517                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13518   if (VT == MVT::i1)
13519     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13520   return SetCC;
13521 }
13522
13523 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13524 static bool isX86LogicalCmp(SDValue Op) {
13525   unsigned Opc = Op.getNode()->getOpcode();
13526   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13527       Opc == X86ISD::SAHF)
13528     return true;
13529   if (Op.getResNo() == 1 &&
13530       (Opc == X86ISD::ADD ||
13531        Opc == X86ISD::SUB ||
13532        Opc == X86ISD::ADC ||
13533        Opc == X86ISD::SBB ||
13534        Opc == X86ISD::SMUL ||
13535        Opc == X86ISD::UMUL ||
13536        Opc == X86ISD::INC ||
13537        Opc == X86ISD::DEC ||
13538        Opc == X86ISD::OR ||
13539        Opc == X86ISD::XOR ||
13540        Opc == X86ISD::AND))
13541     return true;
13542
13543   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13544     return true;
13545
13546   return false;
13547 }
13548
13549 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13550   if (V.getOpcode() != ISD::TRUNCATE)
13551     return false;
13552
13553   SDValue VOp0 = V.getOperand(0);
13554   unsigned InBits = VOp0.getValueSizeInBits();
13555   unsigned Bits = V.getValueSizeInBits();
13556   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13557 }
13558
13559 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13560   bool addTest = true;
13561   SDValue Cond  = Op.getOperand(0);
13562   SDValue Op1 = Op.getOperand(1);
13563   SDValue Op2 = Op.getOperand(2);
13564   SDLoc DL(Op);
13565   EVT VT = Op1.getValueType();
13566   SDValue CC;
13567
13568   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13569   // are available or VBLENDV if AVX is available.
13570   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13571   if (Cond.getOpcode() == ISD::SETCC &&
13572       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13573        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13574       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13575     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13576     int SSECC = translateX86FSETCC(
13577         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13578
13579     if (SSECC != 8) {
13580       if (Subtarget->hasAVX512()) {
13581         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13582                                   DAG.getConstant(SSECC, DL, MVT::i8));
13583         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13584       }
13585
13586       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13587                                 DAG.getConstant(SSECC, DL, MVT::i8));
13588
13589       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13590       // of 3 logic instructions for size savings and potentially speed.
13591       // Unfortunately, there is no scalar form of VBLENDV.
13592
13593       // If either operand is a constant, don't try this. We can expect to
13594       // optimize away at least one of the logic instructions later in that
13595       // case, so that sequence would be faster than a variable blend.
13596
13597       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13598       // uses XMM0 as the selection register. That may need just as many
13599       // instructions as the AND/ANDN/OR sequence due to register moves, so
13600       // don't bother.
13601
13602       if (Subtarget->hasAVX() &&
13603           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13604
13605         // Convert to vectors, do a VSELECT, and convert back to scalar.
13606         // All of the conversions should be optimized away.
13607
13608         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13609         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13610         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13611         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13612
13613         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13614         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13615
13616         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13617
13618         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13619                            VSel, DAG.getIntPtrConstant(0, DL));
13620       }
13621       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13622       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13623       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13624     }
13625   }
13626
13627   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13628     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13629     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13630                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13631     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13632                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13633     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13634                                     Cond, Op1, Op2);
13635     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13636   }
13637
13638   if (Cond.getOpcode() == ISD::SETCC) {
13639     SDValue NewCond = LowerSETCC(Cond, DAG);
13640     if (NewCond.getNode())
13641       Cond = NewCond;
13642   }
13643
13644   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13645   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13646   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13647   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13648   if (Cond.getOpcode() == X86ISD::SETCC &&
13649       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13650       isZero(Cond.getOperand(1).getOperand(1))) {
13651     SDValue Cmp = Cond.getOperand(1);
13652
13653     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13654
13655     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13656         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13657       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13658
13659       SDValue CmpOp0 = Cmp.getOperand(0);
13660       // Apply further optimizations for special cases
13661       // (select (x != 0), -1, 0) -> neg & sbb
13662       // (select (x == 0), 0, -1) -> neg & sbb
13663       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13664         if (YC->isNullValue() &&
13665             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13666           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13667           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13668                                     DAG.getConstant(0, DL,
13669                                                     CmpOp0.getValueType()),
13670                                     CmpOp0);
13671           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13672                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13673                                     SDValue(Neg.getNode(), 1));
13674           return Res;
13675         }
13676
13677       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13678                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13679       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13680
13681       SDValue Res =   // Res = 0 or -1.
13682         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13683                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13684
13685       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13686         Res = DAG.getNOT(DL, Res, Res.getValueType());
13687
13688       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13689       if (!N2C || !N2C->isNullValue())
13690         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13691       return Res;
13692     }
13693   }
13694
13695   // Look past (and (setcc_carry (cmp ...)), 1).
13696   if (Cond.getOpcode() == ISD::AND &&
13697       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13698     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13699     if (C && C->getAPIntValue() == 1)
13700       Cond = Cond.getOperand(0);
13701   }
13702
13703   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13704   // setting operand in place of the X86ISD::SETCC.
13705   unsigned CondOpcode = Cond.getOpcode();
13706   if (CondOpcode == X86ISD::SETCC ||
13707       CondOpcode == X86ISD::SETCC_CARRY) {
13708     CC = Cond.getOperand(0);
13709
13710     SDValue Cmp = Cond.getOperand(1);
13711     unsigned Opc = Cmp.getOpcode();
13712     MVT VT = Op.getSimpleValueType();
13713
13714     bool IllegalFPCMov = false;
13715     if (VT.isFloatingPoint() && !VT.isVector() &&
13716         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13717       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13718
13719     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13720         Opc == X86ISD::BT) { // FIXME
13721       Cond = Cmp;
13722       addTest = false;
13723     }
13724   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13725              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13726              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13727               Cond.getOperand(0).getValueType() != MVT::i8)) {
13728     SDValue LHS = Cond.getOperand(0);
13729     SDValue RHS = Cond.getOperand(1);
13730     unsigned X86Opcode;
13731     unsigned X86Cond;
13732     SDVTList VTs;
13733     switch (CondOpcode) {
13734     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13735     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13736     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13737     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13738     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13739     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13740     default: llvm_unreachable("unexpected overflowing operator");
13741     }
13742     if (CondOpcode == ISD::UMULO)
13743       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13744                           MVT::i32);
13745     else
13746       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13747
13748     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13749
13750     if (CondOpcode == ISD::UMULO)
13751       Cond = X86Op.getValue(2);
13752     else
13753       Cond = X86Op.getValue(1);
13754
13755     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13756     addTest = false;
13757   }
13758
13759   if (addTest) {
13760     // Look pass the truncate if the high bits are known zero.
13761     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13762         Cond = Cond.getOperand(0);
13763
13764     // We know the result of AND is compared against zero. Try to match
13765     // it to BT.
13766     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13767       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13768       if (NewSetCC.getNode()) {
13769         CC = NewSetCC.getOperand(0);
13770         Cond = NewSetCC.getOperand(1);
13771         addTest = false;
13772       }
13773     }
13774   }
13775
13776   if (addTest) {
13777     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13778     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13779   }
13780
13781   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13782   // a <  b ?  0 : -1 -> RES = setcc_carry
13783   // a >= b ? -1 :  0 -> RES = setcc_carry
13784   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13785   if (Cond.getOpcode() == X86ISD::SUB) {
13786     Cond = ConvertCmpIfNecessary(Cond, DAG);
13787     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13788
13789     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13790         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13791       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13792                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13793                                 Cond);
13794       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13795         return DAG.getNOT(DL, Res, Res.getValueType());
13796       return Res;
13797     }
13798   }
13799
13800   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13801   // widen the cmov and push the truncate through. This avoids introducing a new
13802   // branch during isel and doesn't add any extensions.
13803   if (Op.getValueType() == MVT::i8 &&
13804       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13805     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13806     if (T1.getValueType() == T2.getValueType() &&
13807         // Blacklist CopyFromReg to avoid partial register stalls.
13808         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13809       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13810       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13811       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13812     }
13813   }
13814
13815   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13816   // condition is true.
13817   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13818   SDValue Ops[] = { Op2, Op1, CC, Cond };
13819   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13820 }
13821
13822 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13823                                        SelectionDAG &DAG) {
13824   MVT VT = Op->getSimpleValueType(0);
13825   SDValue In = Op->getOperand(0);
13826   MVT InVT = In.getSimpleValueType();
13827   MVT VTElt = VT.getVectorElementType();
13828   MVT InVTElt = InVT.getVectorElementType();
13829   SDLoc dl(Op);
13830
13831   // SKX processor
13832   if ((InVTElt == MVT::i1) &&
13833       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13834         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13835
13836        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13837         VTElt.getSizeInBits() <= 16)) ||
13838
13839        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13840         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13841
13842        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13843         VTElt.getSizeInBits() >= 32))))
13844     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13845
13846   unsigned int NumElts = VT.getVectorNumElements();
13847
13848   if (NumElts != 8 && NumElts != 16)
13849     return SDValue();
13850
13851   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13852     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13853       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13854     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13855   }
13856
13857   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13858   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13859   SDValue NegOne =
13860    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13861                    ExtVT);
13862   SDValue Zero =
13863    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13864
13865   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13866   if (VT.is512BitVector())
13867     return V;
13868   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13869 }
13870
13871 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13872                                 SelectionDAG &DAG) {
13873   MVT VT = Op->getSimpleValueType(0);
13874   SDValue In = Op->getOperand(0);
13875   MVT InVT = In.getSimpleValueType();
13876   SDLoc dl(Op);
13877
13878   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13879     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13880
13881   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13882       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13883       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13884     return SDValue();
13885
13886   if (Subtarget->hasInt256())
13887     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13888
13889   // Optimize vectors in AVX mode
13890   // Sign extend  v8i16 to v8i32 and
13891   //              v4i32 to v4i64
13892   //
13893   // Divide input vector into two parts
13894   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13895   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13896   // concat the vectors to original VT
13897
13898   unsigned NumElems = InVT.getVectorNumElements();
13899   SDValue Undef = DAG.getUNDEF(InVT);
13900
13901   SmallVector<int,8> ShufMask1(NumElems, -1);
13902   for (unsigned i = 0; i != NumElems/2; ++i)
13903     ShufMask1[i] = i;
13904
13905   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13906
13907   SmallVector<int,8> ShufMask2(NumElems, -1);
13908   for (unsigned i = 0; i != NumElems/2; ++i)
13909     ShufMask2[i] = i + NumElems/2;
13910
13911   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13912
13913   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13914                                 VT.getVectorNumElements()/2);
13915
13916   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13917   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13918
13919   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13920 }
13921
13922 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13923 // may emit an illegal shuffle but the expansion is still better than scalar
13924 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13925 // we'll emit a shuffle and a arithmetic shift.
13926 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13927 // TODO: It is possible to support ZExt by zeroing the undef values during
13928 // the shuffle phase or after the shuffle.
13929 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13930                                  SelectionDAG &DAG) {
13931   MVT RegVT = Op.getSimpleValueType();
13932   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13933   assert(RegVT.isInteger() &&
13934          "We only custom lower integer vector sext loads.");
13935
13936   // Nothing useful we can do without SSE2 shuffles.
13937   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13938
13939   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13940   SDLoc dl(Ld);
13941   EVT MemVT = Ld->getMemoryVT();
13942   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13943   unsigned RegSz = RegVT.getSizeInBits();
13944
13945   ISD::LoadExtType Ext = Ld->getExtensionType();
13946
13947   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13948          && "Only anyext and sext are currently implemented.");
13949   assert(MemVT != RegVT && "Cannot extend to the same type");
13950   assert(MemVT.isVector() && "Must load a vector from memory");
13951
13952   unsigned NumElems = RegVT.getVectorNumElements();
13953   unsigned MemSz = MemVT.getSizeInBits();
13954   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13955
13956   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13957     // The only way in which we have a legal 256-bit vector result but not the
13958     // integer 256-bit operations needed to directly lower a sextload is if we
13959     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13960     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13961     // correctly legalized. We do this late to allow the canonical form of
13962     // sextload to persist throughout the rest of the DAG combiner -- it wants
13963     // to fold together any extensions it can, and so will fuse a sign_extend
13964     // of an sextload into a sextload targeting a wider value.
13965     SDValue Load;
13966     if (MemSz == 128) {
13967       // Just switch this to a normal load.
13968       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13969                                        "it must be a legal 128-bit vector "
13970                                        "type!");
13971       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13972                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13973                   Ld->isInvariant(), Ld->getAlignment());
13974     } else {
13975       assert(MemSz < 128 &&
13976              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13977       // Do an sext load to a 128-bit vector type. We want to use the same
13978       // number of elements, but elements half as wide. This will end up being
13979       // recursively lowered by this routine, but will succeed as we definitely
13980       // have all the necessary features if we're using AVX1.
13981       EVT HalfEltVT =
13982           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13983       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13984       Load =
13985           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13986                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13987                          Ld->isNonTemporal(), Ld->isInvariant(),
13988                          Ld->getAlignment());
13989     }
13990
13991     // Replace chain users with the new chain.
13992     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13993     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13994
13995     // Finally, do a normal sign-extend to the desired register.
13996     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13997   }
13998
13999   // All sizes must be a power of two.
14000   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14001          "Non-power-of-two elements are not custom lowered!");
14002
14003   // Attempt to load the original value using scalar loads.
14004   // Find the largest scalar type that divides the total loaded size.
14005   MVT SclrLoadTy = MVT::i8;
14006   for (MVT Tp : MVT::integer_valuetypes()) {
14007     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14008       SclrLoadTy = Tp;
14009     }
14010   }
14011
14012   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14013   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14014       (64 <= MemSz))
14015     SclrLoadTy = MVT::f64;
14016
14017   // Calculate the number of scalar loads that we need to perform
14018   // in order to load our vector from memory.
14019   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14020
14021   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14022          "Can only lower sext loads with a single scalar load!");
14023
14024   unsigned loadRegZize = RegSz;
14025   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14026     loadRegZize = 128;
14027
14028   // Represent our vector as a sequence of elements which are the
14029   // largest scalar that we can load.
14030   EVT LoadUnitVecVT = EVT::getVectorVT(
14031       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14032
14033   // Represent the data using the same element type that is stored in
14034   // memory. In practice, we ''widen'' MemVT.
14035   EVT WideVecVT =
14036       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14037                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14038
14039   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14040          "Invalid vector type");
14041
14042   // We can't shuffle using an illegal type.
14043   assert(TLI.isTypeLegal(WideVecVT) &&
14044          "We only lower types that form legal widened vector types");
14045
14046   SmallVector<SDValue, 8> Chains;
14047   SDValue Ptr = Ld->getBasePtr();
14048   SDValue Increment =
14049       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14050   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14051
14052   for (unsigned i = 0; i < NumLoads; ++i) {
14053     // Perform a single load.
14054     SDValue ScalarLoad =
14055         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14056                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14057                     Ld->getAlignment());
14058     Chains.push_back(ScalarLoad.getValue(1));
14059     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14060     // another round of DAGCombining.
14061     if (i == 0)
14062       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14063     else
14064       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14065                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14066
14067     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14068   }
14069
14070   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14071
14072   // Bitcast the loaded value to a vector of the original element type, in
14073   // the size of the target vector type.
14074   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14075   unsigned SizeRatio = RegSz / MemSz;
14076
14077   if (Ext == ISD::SEXTLOAD) {
14078     // If we have SSE4.1, we can directly emit a VSEXT node.
14079     if (Subtarget->hasSSE41()) {
14080       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14081       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14082       return Sext;
14083     }
14084
14085     // Otherwise we'll shuffle the small elements in the high bits of the
14086     // larger type and perform an arithmetic shift. If the shift is not legal
14087     // it's better to scalarize.
14088     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14089            "We can't implement a sext load without an arithmetic right shift!");
14090
14091     // Redistribute the loaded elements into the different locations.
14092     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14093     for (unsigned i = 0; i != NumElems; ++i)
14094       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14095
14096     SDValue Shuff = DAG.getVectorShuffle(
14097         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14098
14099     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14100
14101     // Build the arithmetic shift.
14102     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14103                    MemVT.getVectorElementType().getSizeInBits();
14104     Shuff =
14105         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14106                     DAG.getConstant(Amt, dl, RegVT));
14107
14108     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14109     return Shuff;
14110   }
14111
14112   // Redistribute the loaded elements into the different locations.
14113   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14114   for (unsigned i = 0; i != NumElems; ++i)
14115     ShuffleVec[i * SizeRatio] = i;
14116
14117   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14118                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14119
14120   // Bitcast to the requested type.
14121   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14122   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14123   return Shuff;
14124 }
14125
14126 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14127 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14128 // from the AND / OR.
14129 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14130   Opc = Op.getOpcode();
14131   if (Opc != ISD::OR && Opc != ISD::AND)
14132     return false;
14133   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14134           Op.getOperand(0).hasOneUse() &&
14135           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14136           Op.getOperand(1).hasOneUse());
14137 }
14138
14139 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14140 // 1 and that the SETCC node has a single use.
14141 static bool isXor1OfSetCC(SDValue Op) {
14142   if (Op.getOpcode() != ISD::XOR)
14143     return false;
14144   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14145   if (N1C && N1C->getAPIntValue() == 1) {
14146     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14147       Op.getOperand(0).hasOneUse();
14148   }
14149   return false;
14150 }
14151
14152 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14153   bool addTest = true;
14154   SDValue Chain = Op.getOperand(0);
14155   SDValue Cond  = Op.getOperand(1);
14156   SDValue Dest  = Op.getOperand(2);
14157   SDLoc dl(Op);
14158   SDValue CC;
14159   bool Inverted = false;
14160
14161   if (Cond.getOpcode() == ISD::SETCC) {
14162     // Check for setcc([su]{add,sub,mul}o == 0).
14163     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14164         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14165         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14166         Cond.getOperand(0).getResNo() == 1 &&
14167         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14168          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14169          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14170          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14171          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14172          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14173       Inverted = true;
14174       Cond = Cond.getOperand(0);
14175     } else {
14176       SDValue NewCond = LowerSETCC(Cond, DAG);
14177       if (NewCond.getNode())
14178         Cond = NewCond;
14179     }
14180   }
14181 #if 0
14182   // FIXME: LowerXALUO doesn't handle these!!
14183   else if (Cond.getOpcode() == X86ISD::ADD  ||
14184            Cond.getOpcode() == X86ISD::SUB  ||
14185            Cond.getOpcode() == X86ISD::SMUL ||
14186            Cond.getOpcode() == X86ISD::UMUL)
14187     Cond = LowerXALUO(Cond, DAG);
14188 #endif
14189
14190   // Look pass (and (setcc_carry (cmp ...)), 1).
14191   if (Cond.getOpcode() == ISD::AND &&
14192       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14193     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14194     if (C && C->getAPIntValue() == 1)
14195       Cond = Cond.getOperand(0);
14196   }
14197
14198   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14199   // setting operand in place of the X86ISD::SETCC.
14200   unsigned CondOpcode = Cond.getOpcode();
14201   if (CondOpcode == X86ISD::SETCC ||
14202       CondOpcode == X86ISD::SETCC_CARRY) {
14203     CC = Cond.getOperand(0);
14204
14205     SDValue Cmp = Cond.getOperand(1);
14206     unsigned Opc = Cmp.getOpcode();
14207     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14208     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14209       Cond = Cmp;
14210       addTest = false;
14211     } else {
14212       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14213       default: break;
14214       case X86::COND_O:
14215       case X86::COND_B:
14216         // These can only come from an arithmetic instruction with overflow,
14217         // e.g. SADDO, UADDO.
14218         Cond = Cond.getNode()->getOperand(1);
14219         addTest = false;
14220         break;
14221       }
14222     }
14223   }
14224   CondOpcode = Cond.getOpcode();
14225   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14226       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14227       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14228        Cond.getOperand(0).getValueType() != MVT::i8)) {
14229     SDValue LHS = Cond.getOperand(0);
14230     SDValue RHS = Cond.getOperand(1);
14231     unsigned X86Opcode;
14232     unsigned X86Cond;
14233     SDVTList VTs;
14234     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14235     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14236     // X86ISD::INC).
14237     switch (CondOpcode) {
14238     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14239     case ISD::SADDO:
14240       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14241         if (C->isOne()) {
14242           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14243           break;
14244         }
14245       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14246     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14247     case ISD::SSUBO:
14248       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14249         if (C->isOne()) {
14250           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14251           break;
14252         }
14253       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14254     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14255     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14256     default: llvm_unreachable("unexpected overflowing operator");
14257     }
14258     if (Inverted)
14259       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14260     if (CondOpcode == ISD::UMULO)
14261       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14262                           MVT::i32);
14263     else
14264       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14265
14266     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14267
14268     if (CondOpcode == ISD::UMULO)
14269       Cond = X86Op.getValue(2);
14270     else
14271       Cond = X86Op.getValue(1);
14272
14273     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14274     addTest = false;
14275   } else {
14276     unsigned CondOpc;
14277     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14278       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14279       if (CondOpc == ISD::OR) {
14280         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14281         // two branches instead of an explicit OR instruction with a
14282         // separate test.
14283         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14284             isX86LogicalCmp(Cmp)) {
14285           CC = Cond.getOperand(0).getOperand(0);
14286           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14287                               Chain, Dest, CC, Cmp);
14288           CC = Cond.getOperand(1).getOperand(0);
14289           Cond = Cmp;
14290           addTest = false;
14291         }
14292       } else { // ISD::AND
14293         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14294         // two branches instead of an explicit AND instruction with a
14295         // separate test. However, we only do this if this block doesn't
14296         // have a fall-through edge, because this requires an explicit
14297         // jmp when the condition is false.
14298         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14299             isX86LogicalCmp(Cmp) &&
14300             Op.getNode()->hasOneUse()) {
14301           X86::CondCode CCode =
14302             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14303           CCode = X86::GetOppositeBranchCondition(CCode);
14304           CC = DAG.getConstant(CCode, dl, MVT::i8);
14305           SDNode *User = *Op.getNode()->use_begin();
14306           // Look for an unconditional branch following this conditional branch.
14307           // We need this because we need to reverse the successors in order
14308           // to implement FCMP_OEQ.
14309           if (User->getOpcode() == ISD::BR) {
14310             SDValue FalseBB = User->getOperand(1);
14311             SDNode *NewBR =
14312               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14313             assert(NewBR == User);
14314             (void)NewBR;
14315             Dest = FalseBB;
14316
14317             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14318                                 Chain, Dest, CC, Cmp);
14319             X86::CondCode CCode =
14320               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14321             CCode = X86::GetOppositeBranchCondition(CCode);
14322             CC = DAG.getConstant(CCode, dl, MVT::i8);
14323             Cond = Cmp;
14324             addTest = false;
14325           }
14326         }
14327       }
14328     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14329       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14330       // It should be transformed during dag combiner except when the condition
14331       // is set by a arithmetics with overflow node.
14332       X86::CondCode CCode =
14333         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14334       CCode = X86::GetOppositeBranchCondition(CCode);
14335       CC = DAG.getConstant(CCode, dl, MVT::i8);
14336       Cond = Cond.getOperand(0).getOperand(1);
14337       addTest = false;
14338     } else if (Cond.getOpcode() == ISD::SETCC &&
14339                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14340       // For FCMP_OEQ, we can emit
14341       // two branches instead of an explicit AND instruction with a
14342       // separate test. However, we only do this if this block doesn't
14343       // have a fall-through edge, because this requires an explicit
14344       // jmp when the condition is false.
14345       if (Op.getNode()->hasOneUse()) {
14346         SDNode *User = *Op.getNode()->use_begin();
14347         // Look for an unconditional branch following this conditional branch.
14348         // We need this because we need to reverse the successors in order
14349         // to implement FCMP_OEQ.
14350         if (User->getOpcode() == ISD::BR) {
14351           SDValue FalseBB = User->getOperand(1);
14352           SDNode *NewBR =
14353             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14354           assert(NewBR == User);
14355           (void)NewBR;
14356           Dest = FalseBB;
14357
14358           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14359                                     Cond.getOperand(0), Cond.getOperand(1));
14360           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14361           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14362           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14363                               Chain, Dest, CC, Cmp);
14364           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14365           Cond = Cmp;
14366           addTest = false;
14367         }
14368       }
14369     } else if (Cond.getOpcode() == ISD::SETCC &&
14370                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14371       // For FCMP_UNE, we can emit
14372       // two branches instead of an explicit AND instruction with a
14373       // separate test. However, we only do this if this block doesn't
14374       // have a fall-through edge, because this requires an explicit
14375       // jmp when the condition is false.
14376       if (Op.getNode()->hasOneUse()) {
14377         SDNode *User = *Op.getNode()->use_begin();
14378         // Look for an unconditional branch following this conditional branch.
14379         // We need this because we need to reverse the successors in order
14380         // to implement FCMP_UNE.
14381         if (User->getOpcode() == ISD::BR) {
14382           SDValue FalseBB = User->getOperand(1);
14383           SDNode *NewBR =
14384             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14385           assert(NewBR == User);
14386           (void)NewBR;
14387
14388           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14389                                     Cond.getOperand(0), Cond.getOperand(1));
14390           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14391           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14392           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14393                               Chain, Dest, CC, Cmp);
14394           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14395           Cond = Cmp;
14396           addTest = false;
14397           Dest = FalseBB;
14398         }
14399       }
14400     }
14401   }
14402
14403   if (addTest) {
14404     // Look pass the truncate if the high bits are known zero.
14405     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14406         Cond = Cond.getOperand(0);
14407
14408     // We know the result of AND is compared against zero. Try to match
14409     // it to BT.
14410     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14411       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14412       if (NewSetCC.getNode()) {
14413         CC = NewSetCC.getOperand(0);
14414         Cond = NewSetCC.getOperand(1);
14415         addTest = false;
14416       }
14417     }
14418   }
14419
14420   if (addTest) {
14421     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14422     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14423     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14424   }
14425   Cond = ConvertCmpIfNecessary(Cond, DAG);
14426   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14427                      Chain, Dest, CC, Cond);
14428 }
14429
14430 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14431 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14432 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14433 // that the guard pages used by the OS virtual memory manager are allocated in
14434 // correct sequence.
14435 SDValue
14436 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14437                                            SelectionDAG &DAG) const {
14438   MachineFunction &MF = DAG.getMachineFunction();
14439   bool SplitStack = MF.shouldSplitStack();
14440   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14441                SplitStack;
14442   SDLoc dl(Op);
14443
14444   if (!Lower) {
14445     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14446     SDNode* Node = Op.getNode();
14447
14448     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14449     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14450         " not tell us which reg is the stack pointer!");
14451     EVT VT = Node->getValueType(0);
14452     SDValue Tmp1 = SDValue(Node, 0);
14453     SDValue Tmp2 = SDValue(Node, 1);
14454     SDValue Tmp3 = Node->getOperand(2);
14455     SDValue Chain = Tmp1.getOperand(0);
14456
14457     // Chain the dynamic stack allocation so that it doesn't modify the stack
14458     // pointer when other instructions are using the stack.
14459     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14460         SDLoc(Node));
14461
14462     SDValue Size = Tmp2.getOperand(1);
14463     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14464     Chain = SP.getValue(1);
14465     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14466     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14467     unsigned StackAlign = TFI.getStackAlignment();
14468     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14469     if (Align > StackAlign)
14470       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14471           DAG.getConstant(-(uint64_t)Align, dl, VT));
14472     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14473
14474     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14475         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14476         SDLoc(Node));
14477
14478     SDValue Ops[2] = { Tmp1, Tmp2 };
14479     return DAG.getMergeValues(Ops, dl);
14480   }
14481
14482   // Get the inputs.
14483   SDValue Chain = Op.getOperand(0);
14484   SDValue Size  = Op.getOperand(1);
14485   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14486   EVT VT = Op.getNode()->getValueType(0);
14487
14488   bool Is64Bit = Subtarget->is64Bit();
14489   EVT SPTy = getPointerTy();
14490
14491   if (SplitStack) {
14492     MachineRegisterInfo &MRI = MF.getRegInfo();
14493
14494     if (Is64Bit) {
14495       // The 64 bit implementation of segmented stacks needs to clobber both r10
14496       // r11. This makes it impossible to use it along with nested parameters.
14497       const Function *F = MF.getFunction();
14498
14499       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14500            I != E; ++I)
14501         if (I->hasNestAttr())
14502           report_fatal_error("Cannot use segmented stacks with functions that "
14503                              "have nested arguments.");
14504     }
14505
14506     const TargetRegisterClass *AddrRegClass =
14507       getRegClassFor(getPointerTy());
14508     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14509     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14510     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14511                                 DAG.getRegister(Vreg, SPTy));
14512     SDValue Ops1[2] = { Value, Chain };
14513     return DAG.getMergeValues(Ops1, dl);
14514   } else {
14515     SDValue Flag;
14516     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14517
14518     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14519     Flag = Chain.getValue(1);
14520     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14521
14522     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14523
14524     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14525     unsigned SPReg = RegInfo->getStackRegister();
14526     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14527     Chain = SP.getValue(1);
14528
14529     if (Align) {
14530       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14531                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14532       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14533     }
14534
14535     SDValue Ops1[2] = { SP, Chain };
14536     return DAG.getMergeValues(Ops1, dl);
14537   }
14538 }
14539
14540 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14541   MachineFunction &MF = DAG.getMachineFunction();
14542   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14543
14544   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14545   SDLoc DL(Op);
14546
14547   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14548     // vastart just stores the address of the VarArgsFrameIndex slot into the
14549     // memory location argument.
14550     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14551                                    getPointerTy());
14552     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14553                         MachinePointerInfo(SV), false, false, 0);
14554   }
14555
14556   // __va_list_tag:
14557   //   gp_offset         (0 - 6 * 8)
14558   //   fp_offset         (48 - 48 + 8 * 16)
14559   //   overflow_arg_area (point to parameters coming in memory).
14560   //   reg_save_area
14561   SmallVector<SDValue, 8> MemOps;
14562   SDValue FIN = Op.getOperand(1);
14563   // Store gp_offset
14564   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14565                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14566                                                DL, MVT::i32),
14567                                FIN, MachinePointerInfo(SV), false, false, 0);
14568   MemOps.push_back(Store);
14569
14570   // Store fp_offset
14571   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14572                     FIN, DAG.getIntPtrConstant(4, DL));
14573   Store = DAG.getStore(Op.getOperand(0), DL,
14574                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14575                                        MVT::i32),
14576                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14577   MemOps.push_back(Store);
14578
14579   // Store ptr to overflow_arg_area
14580   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14581                     FIN, DAG.getIntPtrConstant(4, DL));
14582   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14583                                     getPointerTy());
14584   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14585                        MachinePointerInfo(SV, 8),
14586                        false, false, 0);
14587   MemOps.push_back(Store);
14588
14589   // Store ptr to reg_save_area.
14590   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14591                     FIN, DAG.getIntPtrConstant(8, DL));
14592   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14593                                     getPointerTy());
14594   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14595                        MachinePointerInfo(SV, 16), false, false, 0);
14596   MemOps.push_back(Store);
14597   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14598 }
14599
14600 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14601   assert(Subtarget->is64Bit() &&
14602          "LowerVAARG only handles 64-bit va_arg!");
14603   assert((Subtarget->isTargetLinux() ||
14604           Subtarget->isTargetDarwin()) &&
14605           "Unhandled target in LowerVAARG");
14606   assert(Op.getNode()->getNumOperands() == 4);
14607   SDValue Chain = Op.getOperand(0);
14608   SDValue SrcPtr = Op.getOperand(1);
14609   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14610   unsigned Align = Op.getConstantOperandVal(3);
14611   SDLoc dl(Op);
14612
14613   EVT ArgVT = Op.getNode()->getValueType(0);
14614   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14615   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14616   uint8_t ArgMode;
14617
14618   // Decide which area this value should be read from.
14619   // TODO: Implement the AMD64 ABI in its entirety. This simple
14620   // selection mechanism works only for the basic types.
14621   if (ArgVT == MVT::f80) {
14622     llvm_unreachable("va_arg for f80 not yet implemented");
14623   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14624     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14625   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14626     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14627   } else {
14628     llvm_unreachable("Unhandled argument type in LowerVAARG");
14629   }
14630
14631   if (ArgMode == 2) {
14632     // Sanity Check: Make sure using fp_offset makes sense.
14633     assert(!Subtarget->useSoftFloat() &&
14634            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14635                Attribute::NoImplicitFloat)) &&
14636            Subtarget->hasSSE1());
14637   }
14638
14639   // Insert VAARG_64 node into the DAG
14640   // VAARG_64 returns two values: Variable Argument Address, Chain
14641   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14642                        DAG.getConstant(ArgMode, dl, MVT::i8),
14643                        DAG.getConstant(Align, dl, MVT::i32)};
14644   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14645   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14646                                           VTs, InstOps, MVT::i64,
14647                                           MachinePointerInfo(SV),
14648                                           /*Align=*/0,
14649                                           /*Volatile=*/false,
14650                                           /*ReadMem=*/true,
14651                                           /*WriteMem=*/true);
14652   Chain = VAARG.getValue(1);
14653
14654   // Load the next argument and return it
14655   return DAG.getLoad(ArgVT, dl,
14656                      Chain,
14657                      VAARG,
14658                      MachinePointerInfo(),
14659                      false, false, false, 0);
14660 }
14661
14662 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14663                            SelectionDAG &DAG) {
14664   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14665   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14666   SDValue Chain = Op.getOperand(0);
14667   SDValue DstPtr = Op.getOperand(1);
14668   SDValue SrcPtr = Op.getOperand(2);
14669   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14670   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14671   SDLoc DL(Op);
14672
14673   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14674                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14675                        false, false,
14676                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14677 }
14678
14679 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14680 // amount is a constant. Takes immediate version of shift as input.
14681 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14682                                           SDValue SrcOp, uint64_t ShiftAmt,
14683                                           SelectionDAG &DAG) {
14684   MVT ElementType = VT.getVectorElementType();
14685
14686   // Fold this packed shift into its first operand if ShiftAmt is 0.
14687   if (ShiftAmt == 0)
14688     return SrcOp;
14689
14690   // Check for ShiftAmt >= element width
14691   if (ShiftAmt >= ElementType.getSizeInBits()) {
14692     if (Opc == X86ISD::VSRAI)
14693       ShiftAmt = ElementType.getSizeInBits() - 1;
14694     else
14695       return DAG.getConstant(0, dl, VT);
14696   }
14697
14698   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14699          && "Unknown target vector shift-by-constant node");
14700
14701   // Fold this packed vector shift into a build vector if SrcOp is a
14702   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14703   if (VT == SrcOp.getSimpleValueType() &&
14704       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14705     SmallVector<SDValue, 8> Elts;
14706     unsigned NumElts = SrcOp->getNumOperands();
14707     ConstantSDNode *ND;
14708
14709     switch(Opc) {
14710     default: llvm_unreachable(nullptr);
14711     case X86ISD::VSHLI:
14712       for (unsigned i=0; i!=NumElts; ++i) {
14713         SDValue CurrentOp = SrcOp->getOperand(i);
14714         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14715           Elts.push_back(CurrentOp);
14716           continue;
14717         }
14718         ND = cast<ConstantSDNode>(CurrentOp);
14719         const APInt &C = ND->getAPIntValue();
14720         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14721       }
14722       break;
14723     case X86ISD::VSRLI:
14724       for (unsigned i=0; i!=NumElts; ++i) {
14725         SDValue CurrentOp = SrcOp->getOperand(i);
14726         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14727           Elts.push_back(CurrentOp);
14728           continue;
14729         }
14730         ND = cast<ConstantSDNode>(CurrentOp);
14731         const APInt &C = ND->getAPIntValue();
14732         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14733       }
14734       break;
14735     case X86ISD::VSRAI:
14736       for (unsigned i=0; i!=NumElts; ++i) {
14737         SDValue CurrentOp = SrcOp->getOperand(i);
14738         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14739           Elts.push_back(CurrentOp);
14740           continue;
14741         }
14742         ND = cast<ConstantSDNode>(CurrentOp);
14743         const APInt &C = ND->getAPIntValue();
14744         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14745       }
14746       break;
14747     }
14748
14749     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14750   }
14751
14752   return DAG.getNode(Opc, dl, VT, SrcOp,
14753                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14754 }
14755
14756 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14757 // may or may not be a constant. Takes immediate version of shift as input.
14758 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14759                                    SDValue SrcOp, SDValue ShAmt,
14760                                    SelectionDAG &DAG) {
14761   MVT SVT = ShAmt.getSimpleValueType();
14762   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14763
14764   // Catch shift-by-constant.
14765   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14766     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14767                                       CShAmt->getZExtValue(), DAG);
14768
14769   // Change opcode to non-immediate version
14770   switch (Opc) {
14771     default: llvm_unreachable("Unknown target vector shift node");
14772     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14773     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14774     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14775   }
14776
14777   const X86Subtarget &Subtarget =
14778       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14779   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14780       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14781     // Let the shuffle legalizer expand this shift amount node.
14782     SDValue Op0 = ShAmt.getOperand(0);
14783     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14784     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14785   } else {
14786     // Need to build a vector containing shift amount.
14787     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14788     SmallVector<SDValue, 4> ShOps;
14789     ShOps.push_back(ShAmt);
14790     if (SVT == MVT::i32) {
14791       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14792       ShOps.push_back(DAG.getUNDEF(SVT));
14793     }
14794     ShOps.push_back(DAG.getUNDEF(SVT));
14795
14796     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14797     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14798   }
14799
14800   // The return type has to be a 128-bit type with the same element
14801   // type as the input type.
14802   MVT EltVT = VT.getVectorElementType();
14803   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14804
14805   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14806   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14807 }
14808
14809 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14810 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14811 /// necessary casting for \p Mask when lowering masking intrinsics.
14812 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14813                                     SDValue PreservedSrc,
14814                                     const X86Subtarget *Subtarget,
14815                                     SelectionDAG &DAG) {
14816     EVT VT = Op.getValueType();
14817     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14818                                   MVT::i1, VT.getVectorNumElements());
14819     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14820                                      Mask.getValueType().getSizeInBits());
14821     SDLoc dl(Op);
14822
14823     assert(MaskVT.isSimple() && "invalid mask type");
14824
14825     if (isAllOnes(Mask))
14826       return Op;
14827
14828     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14829     // are extracted by EXTRACT_SUBVECTOR.
14830     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14831                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14832                               DAG.getIntPtrConstant(0, dl));
14833
14834     switch (Op.getOpcode()) {
14835       default: break;
14836       case X86ISD::PCMPEQM:
14837       case X86ISD::PCMPGTM:
14838       case X86ISD::CMPM:
14839       case X86ISD::CMPMU:
14840         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14841     }
14842     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14843       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14844     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14845 }
14846
14847 /// \brief Creates an SDNode for a predicated scalar operation.
14848 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14849 /// The mask is comming as MVT::i8 and it should be truncated
14850 /// to MVT::i1 while lowering masking intrinsics.
14851 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14852 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14853 /// a scalar instruction.
14854 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14855                                     SDValue PreservedSrc,
14856                                     const X86Subtarget *Subtarget,
14857                                     SelectionDAG &DAG) {
14858     if (isAllOnes(Mask))
14859       return Op;
14860
14861     EVT VT = Op.getValueType();
14862     SDLoc dl(Op);
14863     // The mask should be of type MVT::i1
14864     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14865
14866     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14867       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14868     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14869 }
14870
14871 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14872                                        SelectionDAG &DAG) {
14873   SDLoc dl(Op);
14874   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14875   EVT VT = Op.getValueType();
14876   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14877   if (IntrData) {
14878     switch(IntrData->Type) {
14879     case INTR_TYPE_1OP:
14880       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14881     case INTR_TYPE_2OP:
14882       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14883         Op.getOperand(2));
14884     case INTR_TYPE_3OP:
14885       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14886         Op.getOperand(2), Op.getOperand(3));
14887     case INTR_TYPE_1OP_MASK_RM: {
14888       SDValue Src = Op.getOperand(1);
14889       SDValue Src0 = Op.getOperand(2);
14890       SDValue Mask = Op.getOperand(3);
14891       SDValue RoundingMode = Op.getOperand(4);
14892       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14893                                               RoundingMode),
14894                                   Mask, Src0, Subtarget, DAG);
14895     }
14896     case INTR_TYPE_SCALAR_MASK_RM: {
14897       SDValue Src1 = Op.getOperand(1);
14898       SDValue Src2 = Op.getOperand(2);
14899       SDValue Src0 = Op.getOperand(3);
14900       SDValue Mask = Op.getOperand(4);
14901       // There are 2 kinds of intrinsics in this group:
14902       // (1) With supress-all-exceptions (sae) - 6 operands
14903       // (2) With rounding mode and sae - 7 operands.
14904       if (Op.getNumOperands() == 6) {
14905         SDValue Sae  = Op.getOperand(5);
14906         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14907                                                 Sae),
14908                                     Mask, Src0, Subtarget, DAG);
14909       }
14910       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14911       SDValue RoundingMode  = Op.getOperand(5);
14912       SDValue Sae  = Op.getOperand(6);
14913       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14914                                               RoundingMode, Sae),
14915                                   Mask, Src0, Subtarget, DAG);
14916     }
14917     case INTR_TYPE_2OP_MASK: {
14918       SDValue Src1 = Op.getOperand(1);
14919       SDValue Src2 = Op.getOperand(2);
14920       SDValue PassThru = Op.getOperand(3);
14921       SDValue Mask = Op.getOperand(4);
14922       // We specify 2 possible opcodes for intrinsics with rounding modes.
14923       // First, we check if the intrinsic may have non-default rounding mode,
14924       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14925       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14926       if (IntrWithRoundingModeOpcode != 0) {
14927         SDValue Rnd = Op.getOperand(5);
14928         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14929         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14930           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14931                                       dl, Op.getValueType(),
14932                                       Src1, Src2, Rnd),
14933                                       Mask, PassThru, Subtarget, DAG);
14934         }
14935       }
14936       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14937                                               Src1,Src2),
14938                                   Mask, PassThru, Subtarget, DAG);
14939     }
14940     case FMA_OP_MASK: {
14941       SDValue Src1 = Op.getOperand(1);
14942       SDValue Src2 = Op.getOperand(2);
14943       SDValue Src3 = Op.getOperand(3);
14944       SDValue Mask = Op.getOperand(4);
14945       // We specify 2 possible opcodes for intrinsics with rounding modes.
14946       // First, we check if the intrinsic may have non-default rounding mode,
14947       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14948       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14949       if (IntrWithRoundingModeOpcode != 0) {
14950         SDValue Rnd = Op.getOperand(5);
14951         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14952             X86::STATIC_ROUNDING::CUR_DIRECTION)
14953           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14954                                                   dl, Op.getValueType(),
14955                                                   Src1, Src2, Src3, Rnd),
14956                                       Mask, Src1, Subtarget, DAG);
14957       }
14958       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14959                                               dl, Op.getValueType(),
14960                                               Src1, Src2, Src3),
14961                                   Mask, Src1, Subtarget, DAG);
14962     }
14963     case CMP_MASK:
14964     case CMP_MASK_CC: {
14965       // Comparison intrinsics with masks.
14966       // Example of transformation:
14967       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14968       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14969       // (i8 (bitcast
14970       //   (v8i1 (insert_subvector undef,
14971       //           (v2i1 (and (PCMPEQM %a, %b),
14972       //                      (extract_subvector
14973       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14974       EVT VT = Op.getOperand(1).getValueType();
14975       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14976                                     VT.getVectorNumElements());
14977       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14978       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14979                                        Mask.getValueType().getSizeInBits());
14980       SDValue Cmp;
14981       if (IntrData->Type == CMP_MASK_CC) {
14982         SDValue CC = Op.getOperand(3);
14983         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
14984         // We specify 2 possible opcodes for intrinsics with rounding modes.
14985         // First, we check if the intrinsic may have non-default rounding mode,
14986         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14987         if (IntrData->Opc1 != 0) {
14988           SDValue Rnd = Op.getOperand(5);
14989           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14990               X86::STATIC_ROUNDING::CUR_DIRECTION)
14991             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
14992                               Op.getOperand(2), CC, Rnd);
14993         }
14994         //default rounding mode
14995         if(!Cmp.getNode())
14996             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14997                               Op.getOperand(2), CC);
14998
14999       } else {
15000         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15001         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15002                           Op.getOperand(2));
15003       }
15004       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15005                                              DAG.getTargetConstant(0, dl,
15006                                                                    MaskVT),
15007                                              Subtarget, DAG);
15008       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15009                                 DAG.getUNDEF(BitcastVT), CmpMask,
15010                                 DAG.getIntPtrConstant(0, dl));
15011       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15012     }
15013     case COMI: { // Comparison intrinsics
15014       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15015       SDValue LHS = Op.getOperand(1);
15016       SDValue RHS = Op.getOperand(2);
15017       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15018       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15019       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15020       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15021                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15022       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15023     }
15024     case VSHIFT:
15025       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15026                                  Op.getOperand(1), Op.getOperand(2), DAG);
15027     case VSHIFT_MASK:
15028       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15029                                                       Op.getSimpleValueType(),
15030                                                       Op.getOperand(1),
15031                                                       Op.getOperand(2), DAG),
15032                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15033                                   DAG);
15034     case COMPRESS_EXPAND_IN_REG: {
15035       SDValue Mask = Op.getOperand(3);
15036       SDValue DataToCompress = Op.getOperand(1);
15037       SDValue PassThru = Op.getOperand(2);
15038       if (isAllOnes(Mask)) // return data as is
15039         return Op.getOperand(1);
15040       EVT VT = Op.getValueType();
15041       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15042                                     VT.getVectorNumElements());
15043       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15044                                        Mask.getValueType().getSizeInBits());
15045       SDLoc dl(Op);
15046       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15047                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15048                                   DAG.getIntPtrConstant(0, dl));
15049
15050       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15051                          PassThru);
15052     }
15053     case BLEND: {
15054       SDValue Mask = Op.getOperand(3);
15055       EVT VT = Op.getValueType();
15056       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15057                                     VT.getVectorNumElements());
15058       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15059                                        Mask.getValueType().getSizeInBits());
15060       SDLoc dl(Op);
15061       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15062                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15063                                   DAG.getIntPtrConstant(0, dl));
15064       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15065                          Op.getOperand(2));
15066     }
15067     default:
15068       break;
15069     }
15070   }
15071
15072   switch (IntNo) {
15073   default: return SDValue();    // Don't custom lower most intrinsics.
15074
15075   case Intrinsic::x86_avx2_permd:
15076   case Intrinsic::x86_avx2_permps:
15077     // Operands intentionally swapped. Mask is last operand to intrinsic,
15078     // but second operand for node/instruction.
15079     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15080                        Op.getOperand(2), Op.getOperand(1));
15081
15082   case Intrinsic::x86_avx512_mask_valign_q_512:
15083   case Intrinsic::x86_avx512_mask_valign_d_512:
15084     // Vector source operands are swapped.
15085     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15086                                             Op.getValueType(), Op.getOperand(2),
15087                                             Op.getOperand(1),
15088                                             Op.getOperand(3)),
15089                                 Op.getOperand(5), Op.getOperand(4),
15090                                 Subtarget, DAG);
15091
15092   // ptest and testp intrinsics. The intrinsic these come from are designed to
15093   // return an integer value, not just an instruction so lower it to the ptest
15094   // or testp pattern and a setcc for the result.
15095   case Intrinsic::x86_sse41_ptestz:
15096   case Intrinsic::x86_sse41_ptestc:
15097   case Intrinsic::x86_sse41_ptestnzc:
15098   case Intrinsic::x86_avx_ptestz_256:
15099   case Intrinsic::x86_avx_ptestc_256:
15100   case Intrinsic::x86_avx_ptestnzc_256:
15101   case Intrinsic::x86_avx_vtestz_ps:
15102   case Intrinsic::x86_avx_vtestc_ps:
15103   case Intrinsic::x86_avx_vtestnzc_ps:
15104   case Intrinsic::x86_avx_vtestz_pd:
15105   case Intrinsic::x86_avx_vtestc_pd:
15106   case Intrinsic::x86_avx_vtestnzc_pd:
15107   case Intrinsic::x86_avx_vtestz_ps_256:
15108   case Intrinsic::x86_avx_vtestc_ps_256:
15109   case Intrinsic::x86_avx_vtestnzc_ps_256:
15110   case Intrinsic::x86_avx_vtestz_pd_256:
15111   case Intrinsic::x86_avx_vtestc_pd_256:
15112   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15113     bool IsTestPacked = false;
15114     unsigned X86CC;
15115     switch (IntNo) {
15116     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15117     case Intrinsic::x86_avx_vtestz_ps:
15118     case Intrinsic::x86_avx_vtestz_pd:
15119     case Intrinsic::x86_avx_vtestz_ps_256:
15120     case Intrinsic::x86_avx_vtestz_pd_256:
15121       IsTestPacked = true; // Fallthrough
15122     case Intrinsic::x86_sse41_ptestz:
15123     case Intrinsic::x86_avx_ptestz_256:
15124       // ZF = 1
15125       X86CC = X86::COND_E;
15126       break;
15127     case Intrinsic::x86_avx_vtestc_ps:
15128     case Intrinsic::x86_avx_vtestc_pd:
15129     case Intrinsic::x86_avx_vtestc_ps_256:
15130     case Intrinsic::x86_avx_vtestc_pd_256:
15131       IsTestPacked = true; // Fallthrough
15132     case Intrinsic::x86_sse41_ptestc:
15133     case Intrinsic::x86_avx_ptestc_256:
15134       // CF = 1
15135       X86CC = X86::COND_B;
15136       break;
15137     case Intrinsic::x86_avx_vtestnzc_ps:
15138     case Intrinsic::x86_avx_vtestnzc_pd:
15139     case Intrinsic::x86_avx_vtestnzc_ps_256:
15140     case Intrinsic::x86_avx_vtestnzc_pd_256:
15141       IsTestPacked = true; // Fallthrough
15142     case Intrinsic::x86_sse41_ptestnzc:
15143     case Intrinsic::x86_avx_ptestnzc_256:
15144       // ZF and CF = 0
15145       X86CC = X86::COND_A;
15146       break;
15147     }
15148
15149     SDValue LHS = Op.getOperand(1);
15150     SDValue RHS = Op.getOperand(2);
15151     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15152     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15153     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15154     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15155     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15156   }
15157   case Intrinsic::x86_avx512_kortestz_w:
15158   case Intrinsic::x86_avx512_kortestc_w: {
15159     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15160     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15161     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15162     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15163     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15164     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15165     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15166   }
15167
15168   case Intrinsic::x86_sse42_pcmpistria128:
15169   case Intrinsic::x86_sse42_pcmpestria128:
15170   case Intrinsic::x86_sse42_pcmpistric128:
15171   case Intrinsic::x86_sse42_pcmpestric128:
15172   case Intrinsic::x86_sse42_pcmpistrio128:
15173   case Intrinsic::x86_sse42_pcmpestrio128:
15174   case Intrinsic::x86_sse42_pcmpistris128:
15175   case Intrinsic::x86_sse42_pcmpestris128:
15176   case Intrinsic::x86_sse42_pcmpistriz128:
15177   case Intrinsic::x86_sse42_pcmpestriz128: {
15178     unsigned Opcode;
15179     unsigned X86CC;
15180     switch (IntNo) {
15181     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15182     case Intrinsic::x86_sse42_pcmpistria128:
15183       Opcode = X86ISD::PCMPISTRI;
15184       X86CC = X86::COND_A;
15185       break;
15186     case Intrinsic::x86_sse42_pcmpestria128:
15187       Opcode = X86ISD::PCMPESTRI;
15188       X86CC = X86::COND_A;
15189       break;
15190     case Intrinsic::x86_sse42_pcmpistric128:
15191       Opcode = X86ISD::PCMPISTRI;
15192       X86CC = X86::COND_B;
15193       break;
15194     case Intrinsic::x86_sse42_pcmpestric128:
15195       Opcode = X86ISD::PCMPESTRI;
15196       X86CC = X86::COND_B;
15197       break;
15198     case Intrinsic::x86_sse42_pcmpistrio128:
15199       Opcode = X86ISD::PCMPISTRI;
15200       X86CC = X86::COND_O;
15201       break;
15202     case Intrinsic::x86_sse42_pcmpestrio128:
15203       Opcode = X86ISD::PCMPESTRI;
15204       X86CC = X86::COND_O;
15205       break;
15206     case Intrinsic::x86_sse42_pcmpistris128:
15207       Opcode = X86ISD::PCMPISTRI;
15208       X86CC = X86::COND_S;
15209       break;
15210     case Intrinsic::x86_sse42_pcmpestris128:
15211       Opcode = X86ISD::PCMPESTRI;
15212       X86CC = X86::COND_S;
15213       break;
15214     case Intrinsic::x86_sse42_pcmpistriz128:
15215       Opcode = X86ISD::PCMPISTRI;
15216       X86CC = X86::COND_E;
15217       break;
15218     case Intrinsic::x86_sse42_pcmpestriz128:
15219       Opcode = X86ISD::PCMPESTRI;
15220       X86CC = X86::COND_E;
15221       break;
15222     }
15223     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15224     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15225     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15226     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15227                                 DAG.getConstant(X86CC, dl, MVT::i8),
15228                                 SDValue(PCMP.getNode(), 1));
15229     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15230   }
15231
15232   case Intrinsic::x86_sse42_pcmpistri128:
15233   case Intrinsic::x86_sse42_pcmpestri128: {
15234     unsigned Opcode;
15235     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15236       Opcode = X86ISD::PCMPISTRI;
15237     else
15238       Opcode = X86ISD::PCMPESTRI;
15239
15240     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15241     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15242     return DAG.getNode(Opcode, dl, VTs, NewOps);
15243   }
15244   }
15245 }
15246
15247 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15248                               SDValue Src, SDValue Mask, SDValue Base,
15249                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15250                               const X86Subtarget * Subtarget) {
15251   SDLoc dl(Op);
15252   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15253   assert(C && "Invalid scale type");
15254   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15255   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15256                              Index.getSimpleValueType().getVectorNumElements());
15257   SDValue MaskInReg;
15258   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15259   if (MaskC)
15260     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15261   else
15262     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15263   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15264   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15265   SDValue Segment = DAG.getRegister(0, MVT::i32);
15266   if (Src.getOpcode() == ISD::UNDEF)
15267     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15268   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15269   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15270   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15271   return DAG.getMergeValues(RetOps, dl);
15272 }
15273
15274 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15275                                SDValue Src, SDValue Mask, SDValue Base,
15276                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15277   SDLoc dl(Op);
15278   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15279   assert(C && "Invalid scale type");
15280   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15281   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15282   SDValue Segment = DAG.getRegister(0, MVT::i32);
15283   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15284                              Index.getSimpleValueType().getVectorNumElements());
15285   SDValue MaskInReg;
15286   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15287   if (MaskC)
15288     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15289   else
15290     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15291   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15292   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15293   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15294   return SDValue(Res, 1);
15295 }
15296
15297 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15298                                SDValue Mask, SDValue Base, SDValue Index,
15299                                SDValue ScaleOp, SDValue Chain) {
15300   SDLoc dl(Op);
15301   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15302   assert(C && "Invalid scale type");
15303   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15304   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15305   SDValue Segment = DAG.getRegister(0, MVT::i32);
15306   EVT MaskVT =
15307     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15308   SDValue MaskInReg;
15309   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15310   if (MaskC)
15311     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15312   else
15313     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15314   //SDVTList VTs = DAG.getVTList(MVT::Other);
15315   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15316   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15317   return SDValue(Res, 0);
15318 }
15319
15320 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15321 // read performance monitor counters (x86_rdpmc).
15322 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15323                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15324                               SmallVectorImpl<SDValue> &Results) {
15325   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15326   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15327   SDValue LO, HI;
15328
15329   // The ECX register is used to select the index of the performance counter
15330   // to read.
15331   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15332                                    N->getOperand(2));
15333   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15334
15335   // Reads the content of a 64-bit performance counter and returns it in the
15336   // registers EDX:EAX.
15337   if (Subtarget->is64Bit()) {
15338     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15339     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15340                             LO.getValue(2));
15341   } else {
15342     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15343     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15344                             LO.getValue(2));
15345   }
15346   Chain = HI.getValue(1);
15347
15348   if (Subtarget->is64Bit()) {
15349     // The EAX register is loaded with the low-order 32 bits. The EDX register
15350     // is loaded with the supported high-order bits of the counter.
15351     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15352                               DAG.getConstant(32, DL, MVT::i8));
15353     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15354     Results.push_back(Chain);
15355     return;
15356   }
15357
15358   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15359   SDValue Ops[] = { LO, HI };
15360   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15361   Results.push_back(Pair);
15362   Results.push_back(Chain);
15363 }
15364
15365 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15366 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15367 // also used to custom lower READCYCLECOUNTER nodes.
15368 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15369                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15370                               SmallVectorImpl<SDValue> &Results) {
15371   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15372   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15373   SDValue LO, HI;
15374
15375   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15376   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15377   // and the EAX register is loaded with the low-order 32 bits.
15378   if (Subtarget->is64Bit()) {
15379     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15380     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15381                             LO.getValue(2));
15382   } else {
15383     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15384     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15385                             LO.getValue(2));
15386   }
15387   SDValue Chain = HI.getValue(1);
15388
15389   if (Opcode == X86ISD::RDTSCP_DAG) {
15390     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15391
15392     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15393     // the ECX register. Add 'ecx' explicitly to the chain.
15394     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15395                                      HI.getValue(2));
15396     // Explicitly store the content of ECX at the location passed in input
15397     // to the 'rdtscp' intrinsic.
15398     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15399                          MachinePointerInfo(), false, false, 0);
15400   }
15401
15402   if (Subtarget->is64Bit()) {
15403     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15404     // the EAX register is loaded with the low-order 32 bits.
15405     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15406                               DAG.getConstant(32, DL, MVT::i8));
15407     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15408     Results.push_back(Chain);
15409     return;
15410   }
15411
15412   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15413   SDValue Ops[] = { LO, HI };
15414   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15415   Results.push_back(Pair);
15416   Results.push_back(Chain);
15417 }
15418
15419 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15420                                      SelectionDAG &DAG) {
15421   SmallVector<SDValue, 2> Results;
15422   SDLoc DL(Op);
15423   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15424                           Results);
15425   return DAG.getMergeValues(Results, DL);
15426 }
15427
15428
15429 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15430                                       SelectionDAG &DAG) {
15431   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15432
15433   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15434   if (!IntrData)
15435     return SDValue();
15436
15437   SDLoc dl(Op);
15438   switch(IntrData->Type) {
15439   default:
15440     llvm_unreachable("Unknown Intrinsic Type");
15441     break;
15442   case RDSEED:
15443   case RDRAND: {
15444     // Emit the node with the right value type.
15445     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15446     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15447
15448     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15449     // Otherwise return the value from Rand, which is always 0, casted to i32.
15450     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15451                       DAG.getConstant(1, dl, Op->getValueType(1)),
15452                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15453                       SDValue(Result.getNode(), 1) };
15454     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15455                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15456                                   Ops);
15457
15458     // Return { result, isValid, chain }.
15459     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15460                        SDValue(Result.getNode(), 2));
15461   }
15462   case GATHER: {
15463   //gather(v1, mask, index, base, scale);
15464     SDValue Chain = Op.getOperand(0);
15465     SDValue Src   = Op.getOperand(2);
15466     SDValue Base  = Op.getOperand(3);
15467     SDValue Index = Op.getOperand(4);
15468     SDValue Mask  = Op.getOperand(5);
15469     SDValue Scale = Op.getOperand(6);
15470     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15471                          Chain, Subtarget);
15472   }
15473   case SCATTER: {
15474   //scatter(base, mask, index, v1, scale);
15475     SDValue Chain = Op.getOperand(0);
15476     SDValue Base  = Op.getOperand(2);
15477     SDValue Mask  = Op.getOperand(3);
15478     SDValue Index = Op.getOperand(4);
15479     SDValue Src   = Op.getOperand(5);
15480     SDValue Scale = Op.getOperand(6);
15481     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15482                           Scale, Chain);
15483   }
15484   case PREFETCH: {
15485     SDValue Hint = Op.getOperand(6);
15486     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15487     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15488     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15489     SDValue Chain = Op.getOperand(0);
15490     SDValue Mask  = Op.getOperand(2);
15491     SDValue Index = Op.getOperand(3);
15492     SDValue Base  = Op.getOperand(4);
15493     SDValue Scale = Op.getOperand(5);
15494     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15495   }
15496   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15497   case RDTSC: {
15498     SmallVector<SDValue, 2> Results;
15499     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15500                             Results);
15501     return DAG.getMergeValues(Results, dl);
15502   }
15503   // Read Performance Monitoring Counters.
15504   case RDPMC: {
15505     SmallVector<SDValue, 2> Results;
15506     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15507     return DAG.getMergeValues(Results, dl);
15508   }
15509   // XTEST intrinsics.
15510   case XTEST: {
15511     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15512     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15513     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15514                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15515                                 InTrans);
15516     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15517     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15518                        Ret, SDValue(InTrans.getNode(), 1));
15519   }
15520   // ADC/ADCX/SBB
15521   case ADX: {
15522     SmallVector<SDValue, 2> Results;
15523     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15524     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15525     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15526                                 DAG.getConstant(-1, dl, MVT::i8));
15527     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15528                               Op.getOperand(4), GenCF.getValue(1));
15529     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15530                                  Op.getOperand(5), MachinePointerInfo(),
15531                                  false, false, 0);
15532     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15533                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15534                                 Res.getValue(1));
15535     Results.push_back(SetCC);
15536     Results.push_back(Store);
15537     return DAG.getMergeValues(Results, dl);
15538   }
15539   case COMPRESS_TO_MEM: {
15540     SDLoc dl(Op);
15541     SDValue Mask = Op.getOperand(4);
15542     SDValue DataToCompress = Op.getOperand(3);
15543     SDValue Addr = Op.getOperand(2);
15544     SDValue Chain = Op.getOperand(0);
15545
15546     if (isAllOnes(Mask)) // return just a store
15547       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15548                           MachinePointerInfo(), false, false, 0);
15549
15550     EVT VT = DataToCompress.getValueType();
15551     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15552                                   VT.getVectorNumElements());
15553     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15554                                      Mask.getValueType().getSizeInBits());
15555     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15556                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15557                                 DAG.getIntPtrConstant(0, dl));
15558
15559     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15560                                       DataToCompress, DAG.getUNDEF(VT));
15561     return DAG.getStore(Chain, dl, Compressed, Addr,
15562                         MachinePointerInfo(), false, false, 0);
15563   }
15564   case EXPAND_FROM_MEM: {
15565     SDLoc dl(Op);
15566     SDValue Mask = Op.getOperand(4);
15567     SDValue PathThru = Op.getOperand(3);
15568     SDValue Addr = Op.getOperand(2);
15569     SDValue Chain = Op.getOperand(0);
15570     EVT VT = Op.getValueType();
15571
15572     if (isAllOnes(Mask)) // return just a load
15573       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15574                          false, 0);
15575     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15576                                   VT.getVectorNumElements());
15577     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15578                                      Mask.getValueType().getSizeInBits());
15579     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15580                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15581                                 DAG.getIntPtrConstant(0, dl));
15582
15583     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15584                                    false, false, false, 0);
15585
15586     SDValue Results[] = {
15587         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15588         Chain};
15589     return DAG.getMergeValues(Results, dl);
15590   }
15591   }
15592 }
15593
15594 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15595                                            SelectionDAG &DAG) const {
15596   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15597   MFI->setReturnAddressIsTaken(true);
15598
15599   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15600     return SDValue();
15601
15602   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15603   SDLoc dl(Op);
15604   EVT PtrVT = getPointerTy();
15605
15606   if (Depth > 0) {
15607     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15608     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15609     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15610     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15611                        DAG.getNode(ISD::ADD, dl, PtrVT,
15612                                    FrameAddr, Offset),
15613                        MachinePointerInfo(), false, false, false, 0);
15614   }
15615
15616   // Just load the return address.
15617   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15618   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15619                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15620 }
15621
15622 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15623   MachineFunction &MF = DAG.getMachineFunction();
15624   MachineFrameInfo *MFI = MF.getFrameInfo();
15625   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15626   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15627   EVT VT = Op.getValueType();
15628
15629   MFI->setFrameAddressIsTaken(true);
15630
15631   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15632     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15633     // is not possible to crawl up the stack without looking at the unwind codes
15634     // simultaneously.
15635     int FrameAddrIndex = FuncInfo->getFAIndex();
15636     if (!FrameAddrIndex) {
15637       // Set up a frame object for the return address.
15638       unsigned SlotSize = RegInfo->getSlotSize();
15639       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15640           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
15641       FuncInfo->setFAIndex(FrameAddrIndex);
15642     }
15643     return DAG.getFrameIndex(FrameAddrIndex, VT);
15644   }
15645
15646   unsigned FrameReg =
15647       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15648   SDLoc dl(Op);  // FIXME probably not meaningful
15649   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15650   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15651           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15652          "Invalid Frame Register!");
15653   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15654   while (Depth--)
15655     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15656                             MachinePointerInfo(),
15657                             false, false, false, 0);
15658   return FrameAddr;
15659 }
15660
15661 // FIXME? Maybe this could be a TableGen attribute on some registers and
15662 // this table could be generated automatically from RegInfo.
15663 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15664                                               EVT VT) const {
15665   unsigned Reg = StringSwitch<unsigned>(RegName)
15666                        .Case("esp", X86::ESP)
15667                        .Case("rsp", X86::RSP)
15668                        .Default(0);
15669   if (Reg)
15670     return Reg;
15671   report_fatal_error("Invalid register name global variable");
15672 }
15673
15674 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15675                                                      SelectionDAG &DAG) const {
15676   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15677   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15678 }
15679
15680 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15681   SDValue Chain     = Op.getOperand(0);
15682   SDValue Offset    = Op.getOperand(1);
15683   SDValue Handler   = Op.getOperand(2);
15684   SDLoc dl      (Op);
15685
15686   EVT PtrVT = getPointerTy();
15687   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15688   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15689   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15690           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15691          "Invalid Frame Register!");
15692   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15693   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15694
15695   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15696                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15697                                                        dl));
15698   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15699   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15700                        false, false, 0);
15701   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15702
15703   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15704                      DAG.getRegister(StoreAddrReg, PtrVT));
15705 }
15706
15707 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15708                                                SelectionDAG &DAG) const {
15709   SDLoc DL(Op);
15710   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15711                      DAG.getVTList(MVT::i32, MVT::Other),
15712                      Op.getOperand(0), Op.getOperand(1));
15713 }
15714
15715 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15716                                                 SelectionDAG &DAG) const {
15717   SDLoc DL(Op);
15718   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15719                      Op.getOperand(0), Op.getOperand(1));
15720 }
15721
15722 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15723   return Op.getOperand(0);
15724 }
15725
15726 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15727                                                 SelectionDAG &DAG) const {
15728   SDValue Root = Op.getOperand(0);
15729   SDValue Trmp = Op.getOperand(1); // trampoline
15730   SDValue FPtr = Op.getOperand(2); // nested function
15731   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15732   SDLoc dl (Op);
15733
15734   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15735   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15736
15737   if (Subtarget->is64Bit()) {
15738     SDValue OutChains[6];
15739
15740     // Large code-model.
15741     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15742     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15743
15744     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15745     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15746
15747     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15748
15749     // Load the pointer to the nested function into R11.
15750     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15751     SDValue Addr = Trmp;
15752     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15753                                 Addr, MachinePointerInfo(TrmpAddr),
15754                                 false, false, 0);
15755
15756     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15757                        DAG.getConstant(2, dl, MVT::i64));
15758     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15759                                 MachinePointerInfo(TrmpAddr, 2),
15760                                 false, false, 2);
15761
15762     // Load the 'nest' parameter value into R10.
15763     // R10 is specified in X86CallingConv.td
15764     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15765     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15766                        DAG.getConstant(10, dl, MVT::i64));
15767     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15768                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15769                                 false, false, 0);
15770
15771     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15772                        DAG.getConstant(12, dl, MVT::i64));
15773     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15774                                 MachinePointerInfo(TrmpAddr, 12),
15775                                 false, false, 2);
15776
15777     // Jump to the nested function.
15778     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15779     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15780                        DAG.getConstant(20, dl, MVT::i64));
15781     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15782                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15783                                 false, false, 0);
15784
15785     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15786     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15787                        DAG.getConstant(22, dl, MVT::i64));
15788     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15789                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15790                                 false, false, 0);
15791
15792     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15793   } else {
15794     const Function *Func =
15795       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15796     CallingConv::ID CC = Func->getCallingConv();
15797     unsigned NestReg;
15798
15799     switch (CC) {
15800     default:
15801       llvm_unreachable("Unsupported calling convention");
15802     case CallingConv::C:
15803     case CallingConv::X86_StdCall: {
15804       // Pass 'nest' parameter in ECX.
15805       // Must be kept in sync with X86CallingConv.td
15806       NestReg = X86::ECX;
15807
15808       // Check that ECX wasn't needed by an 'inreg' parameter.
15809       FunctionType *FTy = Func->getFunctionType();
15810       const AttributeSet &Attrs = Func->getAttributes();
15811
15812       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15813         unsigned InRegCount = 0;
15814         unsigned Idx = 1;
15815
15816         for (FunctionType::param_iterator I = FTy->param_begin(),
15817              E = FTy->param_end(); I != E; ++I, ++Idx)
15818           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15819             // FIXME: should only count parameters that are lowered to integers.
15820             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15821
15822         if (InRegCount > 2) {
15823           report_fatal_error("Nest register in use - reduce number of inreg"
15824                              " parameters!");
15825         }
15826       }
15827       break;
15828     }
15829     case CallingConv::X86_FastCall:
15830     case CallingConv::X86_ThisCall:
15831     case CallingConv::Fast:
15832       // Pass 'nest' parameter in EAX.
15833       // Must be kept in sync with X86CallingConv.td
15834       NestReg = X86::EAX;
15835       break;
15836     }
15837
15838     SDValue OutChains[4];
15839     SDValue Addr, Disp;
15840
15841     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15842                        DAG.getConstant(10, dl, MVT::i32));
15843     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15844
15845     // This is storing the opcode for MOV32ri.
15846     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15847     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15848     OutChains[0] = DAG.getStore(Root, dl,
15849                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15850                                 Trmp, MachinePointerInfo(TrmpAddr),
15851                                 false, false, 0);
15852
15853     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15854                        DAG.getConstant(1, dl, MVT::i32));
15855     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15856                                 MachinePointerInfo(TrmpAddr, 1),
15857                                 false, false, 1);
15858
15859     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15860     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15861                        DAG.getConstant(5, dl, MVT::i32));
15862     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15863                                 Addr, MachinePointerInfo(TrmpAddr, 5),
15864                                 false, false, 1);
15865
15866     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15867                        DAG.getConstant(6, dl, MVT::i32));
15868     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15869                                 MachinePointerInfo(TrmpAddr, 6),
15870                                 false, false, 1);
15871
15872     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15873   }
15874 }
15875
15876 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15877                                             SelectionDAG &DAG) const {
15878   /*
15879    The rounding mode is in bits 11:10 of FPSR, and has the following
15880    settings:
15881      00 Round to nearest
15882      01 Round to -inf
15883      10 Round to +inf
15884      11 Round to 0
15885
15886   FLT_ROUNDS, on the other hand, expects the following:
15887     -1 Undefined
15888      0 Round to 0
15889      1 Round to nearest
15890      2 Round to +inf
15891      3 Round to -inf
15892
15893   To perform the conversion, we do:
15894     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15895   */
15896
15897   MachineFunction &MF = DAG.getMachineFunction();
15898   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15899   unsigned StackAlignment = TFI.getStackAlignment();
15900   MVT VT = Op.getSimpleValueType();
15901   SDLoc DL(Op);
15902
15903   // Save FP Control Word to stack slot
15904   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15905   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15906
15907   MachineMemOperand *MMO =
15908    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15909                            MachineMemOperand::MOStore, 2, 2);
15910
15911   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15912   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15913                                           DAG.getVTList(MVT::Other),
15914                                           Ops, MVT::i16, MMO);
15915
15916   // Load FP Control Word from stack slot
15917   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15918                             MachinePointerInfo(), false, false, false, 0);
15919
15920   // Transform as necessary
15921   SDValue CWD1 =
15922     DAG.getNode(ISD::SRL, DL, MVT::i16,
15923                 DAG.getNode(ISD::AND, DL, MVT::i16,
15924                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
15925                 DAG.getConstant(11, DL, MVT::i8));
15926   SDValue CWD2 =
15927     DAG.getNode(ISD::SRL, DL, MVT::i16,
15928                 DAG.getNode(ISD::AND, DL, MVT::i16,
15929                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
15930                 DAG.getConstant(9, DL, MVT::i8));
15931
15932   SDValue RetVal =
15933     DAG.getNode(ISD::AND, DL, MVT::i16,
15934                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15935                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15936                             DAG.getConstant(1, DL, MVT::i16)),
15937                 DAG.getConstant(3, DL, MVT::i16));
15938
15939   return DAG.getNode((VT.getSizeInBits() < 16 ?
15940                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15941 }
15942
15943 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15944   MVT VT = Op.getSimpleValueType();
15945   EVT OpVT = VT;
15946   unsigned NumBits = VT.getSizeInBits();
15947   SDLoc dl(Op);
15948
15949   Op = Op.getOperand(0);
15950   if (VT == MVT::i8) {
15951     // Zero extend to i32 since there is not an i8 bsr.
15952     OpVT = MVT::i32;
15953     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15954   }
15955
15956   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15957   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15958   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15959
15960   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15961   SDValue Ops[] = {
15962     Op,
15963     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
15964     DAG.getConstant(X86::COND_E, dl, MVT::i8),
15965     Op.getValue(1)
15966   };
15967   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15968
15969   // Finally xor with NumBits-1.
15970   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15971                    DAG.getConstant(NumBits - 1, dl, OpVT));
15972
15973   if (VT == MVT::i8)
15974     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15975   return Op;
15976 }
15977
15978 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15979   MVT VT = Op.getSimpleValueType();
15980   EVT OpVT = VT;
15981   unsigned NumBits = VT.getSizeInBits();
15982   SDLoc dl(Op);
15983
15984   Op = Op.getOperand(0);
15985   if (VT == MVT::i8) {
15986     // Zero extend to i32 since there is not an i8 bsr.
15987     OpVT = MVT::i32;
15988     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15989   }
15990
15991   // Issue a bsr (scan bits in reverse).
15992   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15993   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15994
15995   // And xor with NumBits-1.
15996   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15997                    DAG.getConstant(NumBits - 1, dl, OpVT));
15998
15999   if (VT == MVT::i8)
16000     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16001   return Op;
16002 }
16003
16004 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16005   MVT VT = Op.getSimpleValueType();
16006   unsigned NumBits = VT.getSizeInBits();
16007   SDLoc dl(Op);
16008   Op = Op.getOperand(0);
16009
16010   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16011   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16012   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16013
16014   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16015   SDValue Ops[] = {
16016     Op,
16017     DAG.getConstant(NumBits, dl, VT),
16018     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16019     Op.getValue(1)
16020   };
16021   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16022 }
16023
16024 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16025 // ones, and then concatenate the result back.
16026 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16027   MVT VT = Op.getSimpleValueType();
16028
16029   assert(VT.is256BitVector() && VT.isInteger() &&
16030          "Unsupported value type for operation");
16031
16032   unsigned NumElems = VT.getVectorNumElements();
16033   SDLoc dl(Op);
16034
16035   // Extract the LHS vectors
16036   SDValue LHS = Op.getOperand(0);
16037   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16038   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16039
16040   // Extract the RHS vectors
16041   SDValue RHS = Op.getOperand(1);
16042   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16043   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16044
16045   MVT EltVT = VT.getVectorElementType();
16046   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16047
16048   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16049                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16050                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16051 }
16052
16053 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16054   assert(Op.getSimpleValueType().is256BitVector() &&
16055          Op.getSimpleValueType().isInteger() &&
16056          "Only handle AVX 256-bit vector integer operation");
16057   return Lower256IntArith(Op, DAG);
16058 }
16059
16060 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16061   assert(Op.getSimpleValueType().is256BitVector() &&
16062          Op.getSimpleValueType().isInteger() &&
16063          "Only handle AVX 256-bit vector integer operation");
16064   return Lower256IntArith(Op, DAG);
16065 }
16066
16067 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16068                         SelectionDAG &DAG) {
16069   SDLoc dl(Op);
16070   MVT VT = Op.getSimpleValueType();
16071
16072   // Decompose 256-bit ops into smaller 128-bit ops.
16073   if (VT.is256BitVector() && !Subtarget->hasInt256())
16074     return Lower256IntArith(Op, DAG);
16075
16076   SDValue A = Op.getOperand(0);
16077   SDValue B = Op.getOperand(1);
16078
16079   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16080   // pairs, multiply and truncate.
16081   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16082     if (Subtarget->hasInt256()) {
16083       if (VT == MVT::v32i8) {
16084         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16085         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16086         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16087         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16088         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16089         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16090         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16091         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16092                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16093                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16094       }
16095
16096       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16097       return DAG.getNode(
16098           ISD::TRUNCATE, dl, VT,
16099           DAG.getNode(ISD::MUL, dl, ExVT,
16100                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16101                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16102     }
16103
16104     assert(VT == MVT::v16i8 &&
16105            "Pre-AVX2 support only supports v16i8 multiplication");
16106     MVT ExVT = MVT::v8i16;
16107
16108     // Extract the lo parts and sign extend to i16
16109     SDValue ALo, BLo;
16110     if (Subtarget->hasSSE41()) {
16111       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16112       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16113     } else {
16114       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16115                               -1, 4, -1, 5, -1, 6, -1, 7};
16116       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16117       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16118       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16119       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16120       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16121       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16122     }
16123
16124     // Extract the hi parts and sign extend to i16
16125     SDValue AHi, BHi;
16126     if (Subtarget->hasSSE41()) {
16127       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16128                               -1, -1, -1, -1, -1, -1, -1, -1};
16129       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16130       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16131       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16132       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16133     } else {
16134       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16135                               -1, 12, -1, 13, -1, 14, -1, 15};
16136       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16137       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16138       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16139       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16140       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16141       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16142     }
16143
16144     // Multiply, mask the lower 8bits of the lo/hi results and pack
16145     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16146     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16147     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16148     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16149     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16150   }
16151
16152   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16153   if (VT == MVT::v4i32) {
16154     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16155            "Should not custom lower when pmuldq is available!");
16156
16157     // Extract the odd parts.
16158     static const int UnpackMask[] = { 1, -1, 3, -1 };
16159     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16160     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16161
16162     // Multiply the even parts.
16163     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16164     // Now multiply odd parts.
16165     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16166
16167     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16168     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16169
16170     // Merge the two vectors back together with a shuffle. This expands into 2
16171     // shuffles.
16172     static const int ShufMask[] = { 0, 4, 2, 6 };
16173     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16174   }
16175
16176   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16177          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16178
16179   //  Ahi = psrlqi(a, 32);
16180   //  Bhi = psrlqi(b, 32);
16181   //
16182   //  AloBlo = pmuludq(a, b);
16183   //  AloBhi = pmuludq(a, Bhi);
16184   //  AhiBlo = pmuludq(Ahi, b);
16185
16186   //  AloBhi = psllqi(AloBhi, 32);
16187   //  AhiBlo = psllqi(AhiBlo, 32);
16188   //  return AloBlo + AloBhi + AhiBlo;
16189
16190   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16191   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16192
16193   // Bit cast to 32-bit vectors for MULUDQ
16194   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16195                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16196   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16197   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16198   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16199   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16200
16201   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16202   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16203   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16204
16205   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16206   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16207
16208   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16209   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16210 }
16211
16212 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16213   assert(Subtarget->isTargetWin64() && "Unexpected target");
16214   EVT VT = Op.getValueType();
16215   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16216          "Unexpected return type for lowering");
16217
16218   RTLIB::Libcall LC;
16219   bool isSigned;
16220   switch (Op->getOpcode()) {
16221   default: llvm_unreachable("Unexpected request for libcall!");
16222   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16223   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16224   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16225   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16226   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16227   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16228   }
16229
16230   SDLoc dl(Op);
16231   SDValue InChain = DAG.getEntryNode();
16232
16233   TargetLowering::ArgListTy Args;
16234   TargetLowering::ArgListEntry Entry;
16235   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16236     EVT ArgVT = Op->getOperand(i).getValueType();
16237     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16238            "Unexpected argument type for lowering");
16239     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16240     Entry.Node = StackPtr;
16241     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16242                            false, false, 16);
16243     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16244     Entry.Ty = PointerType::get(ArgTy,0);
16245     Entry.isSExt = false;
16246     Entry.isZExt = false;
16247     Args.push_back(Entry);
16248   }
16249
16250   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16251                                          getPointerTy());
16252
16253   TargetLowering::CallLoweringInfo CLI(DAG);
16254   CLI.setDebugLoc(dl).setChain(InChain)
16255     .setCallee(getLibcallCallingConv(LC),
16256                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16257                Callee, std::move(Args), 0)
16258     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16259
16260   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16261   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16262 }
16263
16264 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16265                              SelectionDAG &DAG) {
16266   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16267   EVT VT = Op0.getValueType();
16268   SDLoc dl(Op);
16269
16270   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16271          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16272
16273   // PMULxD operations multiply each even value (starting at 0) of LHS with
16274   // the related value of RHS and produce a widen result.
16275   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16276   // => <2 x i64> <ae|cg>
16277   //
16278   // In other word, to have all the results, we need to perform two PMULxD:
16279   // 1. one with the even values.
16280   // 2. one with the odd values.
16281   // To achieve #2, with need to place the odd values at an even position.
16282   //
16283   // Place the odd value at an even position (basically, shift all values 1
16284   // step to the left):
16285   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16286   // <a|b|c|d> => <b|undef|d|undef>
16287   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16288   // <e|f|g|h> => <f|undef|h|undef>
16289   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16290
16291   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16292   // ints.
16293   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16294   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16295   unsigned Opcode =
16296       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16297   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16298   // => <2 x i64> <ae|cg>
16299   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16300                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16301   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16302   // => <2 x i64> <bf|dh>
16303   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16304                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16305
16306   // Shuffle it back into the right order.
16307   SDValue Highs, Lows;
16308   if (VT == MVT::v8i32) {
16309     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16310     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16311     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16312     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16313   } else {
16314     const int HighMask[] = {1, 5, 3, 7};
16315     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16316     const int LowMask[] = {0, 4, 2, 6};
16317     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16318   }
16319
16320   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16321   // unsigned multiply.
16322   if (IsSigned && !Subtarget->hasSSE41()) {
16323     SDValue ShAmt =
16324         DAG.getConstant(31, dl,
16325                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16326     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16327                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16328     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16329                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16330
16331     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16332     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16333   }
16334
16335   // The first result of MUL_LOHI is actually the low value, followed by the
16336   // high value.
16337   SDValue Ops[] = {Lows, Highs};
16338   return DAG.getMergeValues(Ops, dl);
16339 }
16340
16341 // Return true if the requred (according to Opcode) shift-imm form is natively
16342 // supported by the Subtarget
16343 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget, 
16344                                         unsigned Opcode) {
16345   if (VT.getScalarSizeInBits() < 16)
16346     return false;
16347  
16348   if (VT.is512BitVector() &&
16349       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16350     return true;
16351
16352   bool LShift = VT.is128BitVector() || 
16353     (VT.is256BitVector() && Subtarget->hasInt256());
16354
16355   bool AShift = LShift && (Subtarget->hasVLX() ||
16356     (VT != MVT::v2i64 && VT != MVT::v4i64));
16357   return (Opcode == ISD::SRA) ? AShift : LShift;
16358 }
16359
16360 // The shift amount is a variable, but it is the same for all vector lanes.
16361 // These instrcutions are defined together with shift-immediate.
16362 static 
16363 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget, 
16364                                       unsigned Opcode) {
16365   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16366 }
16367
16368 // Return true if the requred (according to Opcode) variable-shift form is
16369 // natively supported by the Subtarget
16370 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget, 
16371                                     unsigned Opcode) {
16372
16373   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16374     return false;
16375
16376   // vXi16 supported only on AVX-512, BWI
16377   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16378     return false;
16379
16380   if (VT.is512BitVector() || Subtarget->hasVLX())
16381     return true;
16382
16383   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16384   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16385   return (Opcode == ISD::SRA) ? AShift : LShift;
16386 }
16387
16388 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16389                                          const X86Subtarget *Subtarget) {
16390   MVT VT = Op.getSimpleValueType();
16391   SDLoc dl(Op);
16392   SDValue R = Op.getOperand(0);
16393   SDValue Amt = Op.getOperand(1);
16394
16395   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16396     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16397
16398   // Optimize shl/srl/sra with constant shift amount.
16399   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16400     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16401       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16402
16403       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16404         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16405
16406       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16407         unsigned NumElts = VT.getVectorNumElements();
16408         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16409
16410         if (Op.getOpcode() == ISD::SHL) {
16411           // Make a large shift.
16412           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16413                                                    R, ShiftAmt, DAG);
16414           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16415           // Zero out the rightmost bits.
16416           SmallVector<SDValue, 32> V(
16417               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16418           return DAG.getNode(ISD::AND, dl, VT, SHL,
16419                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16420         }
16421         if (Op.getOpcode() == ISD::SRL) {
16422           // Make a large shift.
16423           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16424                                                    R, ShiftAmt, DAG);
16425           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16426           // Zero out the leftmost bits.
16427           SmallVector<SDValue, 32> V(
16428               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16429           return DAG.getNode(ISD::AND, dl, VT, SRL,
16430                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16431         }
16432         if (Op.getOpcode() == ISD::SRA) {
16433           if (ShiftAmt == 7) {
16434             // R s>> 7  ===  R s< 0
16435             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16436             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16437           }
16438
16439           // R s>> a === ((R u>> a) ^ m) - m
16440           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16441           SmallVector<SDValue, 32> V(NumElts,
16442                                      DAG.getConstant(128 >> ShiftAmt, dl,
16443                                                      MVT::i8));
16444           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16445           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16446           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16447           return Res;
16448         }
16449         llvm_unreachable("Unknown shift opcode.");
16450       }
16451     }
16452   }
16453
16454   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16455   if (!Subtarget->is64Bit() &&
16456       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16457       Amt.getOpcode() == ISD::BITCAST &&
16458       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16459     Amt = Amt.getOperand(0);
16460     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16461                      VT.getVectorNumElements();
16462     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16463     uint64_t ShiftAmt = 0;
16464     for (unsigned i = 0; i != Ratio; ++i) {
16465       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16466       if (!C)
16467         return SDValue();
16468       // 6 == Log2(64)
16469       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16470     }
16471     // Check remaining shift amounts.
16472     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16473       uint64_t ShAmt = 0;
16474       for (unsigned j = 0; j != Ratio; ++j) {
16475         ConstantSDNode *C =
16476           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16477         if (!C)
16478           return SDValue();
16479         // 6 == Log2(64)
16480         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16481       }
16482       if (ShAmt != ShiftAmt)
16483         return SDValue();
16484     }
16485     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16486   }
16487
16488   return SDValue();
16489 }
16490
16491 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16492                                         const X86Subtarget* Subtarget) {
16493   MVT VT = Op.getSimpleValueType();
16494   SDLoc dl(Op);
16495   SDValue R = Op.getOperand(0);
16496   SDValue Amt = Op.getOperand(1);
16497
16498   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16499     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16500
16501   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
16502     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
16503
16504   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
16505     SDValue BaseShAmt;
16506     EVT EltVT = VT.getVectorElementType();
16507
16508     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16509       // Check if this build_vector node is doing a splat.
16510       // If so, then set BaseShAmt equal to the splat value.
16511       BaseShAmt = BV->getSplatValue();
16512       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16513         BaseShAmt = SDValue();
16514     } else {
16515       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16516         Amt = Amt.getOperand(0);
16517
16518       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16519       if (SVN && SVN->isSplat()) {
16520         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16521         SDValue InVec = Amt.getOperand(0);
16522         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16523           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16524                  "Unexpected shuffle index found!");
16525           BaseShAmt = InVec.getOperand(SplatIdx);
16526         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16527            if (ConstantSDNode *C =
16528                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16529              if (C->getZExtValue() == SplatIdx)
16530                BaseShAmt = InVec.getOperand(1);
16531            }
16532         }
16533
16534         if (!BaseShAmt)
16535           // Avoid introducing an extract element from a shuffle.
16536           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16537                                   DAG.getIntPtrConstant(SplatIdx, dl));
16538       }
16539     }
16540
16541     if (BaseShAmt.getNode()) {
16542       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16543       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16544         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16545       else if (EltVT.bitsLT(MVT::i32))
16546         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16547
16548       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
16549     }
16550   }
16551
16552   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16553   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16554       Amt.getOpcode() == ISD::BITCAST &&
16555       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16556     Amt = Amt.getOperand(0);
16557     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16558                      VT.getVectorNumElements();
16559     std::vector<SDValue> Vals(Ratio);
16560     for (unsigned i = 0; i != Ratio; ++i)
16561       Vals[i] = Amt.getOperand(i);
16562     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16563       for (unsigned j = 0; j != Ratio; ++j)
16564         if (Vals[j] != Amt.getOperand(i + j))
16565           return SDValue();
16566     }
16567     return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
16568   }
16569   return SDValue();
16570 }
16571
16572 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16573                           SelectionDAG &DAG) {
16574   MVT VT = Op.getSimpleValueType();
16575   SDLoc dl(Op);
16576   SDValue R = Op.getOperand(0);
16577   SDValue Amt = Op.getOperand(1);
16578
16579   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16580   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16581
16582   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16583     return V;
16584
16585   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16586       return V;
16587
16588   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
16589     return Op;
16590
16591   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16592   // shifts per-lane and then shuffle the partial results back together.
16593   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16594     // Splat the shift amounts so the scalar shifts above will catch it.
16595     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16596     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16597     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16598     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16599     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16600   }
16601
16602   // If possible, lower this packed shift into a vector multiply instead of
16603   // expanding it into a sequence of scalar shifts.
16604   // Do this only if the vector shift count is a constant build_vector.
16605   if (Op.getOpcode() == ISD::SHL &&
16606       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16607        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16608       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16609     SmallVector<SDValue, 8> Elts;
16610     EVT SVT = VT.getScalarType();
16611     unsigned SVTBits = SVT.getSizeInBits();
16612     const APInt &One = APInt(SVTBits, 1);
16613     unsigned NumElems = VT.getVectorNumElements();
16614
16615     for (unsigned i=0; i !=NumElems; ++i) {
16616       SDValue Op = Amt->getOperand(i);
16617       if (Op->getOpcode() == ISD::UNDEF) {
16618         Elts.push_back(Op);
16619         continue;
16620       }
16621
16622       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16623       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16624       uint64_t ShAmt = C.getZExtValue();
16625       if (ShAmt >= SVTBits) {
16626         Elts.push_back(DAG.getUNDEF(SVT));
16627         continue;
16628       }
16629       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16630     }
16631     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16632     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16633   }
16634
16635   // Lower SHL with variable shift amount.
16636   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16637     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16638
16639     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16640                      DAG.getConstant(0x3f800000U, dl, VT));
16641     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16642     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16643     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16644   }
16645
16646   // If possible, lower this shift as a sequence of two shifts by
16647   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16648   // Example:
16649   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16650   //
16651   // Could be rewritten as:
16652   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16653   //
16654   // The advantage is that the two shifts from the example would be
16655   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16656   // the vector shift into four scalar shifts plus four pairs of vector
16657   // insert/extract.
16658   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16659       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16660     unsigned TargetOpcode = X86ISD::MOVSS;
16661     bool CanBeSimplified;
16662     // The splat value for the first packed shift (the 'X' from the example).
16663     SDValue Amt1 = Amt->getOperand(0);
16664     // The splat value for the second packed shift (the 'Y' from the example).
16665     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16666                                         Amt->getOperand(2);
16667
16668     // See if it is possible to replace this node with a sequence of
16669     // two shifts followed by a MOVSS/MOVSD
16670     if (VT == MVT::v4i32) {
16671       // Check if it is legal to use a MOVSS.
16672       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16673                         Amt2 == Amt->getOperand(3);
16674       if (!CanBeSimplified) {
16675         // Otherwise, check if we can still simplify this node using a MOVSD.
16676         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16677                           Amt->getOperand(2) == Amt->getOperand(3);
16678         TargetOpcode = X86ISD::MOVSD;
16679         Amt2 = Amt->getOperand(2);
16680       }
16681     } else {
16682       // Do similar checks for the case where the machine value type
16683       // is MVT::v8i16.
16684       CanBeSimplified = Amt1 == Amt->getOperand(1);
16685       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16686         CanBeSimplified = Amt2 == Amt->getOperand(i);
16687
16688       if (!CanBeSimplified) {
16689         TargetOpcode = X86ISD::MOVSD;
16690         CanBeSimplified = true;
16691         Amt2 = Amt->getOperand(4);
16692         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16693           CanBeSimplified = Amt1 == Amt->getOperand(i);
16694         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16695           CanBeSimplified = Amt2 == Amt->getOperand(j);
16696       }
16697     }
16698
16699     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16700         isa<ConstantSDNode>(Amt2)) {
16701       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16702       EVT CastVT = MVT::v4i32;
16703       SDValue Splat1 =
16704         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16705       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16706       SDValue Splat2 =
16707         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16708       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16709       if (TargetOpcode == X86ISD::MOVSD)
16710         CastVT = MVT::v2i64;
16711       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16712       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16713       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16714                                             BitCast1, DAG);
16715       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16716     }
16717   }
16718
16719   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16720     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16721     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16722
16723     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16724     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16725     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16726
16727     // r = VSELECT(r, shl(r, 4), a);
16728     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16729     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16730
16731     // a += a
16732     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16733     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16734     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16735
16736     // r = VSELECT(r, shl(r, 2), a);
16737     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16738     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16739
16740     // a += a
16741     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16742     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16743     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16744
16745     // return VSELECT(r, r+r, a);
16746     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16747                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16748     return R;
16749   }
16750
16751   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16752   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16753   // solution better.
16754   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16755     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16756     unsigned ExtOpc =
16757         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16758     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16759     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16760     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16761                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16762   }
16763
16764   // Decompose 256-bit shifts into smaller 128-bit shifts.
16765   if (VT.is256BitVector()) {
16766     unsigned NumElems = VT.getVectorNumElements();
16767     MVT EltVT = VT.getVectorElementType();
16768     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16769
16770     // Extract the two vectors
16771     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16772     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16773
16774     // Recreate the shift amount vectors
16775     SDValue Amt1, Amt2;
16776     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16777       // Constant shift amount
16778       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16779       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16780       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16781
16782       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16783       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16784     } else {
16785       // Variable shift amount
16786       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16787       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16788     }
16789
16790     // Issue new vector shifts for the smaller types
16791     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16792     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16793
16794     // Concatenate the result back
16795     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16796   }
16797
16798   return SDValue();
16799 }
16800
16801 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16802   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16803   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16804   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16805   // has only one use.
16806   SDNode *N = Op.getNode();
16807   SDValue LHS = N->getOperand(0);
16808   SDValue RHS = N->getOperand(1);
16809   unsigned BaseOp = 0;
16810   unsigned Cond = 0;
16811   SDLoc DL(Op);
16812   switch (Op.getOpcode()) {
16813   default: llvm_unreachable("Unknown ovf instruction!");
16814   case ISD::SADDO:
16815     // A subtract of one will be selected as a INC. Note that INC doesn't
16816     // set CF, so we can't do this for UADDO.
16817     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16818       if (C->isOne()) {
16819         BaseOp = X86ISD::INC;
16820         Cond = X86::COND_O;
16821         break;
16822       }
16823     BaseOp = X86ISD::ADD;
16824     Cond = X86::COND_O;
16825     break;
16826   case ISD::UADDO:
16827     BaseOp = X86ISD::ADD;
16828     Cond = X86::COND_B;
16829     break;
16830   case ISD::SSUBO:
16831     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16832     // set CF, so we can't do this for USUBO.
16833     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16834       if (C->isOne()) {
16835         BaseOp = X86ISD::DEC;
16836         Cond = X86::COND_O;
16837         break;
16838       }
16839     BaseOp = X86ISD::SUB;
16840     Cond = X86::COND_O;
16841     break;
16842   case ISD::USUBO:
16843     BaseOp = X86ISD::SUB;
16844     Cond = X86::COND_B;
16845     break;
16846   case ISD::SMULO:
16847     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16848     Cond = X86::COND_O;
16849     break;
16850   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16851     if (N->getValueType(0) == MVT::i8) {
16852       BaseOp = X86ISD::UMUL8;
16853       Cond = X86::COND_O;
16854       break;
16855     }
16856     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16857                                  MVT::i32);
16858     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16859
16860     SDValue SetCC =
16861       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16862                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
16863                   SDValue(Sum.getNode(), 2));
16864
16865     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16866   }
16867   }
16868
16869   // Also sets EFLAGS.
16870   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16871   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16872
16873   SDValue SetCC =
16874     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16875                 DAG.getConstant(Cond, DL, MVT::i32),
16876                 SDValue(Sum.getNode(), 1));
16877
16878   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16879 }
16880
16881 /// Returns true if the operand type is exactly twice the native width, and
16882 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16883 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16884 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16885 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16886   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16887
16888   if (OpWidth == 64)
16889     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16890   else if (OpWidth == 128)
16891     return Subtarget->hasCmpxchg16b();
16892   else
16893     return false;
16894 }
16895
16896 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16897   return needsCmpXchgNb(SI->getValueOperand()->getType());
16898 }
16899
16900 // Note: this turns large loads into lock cmpxchg8b/16b.
16901 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16902 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16903   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16904   return needsCmpXchgNb(PTy->getElementType());
16905 }
16906
16907 TargetLoweringBase::AtomicRMWExpansionKind
16908 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16909   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16910   const Type *MemType = AI->getType();
16911
16912   // If the operand is too big, we must see if cmpxchg8/16b is available
16913   // and default to library calls otherwise.
16914   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16915     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16916                                    : AtomicRMWExpansionKind::None;
16917   }
16918
16919   AtomicRMWInst::BinOp Op = AI->getOperation();
16920   switch (Op) {
16921   default:
16922     llvm_unreachable("Unknown atomic operation");
16923   case AtomicRMWInst::Xchg:
16924   case AtomicRMWInst::Add:
16925   case AtomicRMWInst::Sub:
16926     // It's better to use xadd, xsub or xchg for these in all cases.
16927     return AtomicRMWExpansionKind::None;
16928   case AtomicRMWInst::Or:
16929   case AtomicRMWInst::And:
16930   case AtomicRMWInst::Xor:
16931     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16932     // prefix to a normal instruction for these operations.
16933     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16934                             : AtomicRMWExpansionKind::None;
16935   case AtomicRMWInst::Nand:
16936   case AtomicRMWInst::Max:
16937   case AtomicRMWInst::Min:
16938   case AtomicRMWInst::UMax:
16939   case AtomicRMWInst::UMin:
16940     // These always require a non-trivial set of data operations on x86. We must
16941     // use a cmpxchg loop.
16942     return AtomicRMWExpansionKind::CmpXChg;
16943   }
16944 }
16945
16946 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16947   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16948   // no-sse2). There isn't any reason to disable it if the target processor
16949   // supports it.
16950   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16951 }
16952
16953 LoadInst *
16954 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16955   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16956   const Type *MemType = AI->getType();
16957   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16958   // there is no benefit in turning such RMWs into loads, and it is actually
16959   // harmful as it introduces a mfence.
16960   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16961     return nullptr;
16962
16963   auto Builder = IRBuilder<>(AI);
16964   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16965   auto SynchScope = AI->getSynchScope();
16966   // We must restrict the ordering to avoid generating loads with Release or
16967   // ReleaseAcquire orderings.
16968   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16969   auto Ptr = AI->getPointerOperand();
16970
16971   // Before the load we need a fence. Here is an example lifted from
16972   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16973   // is required:
16974   // Thread 0:
16975   //   x.store(1, relaxed);
16976   //   r1 = y.fetch_add(0, release);
16977   // Thread 1:
16978   //   y.fetch_add(42, acquire);
16979   //   r2 = x.load(relaxed);
16980   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16981   // lowered to just a load without a fence. A mfence flushes the store buffer,
16982   // making the optimization clearly correct.
16983   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16984   // otherwise, we might be able to be more agressive on relaxed idempotent
16985   // rmw. In practice, they do not look useful, so we don't try to be
16986   // especially clever.
16987   if (SynchScope == SingleThread) {
16988     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16989     // the IR level, so we must wrap it in an intrinsic.
16990     return nullptr;
16991   } else if (hasMFENCE(*Subtarget)) {
16992     Function *MFence = llvm::Intrinsic::getDeclaration(M,
16993             Intrinsic::x86_sse2_mfence);
16994     Builder.CreateCall(MFence);
16995   } else {
16996     // FIXME: it might make sense to use a locked operation here but on a
16997     // different cache-line to prevent cache-line bouncing. In practice it
16998     // is probably a small win, and x86 processors without mfence are rare
16999     // enough that we do not bother.
17000     return nullptr;
17001   }
17002
17003   // Finally we can emit the atomic load.
17004   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17005           AI->getType()->getPrimitiveSizeInBits());
17006   Loaded->setAtomic(Order, SynchScope);
17007   AI->replaceAllUsesWith(Loaded);
17008   AI->eraseFromParent();
17009   return Loaded;
17010 }
17011
17012 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17013                                  SelectionDAG &DAG) {
17014   SDLoc dl(Op);
17015   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17016     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17017   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17018     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17019
17020   // The only fence that needs an instruction is a sequentially-consistent
17021   // cross-thread fence.
17022   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17023     if (hasMFENCE(*Subtarget))
17024       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17025
17026     SDValue Chain = Op.getOperand(0);
17027     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17028     SDValue Ops[] = {
17029       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17030       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17031       DAG.getRegister(0, MVT::i32),            // Index
17032       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17033       DAG.getRegister(0, MVT::i32),            // Segment.
17034       Zero,
17035       Chain
17036     };
17037     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17038     return SDValue(Res, 0);
17039   }
17040
17041   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17042   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17043 }
17044
17045 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17046                              SelectionDAG &DAG) {
17047   MVT T = Op.getSimpleValueType();
17048   SDLoc DL(Op);
17049   unsigned Reg = 0;
17050   unsigned size = 0;
17051   switch(T.SimpleTy) {
17052   default: llvm_unreachable("Invalid value type!");
17053   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17054   case MVT::i16: Reg = X86::AX;  size = 2; break;
17055   case MVT::i32: Reg = X86::EAX; size = 4; break;
17056   case MVT::i64:
17057     assert(Subtarget->is64Bit() && "Node not type legal!");
17058     Reg = X86::RAX; size = 8;
17059     break;
17060   }
17061   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17062                                   Op.getOperand(2), SDValue());
17063   SDValue Ops[] = { cpIn.getValue(0),
17064                     Op.getOperand(1),
17065                     Op.getOperand(3),
17066                     DAG.getTargetConstant(size, DL, MVT::i8),
17067                     cpIn.getValue(1) };
17068   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17069   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17070   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17071                                            Ops, T, MMO);
17072
17073   SDValue cpOut =
17074     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17075   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17076                                       MVT::i32, cpOut.getValue(2));
17077   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17078                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17079                                 EFLAGS);
17080
17081   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17082   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17083   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17084   return SDValue();
17085 }
17086
17087 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17088                             SelectionDAG &DAG) {
17089   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17090   MVT DstVT = Op.getSimpleValueType();
17091
17092   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17093     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17094     if (DstVT != MVT::f64)
17095       // This conversion needs to be expanded.
17096       return SDValue();
17097
17098     SDValue InVec = Op->getOperand(0);
17099     SDLoc dl(Op);
17100     unsigned NumElts = SrcVT.getVectorNumElements();
17101     EVT SVT = SrcVT.getVectorElementType();
17102
17103     // Widen the vector in input in the case of MVT::v2i32.
17104     // Example: from MVT::v2i32 to MVT::v4i32.
17105     SmallVector<SDValue, 16> Elts;
17106     for (unsigned i = 0, e = NumElts; i != e; ++i)
17107       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17108                                  DAG.getIntPtrConstant(i, dl)));
17109
17110     // Explicitly mark the extra elements as Undef.
17111     Elts.append(NumElts, DAG.getUNDEF(SVT));
17112
17113     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17114     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17115     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17116     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17117                        DAG.getIntPtrConstant(0, dl));
17118   }
17119
17120   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17121          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17122   assert((DstVT == MVT::i64 ||
17123           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17124          "Unexpected custom BITCAST");
17125   // i64 <=> MMX conversions are Legal.
17126   if (SrcVT==MVT::i64 && DstVT.isVector())
17127     return Op;
17128   if (DstVT==MVT::i64 && SrcVT.isVector())
17129     return Op;
17130   // MMX <=> MMX conversions are Legal.
17131   if (SrcVT.isVector() && DstVT.isVector())
17132     return Op;
17133   // All other conversions need to be expanded.
17134   return SDValue();
17135 }
17136
17137 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17138                           SelectionDAG &DAG) {
17139   SDNode *Node = Op.getNode();
17140   SDLoc dl(Node);
17141
17142   Op = Op.getOperand(0);
17143   EVT VT = Op.getValueType();
17144   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17145          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17146
17147   unsigned NumElts = VT.getVectorNumElements();
17148   EVT EltVT = VT.getVectorElementType();
17149   unsigned Len = EltVT.getSizeInBits();
17150
17151   // This is the vectorized version of the "best" algorithm from
17152   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17153   // with a minor tweak to use a series of adds + shifts instead of vector
17154   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17155   //
17156   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17157   //  v8i32 => Always profitable
17158   //
17159   // FIXME: There a couple of possible improvements:
17160   //
17161   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17162   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17163   //
17164   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17165          "CTPOP not implemented for this vector element type.");
17166
17167   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17168   // extra legalization.
17169   bool NeedsBitcast = EltVT == MVT::i32;
17170   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17171
17172   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17173                                   EltVT);
17174   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17175                                   EltVT);
17176   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17177                                   EltVT);
17178
17179   // v = v - ((v >> 1) & 0x55555555...)
17180   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17181   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17182   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17183   if (NeedsBitcast)
17184     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17185
17186   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17187   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17188   if (NeedsBitcast)
17189     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17190
17191   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17192   if (VT != And.getValueType())
17193     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17194   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17195
17196   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17197   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17198   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17199   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17200   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17201
17202   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17203   if (NeedsBitcast) {
17204     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17205     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17206     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17207   }
17208
17209   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17210   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17211   if (VT != AndRHS.getValueType()) {
17212     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17213     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17214   }
17215   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17216
17217   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17218   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17219   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17220   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17221   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17222
17223   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17224   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17225   if (NeedsBitcast) {
17226     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17227     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17228   }
17229   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17230   if (VT != And.getValueType())
17231     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17232
17233   // The algorithm mentioned above uses:
17234   //    v = (v * 0x01010101...) >> (Len - 8)
17235   //
17236   // Change it to use vector adds + vector shifts which yield faster results on
17237   // Haswell than using vector integer multiplication.
17238   //
17239   // For i32 elements:
17240   //    v = v + (v >> 8)
17241   //    v = v + (v >> 16)
17242   //
17243   // For i64 elements:
17244   //    v = v + (v >> 8)
17245   //    v = v + (v >> 16)
17246   //    v = v + (v >> 32)
17247   //
17248   Add = And;
17249   SmallVector<SDValue, 8> Csts;
17250   for (unsigned i = 8; i <= Len/2; i *= 2) {
17251     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17252     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17253     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17254     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17255     Csts.clear();
17256   }
17257
17258   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17259   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17260                                   EltVT);
17261   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17262   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17263   if (NeedsBitcast) {
17264     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17265     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17266   }
17267   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17268   if (VT != And.getValueType())
17269     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17270
17271   return And;
17272 }
17273
17274 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17275   SDNode *Node = Op.getNode();
17276   SDLoc dl(Node);
17277   EVT T = Node->getValueType(0);
17278   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17279                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17280   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17281                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17282                        Node->getOperand(0),
17283                        Node->getOperand(1), negOp,
17284                        cast<AtomicSDNode>(Node)->getMemOperand(),
17285                        cast<AtomicSDNode>(Node)->getOrdering(),
17286                        cast<AtomicSDNode>(Node)->getSynchScope());
17287 }
17288
17289 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17290   SDNode *Node = Op.getNode();
17291   SDLoc dl(Node);
17292   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17293
17294   // Convert seq_cst store -> xchg
17295   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17296   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17297   //        (The only way to get a 16-byte store is cmpxchg16b)
17298   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17299   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17300       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17301     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17302                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17303                                  Node->getOperand(0),
17304                                  Node->getOperand(1), Node->getOperand(2),
17305                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17306                                  cast<AtomicSDNode>(Node)->getOrdering(),
17307                                  cast<AtomicSDNode>(Node)->getSynchScope());
17308     return Swap.getValue(1);
17309   }
17310   // Other atomic stores have a simple pattern.
17311   return Op;
17312 }
17313
17314 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17315   EVT VT = Op.getNode()->getSimpleValueType(0);
17316
17317   // Let legalize expand this if it isn't a legal type yet.
17318   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17319     return SDValue();
17320
17321   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17322
17323   unsigned Opc;
17324   bool ExtraOp = false;
17325   switch (Op.getOpcode()) {
17326   default: llvm_unreachable("Invalid code");
17327   case ISD::ADDC: Opc = X86ISD::ADD; break;
17328   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17329   case ISD::SUBC: Opc = X86ISD::SUB; break;
17330   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17331   }
17332
17333   if (!ExtraOp)
17334     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17335                        Op.getOperand(1));
17336   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17337                      Op.getOperand(1), Op.getOperand(2));
17338 }
17339
17340 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17341                             SelectionDAG &DAG) {
17342   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17343
17344   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17345   // which returns the values as { float, float } (in XMM0) or
17346   // { double, double } (which is returned in XMM0, XMM1).
17347   SDLoc dl(Op);
17348   SDValue Arg = Op.getOperand(0);
17349   EVT ArgVT = Arg.getValueType();
17350   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17351
17352   TargetLowering::ArgListTy Args;
17353   TargetLowering::ArgListEntry Entry;
17354
17355   Entry.Node = Arg;
17356   Entry.Ty = ArgTy;
17357   Entry.isSExt = false;
17358   Entry.isZExt = false;
17359   Args.push_back(Entry);
17360
17361   bool isF64 = ArgVT == MVT::f64;
17362   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17363   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17364   // the results are returned via SRet in memory.
17365   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17366   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17367   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17368
17369   Type *RetTy = isF64
17370     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17371     : (Type*)VectorType::get(ArgTy, 4);
17372
17373   TargetLowering::CallLoweringInfo CLI(DAG);
17374   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17375     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17376
17377   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17378
17379   if (isF64)
17380     // Returned in xmm0 and xmm1.
17381     return CallResult.first;
17382
17383   // Returned in bits 0:31 and 32:64 xmm0.
17384   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17385                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17386   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17387                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17388   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17389   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17390 }
17391
17392 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17393                              SelectionDAG &DAG) {
17394   assert(Subtarget->hasAVX512() &&
17395          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17396
17397   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17398   EVT VT = N->getValue().getValueType();
17399   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17400   SDLoc dl(Op);
17401
17402   // X86 scatter kills mask register, so its type should be added to
17403   // the list of return values
17404   if (N->getNumValues() == 1) {
17405     SDValue Index = N->getIndex();
17406     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17407         !Index.getValueType().is512BitVector())
17408       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17409
17410     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17411     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17412                       N->getOperand(3), Index };
17413
17414     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17415     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17416     return SDValue(NewScatter.getNode(), 0);
17417   }
17418   return Op;
17419 }
17420
17421 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17422                             SelectionDAG &DAG) {
17423   assert(Subtarget->hasAVX512() &&
17424          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17425
17426   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17427   EVT VT = Op.getValueType();
17428   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17429   SDLoc dl(Op);
17430
17431   SDValue Index = N->getIndex();
17432   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17433       !Index.getValueType().is512BitVector()) {
17434     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17435     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17436                       N->getOperand(3), Index };
17437     DAG.UpdateNodeOperands(N, Ops);
17438   }
17439   return Op;
17440 }
17441
17442 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17443                                                     SelectionDAG &DAG) const {
17444   // TODO: Eventually, the lowering of these nodes should be informed by or
17445   // deferred to the GC strategy for the function in which they appear. For
17446   // now, however, they must be lowered to something. Since they are logically
17447   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17448   // require special handling for these nodes), lower them as literal NOOPs for
17449   // the time being.
17450   SmallVector<SDValue, 2> Ops;
17451
17452   Ops.push_back(Op.getOperand(0));
17453   if (Op->getGluedNode())
17454     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17455
17456   SDLoc OpDL(Op);
17457   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17458   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17459
17460   return NOOP;
17461 }
17462
17463 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17464                                                   SelectionDAG &DAG) const {
17465   // TODO: Eventually, the lowering of these nodes should be informed by or
17466   // deferred to the GC strategy for the function in which they appear. For
17467   // now, however, they must be lowered to something. Since they are logically
17468   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17469   // require special handling for these nodes), lower them as literal NOOPs for
17470   // the time being.
17471   SmallVector<SDValue, 2> Ops;
17472
17473   Ops.push_back(Op.getOperand(0));
17474   if (Op->getGluedNode())
17475     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17476
17477   SDLoc OpDL(Op);
17478   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17479   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17480
17481   return NOOP;
17482 }
17483
17484 /// LowerOperation - Provide custom lowering hooks for some operations.
17485 ///
17486 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17487   switch (Op.getOpcode()) {
17488   default: llvm_unreachable("Should not custom lower this!");
17489   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17490   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17491     return LowerCMP_SWAP(Op, Subtarget, DAG);
17492   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17493   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17494   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17495   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17496   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17497   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17498   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17499   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17500   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17501   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17502   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17503   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17504   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17505   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17506   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17507   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17508   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17509   case ISD::SHL_PARTS:
17510   case ISD::SRA_PARTS:
17511   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17512   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17513   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17514   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17515   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17516   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17517   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17518   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17519   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17520   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17521   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17522   case ISD::FABS:
17523   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17524   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17525   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17526   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17527   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17528   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17529   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17530   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17531   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17532   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17533   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17534   case ISD::INTRINSIC_VOID:
17535   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17536   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17537   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17538   case ISD::FRAME_TO_ARGS_OFFSET:
17539                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17540   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17541   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17542   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17543   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17544   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17545   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17546   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17547   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17548   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17549   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17550   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17551   case ISD::UMUL_LOHI:
17552   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17553   case ISD::SRA:
17554   case ISD::SRL:
17555   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17556   case ISD::SADDO:
17557   case ISD::UADDO:
17558   case ISD::SSUBO:
17559   case ISD::USUBO:
17560   case ISD::SMULO:
17561   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17562   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17563   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17564   case ISD::ADDC:
17565   case ISD::ADDE:
17566   case ISD::SUBC:
17567   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17568   case ISD::ADD:                return LowerADD(Op, DAG);
17569   case ISD::SUB:                return LowerSUB(Op, DAG);
17570   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17571   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17572   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17573   case ISD::GC_TRANSITION_START:
17574                                 return LowerGC_TRANSITION_START(Op, DAG);
17575   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17576   }
17577 }
17578
17579 /// ReplaceNodeResults - Replace a node with an illegal result type
17580 /// with a new node built out of custom code.
17581 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17582                                            SmallVectorImpl<SDValue>&Results,
17583                                            SelectionDAG &DAG) const {
17584   SDLoc dl(N);
17585   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17586   switch (N->getOpcode()) {
17587   default:
17588     llvm_unreachable("Do not know how to custom type legalize this operation!");
17589   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17590   case X86ISD::FMINC:
17591   case X86ISD::FMIN:
17592   case X86ISD::FMAXC:
17593   case X86ISD::FMAX: {
17594     EVT VT = N->getValueType(0);
17595     if (VT != MVT::v2f32)
17596       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17597     SDValue UNDEF = DAG.getUNDEF(VT);
17598     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17599                               N->getOperand(0), UNDEF);
17600     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17601                               N->getOperand(1), UNDEF);
17602     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17603     return;
17604   }
17605   case ISD::SIGN_EXTEND_INREG:
17606   case ISD::ADDC:
17607   case ISD::ADDE:
17608   case ISD::SUBC:
17609   case ISD::SUBE:
17610     // We don't want to expand or promote these.
17611     return;
17612   case ISD::SDIV:
17613   case ISD::UDIV:
17614   case ISD::SREM:
17615   case ISD::UREM:
17616   case ISD::SDIVREM:
17617   case ISD::UDIVREM: {
17618     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17619     Results.push_back(V);
17620     return;
17621   }
17622   case ISD::FP_TO_SINT:
17623     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
17624     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17625     if (N->getOperand(0).getValueType() == MVT::f16)
17626       break;
17627     // fallthrough
17628   case ISD::FP_TO_UINT: {
17629     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17630
17631     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17632       return;
17633
17634     std::pair<SDValue,SDValue> Vals =
17635         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17636     SDValue FIST = Vals.first, StackSlot = Vals.second;
17637     if (FIST.getNode()) {
17638       EVT VT = N->getValueType(0);
17639       // Return a load from the stack slot.
17640       if (StackSlot.getNode())
17641         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17642                                       MachinePointerInfo(),
17643                                       false, false, false, 0));
17644       else
17645         Results.push_back(FIST);
17646     }
17647     return;
17648   }
17649   case ISD::UINT_TO_FP: {
17650     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17651     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17652         N->getValueType(0) != MVT::v2f32)
17653       return;
17654     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17655                                  N->getOperand(0));
17656     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17657                                      MVT::f64);
17658     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17659     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17660                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17661     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17662     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17663     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17664     return;
17665   }
17666   case ISD::FP_ROUND: {
17667     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17668         return;
17669     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17670     Results.push_back(V);
17671     return;
17672   }
17673   case ISD::FP_EXTEND: {
17674     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17675     // No other ValueType for FP_EXTEND should reach this point.
17676     assert(N->getValueType(0) == MVT::v2f32 &&
17677            "Do not know how to legalize this Node");
17678     return;
17679   }
17680   case ISD::INTRINSIC_W_CHAIN: {
17681     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17682     switch (IntNo) {
17683     default : llvm_unreachable("Do not know how to custom type "
17684                                "legalize this intrinsic operation!");
17685     case Intrinsic::x86_rdtsc:
17686       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17687                                      Results);
17688     case Intrinsic::x86_rdtscp:
17689       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17690                                      Results);
17691     case Intrinsic::x86_rdpmc:
17692       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17693     }
17694   }
17695   case ISD::READCYCLECOUNTER: {
17696     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17697                                    Results);
17698   }
17699   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17700     EVT T = N->getValueType(0);
17701     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17702     bool Regs64bit = T == MVT::i128;
17703     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17704     SDValue cpInL, cpInH;
17705     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17706                         DAG.getConstant(0, dl, HalfT));
17707     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17708                         DAG.getConstant(1, dl, HalfT));
17709     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17710                              Regs64bit ? X86::RAX : X86::EAX,
17711                              cpInL, SDValue());
17712     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17713                              Regs64bit ? X86::RDX : X86::EDX,
17714                              cpInH, cpInL.getValue(1));
17715     SDValue swapInL, swapInH;
17716     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17717                           DAG.getConstant(0, dl, HalfT));
17718     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17719                           DAG.getConstant(1, dl, HalfT));
17720     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17721                                Regs64bit ? X86::RBX : X86::EBX,
17722                                swapInL, cpInH.getValue(1));
17723     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17724                                Regs64bit ? X86::RCX : X86::ECX,
17725                                swapInH, swapInL.getValue(1));
17726     SDValue Ops[] = { swapInH.getValue(0),
17727                       N->getOperand(1),
17728                       swapInH.getValue(1) };
17729     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17730     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17731     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17732                                   X86ISD::LCMPXCHG8_DAG;
17733     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17734     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17735                                         Regs64bit ? X86::RAX : X86::EAX,
17736                                         HalfT, Result.getValue(1));
17737     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17738                                         Regs64bit ? X86::RDX : X86::EDX,
17739                                         HalfT, cpOutL.getValue(2));
17740     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17741
17742     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17743                                         MVT::i32, cpOutH.getValue(2));
17744     SDValue Success =
17745         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17746                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17747     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17748
17749     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17750     Results.push_back(Success);
17751     Results.push_back(EFLAGS.getValue(1));
17752     return;
17753   }
17754   case ISD::ATOMIC_SWAP:
17755   case ISD::ATOMIC_LOAD_ADD:
17756   case ISD::ATOMIC_LOAD_SUB:
17757   case ISD::ATOMIC_LOAD_AND:
17758   case ISD::ATOMIC_LOAD_OR:
17759   case ISD::ATOMIC_LOAD_XOR:
17760   case ISD::ATOMIC_LOAD_NAND:
17761   case ISD::ATOMIC_LOAD_MIN:
17762   case ISD::ATOMIC_LOAD_MAX:
17763   case ISD::ATOMIC_LOAD_UMIN:
17764   case ISD::ATOMIC_LOAD_UMAX:
17765   case ISD::ATOMIC_LOAD: {
17766     // Delegate to generic TypeLegalization. Situations we can really handle
17767     // should have already been dealt with by AtomicExpandPass.cpp.
17768     break;
17769   }
17770   case ISD::BITCAST: {
17771     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17772     EVT DstVT = N->getValueType(0);
17773     EVT SrcVT = N->getOperand(0)->getValueType(0);
17774
17775     if (SrcVT != MVT::f64 ||
17776         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17777       return;
17778
17779     unsigned NumElts = DstVT.getVectorNumElements();
17780     EVT SVT = DstVT.getVectorElementType();
17781     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17782     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17783                                    MVT::v2f64, N->getOperand(0));
17784     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17785
17786     if (ExperimentalVectorWideningLegalization) {
17787       // If we are legalizing vectors by widening, we already have the desired
17788       // legal vector type, just return it.
17789       Results.push_back(ToVecInt);
17790       return;
17791     }
17792
17793     SmallVector<SDValue, 8> Elts;
17794     for (unsigned i = 0, e = NumElts; i != e; ++i)
17795       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17796                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17797
17798     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17799   }
17800   }
17801 }
17802
17803 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17804   switch ((X86ISD::NodeType)Opcode) {
17805   case X86ISD::FIRST_NUMBER:       break;
17806   case X86ISD::BSF:                return "X86ISD::BSF";
17807   case X86ISD::BSR:                return "X86ISD::BSR";
17808   case X86ISD::SHLD:               return "X86ISD::SHLD";
17809   case X86ISD::SHRD:               return "X86ISD::SHRD";
17810   case X86ISD::FAND:               return "X86ISD::FAND";
17811   case X86ISD::FANDN:              return "X86ISD::FANDN";
17812   case X86ISD::FOR:                return "X86ISD::FOR";
17813   case X86ISD::FXOR:               return "X86ISD::FXOR";
17814   case X86ISD::FSRL:               return "X86ISD::FSRL";
17815   case X86ISD::FILD:               return "X86ISD::FILD";
17816   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17817   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17818   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17819   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17820   case X86ISD::FLD:                return "X86ISD::FLD";
17821   case X86ISD::FST:                return "X86ISD::FST";
17822   case X86ISD::CALL:               return "X86ISD::CALL";
17823   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17824   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17825   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17826   case X86ISD::BT:                 return "X86ISD::BT";
17827   case X86ISD::CMP:                return "X86ISD::CMP";
17828   case X86ISD::COMI:               return "X86ISD::COMI";
17829   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17830   case X86ISD::CMPM:               return "X86ISD::CMPM";
17831   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17832   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
17833   case X86ISD::SETCC:              return "X86ISD::SETCC";
17834   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17835   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17836   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
17837   case X86ISD::CMOV:               return "X86ISD::CMOV";
17838   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17839   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17840   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17841   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17842   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17843   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17844   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17845   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
17846   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
17847   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
17848   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17849   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17850   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17851   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17852   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17853   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
17854   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17855   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17856   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17857   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17858   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17859   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
17860   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17861   case X86ISD::HADD:               return "X86ISD::HADD";
17862   case X86ISD::HSUB:               return "X86ISD::HSUB";
17863   case X86ISD::FHADD:              return "X86ISD::FHADD";
17864   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17865   case X86ISD::UMAX:               return "X86ISD::UMAX";
17866   case X86ISD::UMIN:               return "X86ISD::UMIN";
17867   case X86ISD::SMAX:               return "X86ISD::SMAX";
17868   case X86ISD::SMIN:               return "X86ISD::SMIN";
17869   case X86ISD::FMAX:               return "X86ISD::FMAX";
17870   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
17871   case X86ISD::FMIN:               return "X86ISD::FMIN";
17872   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
17873   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17874   case X86ISD::FMINC:              return "X86ISD::FMINC";
17875   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17876   case X86ISD::FRCP:               return "X86ISD::FRCP";
17877   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17878   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17879   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17880   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17881   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17882   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17883   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17884   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17885   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17886   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17887   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17888   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17889   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17890   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17891   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17892   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17893   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17894   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17895   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17896   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17897   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17898   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17899   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17900   case X86ISD::VSHL:               return "X86ISD::VSHL";
17901   case X86ISD::VSRL:               return "X86ISD::VSRL";
17902   case X86ISD::VSRA:               return "X86ISD::VSRA";
17903   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17904   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17905   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17906   case X86ISD::CMPP:               return "X86ISD::CMPP";
17907   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17908   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17909   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17910   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17911   case X86ISD::ADD:                return "X86ISD::ADD";
17912   case X86ISD::SUB:                return "X86ISD::SUB";
17913   case X86ISD::ADC:                return "X86ISD::ADC";
17914   case X86ISD::SBB:                return "X86ISD::SBB";
17915   case X86ISD::SMUL:               return "X86ISD::SMUL";
17916   case X86ISD::UMUL:               return "X86ISD::UMUL";
17917   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17918   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17919   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17920   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17921   case X86ISD::INC:                return "X86ISD::INC";
17922   case X86ISD::DEC:                return "X86ISD::DEC";
17923   case X86ISD::OR:                 return "X86ISD::OR";
17924   case X86ISD::XOR:                return "X86ISD::XOR";
17925   case X86ISD::AND:                return "X86ISD::AND";
17926   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17927   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17928   case X86ISD::PTEST:              return "X86ISD::PTEST";
17929   case X86ISD::TESTP:              return "X86ISD::TESTP";
17930   case X86ISD::TESTM:              return "X86ISD::TESTM";
17931   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17932   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17933   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17934   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17935   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17936   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17937   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17938   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17939   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17940   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17941   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17942   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17943   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17944   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17945   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17946   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17947   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17948   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17949   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17950   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17951   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17952   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17953   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17954   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
17955   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17956   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
17957   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17958   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17959   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17960   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17961   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17962   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17963   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17964   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17965   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17966   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17967   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17968   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17969   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
17970   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
17971   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
17972   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17973   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17974   case X86ISD::SAHF:               return "X86ISD::SAHF";
17975   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17976   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17977   case X86ISD::FMADD:              return "X86ISD::FMADD";
17978   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17979   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17980   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17981   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17982   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17983   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
17984   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
17985   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
17986   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
17987   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
17988   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
17989   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
17990   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17991   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17992   case X86ISD::XTEST:              return "X86ISD::XTEST";
17993   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
17994   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
17995   case X86ISD::SELECT:             return "X86ISD::SELECT";
17996   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
17997   case X86ISD::RCP28:              return "X86ISD::RCP28";
17998   case X86ISD::EXP2:               return "X86ISD::EXP2";
17999   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18000   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18001   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18002   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18003   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18004   case X86ISD::ADDS:               return "X86ISD::ADDS";
18005   case X86ISD::SUBS:               return "X86ISD::SUBS";
18006   }
18007   return nullptr;
18008 }
18009
18010 // isLegalAddressingMode - Return true if the addressing mode represented
18011 // by AM is legal for this target, for a load/store of the specified type.
18012 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18013                                               Type *Ty) const {
18014   // X86 supports extremely general addressing modes.
18015   CodeModel::Model M = getTargetMachine().getCodeModel();
18016   Reloc::Model R = getTargetMachine().getRelocationModel();
18017
18018   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18019   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18020     return false;
18021
18022   if (AM.BaseGV) {
18023     unsigned GVFlags =
18024       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18025
18026     // If a reference to this global requires an extra load, we can't fold it.
18027     if (isGlobalStubReference(GVFlags))
18028       return false;
18029
18030     // If BaseGV requires a register for the PIC base, we cannot also have a
18031     // BaseReg specified.
18032     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18033       return false;
18034
18035     // If lower 4G is not available, then we must use rip-relative addressing.
18036     if ((M != CodeModel::Small || R != Reloc::Static) &&
18037         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18038       return false;
18039   }
18040
18041   switch (AM.Scale) {
18042   case 0:
18043   case 1:
18044   case 2:
18045   case 4:
18046   case 8:
18047     // These scales always work.
18048     break;
18049   case 3:
18050   case 5:
18051   case 9:
18052     // These scales are formed with basereg+scalereg.  Only accept if there is
18053     // no basereg yet.
18054     if (AM.HasBaseReg)
18055       return false;
18056     break;
18057   default:  // Other stuff never works.
18058     return false;
18059   }
18060
18061   return true;
18062 }
18063
18064 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18065   unsigned Bits = Ty->getScalarSizeInBits();
18066
18067   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18068   // particularly cheaper than those without.
18069   if (Bits == 8)
18070     return false;
18071
18072   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18073   // variable shifts just as cheap as scalar ones.
18074   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18075     return false;
18076
18077   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18078   // fully general vector.
18079   return true;
18080 }
18081
18082 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18083   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18084     return false;
18085   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18086   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18087   return NumBits1 > NumBits2;
18088 }
18089
18090 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18091   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18092     return false;
18093
18094   if (!isTypeLegal(EVT::getEVT(Ty1)))
18095     return false;
18096
18097   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18098
18099   // Assuming the caller doesn't have a zeroext or signext return parameter,
18100   // truncation all the way down to i1 is valid.
18101   return true;
18102 }
18103
18104 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18105   return isInt<32>(Imm);
18106 }
18107
18108 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18109   // Can also use sub to handle negated immediates.
18110   return isInt<32>(Imm);
18111 }
18112
18113 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18114   if (!VT1.isInteger() || !VT2.isInteger())
18115     return false;
18116   unsigned NumBits1 = VT1.getSizeInBits();
18117   unsigned NumBits2 = VT2.getSizeInBits();
18118   return NumBits1 > NumBits2;
18119 }
18120
18121 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18122   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18123   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18124 }
18125
18126 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18127   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18128   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18129 }
18130
18131 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18132   EVT VT1 = Val.getValueType();
18133   if (isZExtFree(VT1, VT2))
18134     return true;
18135
18136   if (Val.getOpcode() != ISD::LOAD)
18137     return false;
18138
18139   if (!VT1.isSimple() || !VT1.isInteger() ||
18140       !VT2.isSimple() || !VT2.isInteger())
18141     return false;
18142
18143   switch (VT1.getSimpleVT().SimpleTy) {
18144   default: break;
18145   case MVT::i8:
18146   case MVT::i16:
18147   case MVT::i32:
18148     // X86 has 8, 16, and 32-bit zero-extending loads.
18149     return true;
18150   }
18151
18152   return false;
18153 }
18154
18155 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18156
18157 bool
18158 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18159   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18160     return false;
18161
18162   VT = VT.getScalarType();
18163
18164   if (!VT.isSimple())
18165     return false;
18166
18167   switch (VT.getSimpleVT().SimpleTy) {
18168   case MVT::f32:
18169   case MVT::f64:
18170     return true;
18171   default:
18172     break;
18173   }
18174
18175   return false;
18176 }
18177
18178 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18179   // i16 instructions are longer (0x66 prefix) and potentially slower.
18180   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18181 }
18182
18183 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18184 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18185 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18186 /// are assumed to be legal.
18187 bool
18188 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18189                                       EVT VT) const {
18190   if (!VT.isSimple())
18191     return false;
18192
18193   // Not for i1 vectors
18194   if (VT.getScalarType() == MVT::i1)
18195     return false;
18196
18197   // Very little shuffling can be done for 64-bit vectors right now.
18198   if (VT.getSizeInBits() == 64)
18199     return false;
18200
18201   // We only care that the types being shuffled are legal. The lowering can
18202   // handle any possible shuffle mask that results.
18203   return isTypeLegal(VT.getSimpleVT());
18204 }
18205
18206 bool
18207 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18208                                           EVT VT) const {
18209   // Just delegate to the generic legality, clear masks aren't special.
18210   return isShuffleMaskLegal(Mask, VT);
18211 }
18212
18213 //===----------------------------------------------------------------------===//
18214 //                           X86 Scheduler Hooks
18215 //===----------------------------------------------------------------------===//
18216
18217 /// Utility function to emit xbegin specifying the start of an RTM region.
18218 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18219                                      const TargetInstrInfo *TII) {
18220   DebugLoc DL = MI->getDebugLoc();
18221
18222   const BasicBlock *BB = MBB->getBasicBlock();
18223   MachineFunction::iterator I = MBB;
18224   ++I;
18225
18226   // For the v = xbegin(), we generate
18227   //
18228   // thisMBB:
18229   //  xbegin sinkMBB
18230   //
18231   // mainMBB:
18232   //  eax = -1
18233   //
18234   // sinkMBB:
18235   //  v = eax
18236
18237   MachineBasicBlock *thisMBB = MBB;
18238   MachineFunction *MF = MBB->getParent();
18239   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18240   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18241   MF->insert(I, mainMBB);
18242   MF->insert(I, sinkMBB);
18243
18244   // Transfer the remainder of BB and its successor edges to sinkMBB.
18245   sinkMBB->splice(sinkMBB->begin(), MBB,
18246                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18247   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18248
18249   // thisMBB:
18250   //  xbegin sinkMBB
18251   //  # fallthrough to mainMBB
18252   //  # abortion to sinkMBB
18253   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18254   thisMBB->addSuccessor(mainMBB);
18255   thisMBB->addSuccessor(sinkMBB);
18256
18257   // mainMBB:
18258   //  EAX = -1
18259   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18260   mainMBB->addSuccessor(sinkMBB);
18261
18262   // sinkMBB:
18263   // EAX is live into the sinkMBB
18264   sinkMBB->addLiveIn(X86::EAX);
18265   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18266           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18267     .addReg(X86::EAX);
18268
18269   MI->eraseFromParent();
18270   return sinkMBB;
18271 }
18272
18273 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18274 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18275 // in the .td file.
18276 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18277                                        const TargetInstrInfo *TII) {
18278   unsigned Opc;
18279   switch (MI->getOpcode()) {
18280   default: llvm_unreachable("illegal opcode!");
18281   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18282   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18283   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18284   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18285   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18286   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18287   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18288   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18289   }
18290
18291   DebugLoc dl = MI->getDebugLoc();
18292   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18293
18294   unsigned NumArgs = MI->getNumOperands();
18295   for (unsigned i = 1; i < NumArgs; ++i) {
18296     MachineOperand &Op = MI->getOperand(i);
18297     if (!(Op.isReg() && Op.isImplicit()))
18298       MIB.addOperand(Op);
18299   }
18300   if (MI->hasOneMemOperand())
18301     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18302
18303   BuildMI(*BB, MI, dl,
18304     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18305     .addReg(X86::XMM0);
18306
18307   MI->eraseFromParent();
18308   return BB;
18309 }
18310
18311 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18312 // defs in an instruction pattern
18313 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18314                                        const TargetInstrInfo *TII) {
18315   unsigned Opc;
18316   switch (MI->getOpcode()) {
18317   default: llvm_unreachable("illegal opcode!");
18318   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18319   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18320   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18321   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18322   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18323   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18324   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18325   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18326   }
18327
18328   DebugLoc dl = MI->getDebugLoc();
18329   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18330
18331   unsigned NumArgs = MI->getNumOperands(); // remove the results
18332   for (unsigned i = 1; i < NumArgs; ++i) {
18333     MachineOperand &Op = MI->getOperand(i);
18334     if (!(Op.isReg() && Op.isImplicit()))
18335       MIB.addOperand(Op);
18336   }
18337   if (MI->hasOneMemOperand())
18338     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18339
18340   BuildMI(*BB, MI, dl,
18341     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18342     .addReg(X86::ECX);
18343
18344   MI->eraseFromParent();
18345   return BB;
18346 }
18347
18348 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18349                                       const X86Subtarget *Subtarget) {
18350   DebugLoc dl = MI->getDebugLoc();
18351   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18352   // Address into RAX/EAX, other two args into ECX, EDX.
18353   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18354   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18355   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18356   for (int i = 0; i < X86::AddrNumOperands; ++i)
18357     MIB.addOperand(MI->getOperand(i));
18358
18359   unsigned ValOps = X86::AddrNumOperands;
18360   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18361     .addReg(MI->getOperand(ValOps).getReg());
18362   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18363     .addReg(MI->getOperand(ValOps+1).getReg());
18364
18365   // The instruction doesn't actually take any operands though.
18366   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18367
18368   MI->eraseFromParent(); // The pseudo is gone now.
18369   return BB;
18370 }
18371
18372 MachineBasicBlock *
18373 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18374                                                  MachineBasicBlock *MBB) const {
18375   // Emit va_arg instruction on X86-64.
18376
18377   // Operands to this pseudo-instruction:
18378   // 0  ) Output        : destination address (reg)
18379   // 1-5) Input         : va_list address (addr, i64mem)
18380   // 6  ) ArgSize       : Size (in bytes) of vararg type
18381   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18382   // 8  ) Align         : Alignment of type
18383   // 9  ) EFLAGS (implicit-def)
18384
18385   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18386   static_assert(X86::AddrNumOperands == 5,
18387                 "VAARG_64 assumes 5 address operands");
18388
18389   unsigned DestReg = MI->getOperand(0).getReg();
18390   MachineOperand &Base = MI->getOperand(1);
18391   MachineOperand &Scale = MI->getOperand(2);
18392   MachineOperand &Index = MI->getOperand(3);
18393   MachineOperand &Disp = MI->getOperand(4);
18394   MachineOperand &Segment = MI->getOperand(5);
18395   unsigned ArgSize = MI->getOperand(6).getImm();
18396   unsigned ArgMode = MI->getOperand(7).getImm();
18397   unsigned Align = MI->getOperand(8).getImm();
18398
18399   // Memory Reference
18400   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18401   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18402   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18403
18404   // Machine Information
18405   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18406   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18407   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18408   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18409   DebugLoc DL = MI->getDebugLoc();
18410
18411   // struct va_list {
18412   //   i32   gp_offset
18413   //   i32   fp_offset
18414   //   i64   overflow_area (address)
18415   //   i64   reg_save_area (address)
18416   // }
18417   // sizeof(va_list) = 24
18418   // alignment(va_list) = 8
18419
18420   unsigned TotalNumIntRegs = 6;
18421   unsigned TotalNumXMMRegs = 8;
18422   bool UseGPOffset = (ArgMode == 1);
18423   bool UseFPOffset = (ArgMode == 2);
18424   unsigned MaxOffset = TotalNumIntRegs * 8 +
18425                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18426
18427   /* Align ArgSize to a multiple of 8 */
18428   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18429   bool NeedsAlign = (Align > 8);
18430
18431   MachineBasicBlock *thisMBB = MBB;
18432   MachineBasicBlock *overflowMBB;
18433   MachineBasicBlock *offsetMBB;
18434   MachineBasicBlock *endMBB;
18435
18436   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18437   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18438   unsigned OffsetReg = 0;
18439
18440   if (!UseGPOffset && !UseFPOffset) {
18441     // If we only pull from the overflow region, we don't create a branch.
18442     // We don't need to alter control flow.
18443     OffsetDestReg = 0; // unused
18444     OverflowDestReg = DestReg;
18445
18446     offsetMBB = nullptr;
18447     overflowMBB = thisMBB;
18448     endMBB = thisMBB;
18449   } else {
18450     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18451     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18452     // If not, pull from overflow_area. (branch to overflowMBB)
18453     //
18454     //       thisMBB
18455     //         |     .
18456     //         |        .
18457     //     offsetMBB   overflowMBB
18458     //         |        .
18459     //         |     .
18460     //        endMBB
18461
18462     // Registers for the PHI in endMBB
18463     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18464     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18465
18466     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18467     MachineFunction *MF = MBB->getParent();
18468     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18469     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18470     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18471
18472     MachineFunction::iterator MBBIter = MBB;
18473     ++MBBIter;
18474
18475     // Insert the new basic blocks
18476     MF->insert(MBBIter, offsetMBB);
18477     MF->insert(MBBIter, overflowMBB);
18478     MF->insert(MBBIter, endMBB);
18479
18480     // Transfer the remainder of MBB and its successor edges to endMBB.
18481     endMBB->splice(endMBB->begin(), thisMBB,
18482                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18483     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18484
18485     // Make offsetMBB and overflowMBB successors of thisMBB
18486     thisMBB->addSuccessor(offsetMBB);
18487     thisMBB->addSuccessor(overflowMBB);
18488
18489     // endMBB is a successor of both offsetMBB and overflowMBB
18490     offsetMBB->addSuccessor(endMBB);
18491     overflowMBB->addSuccessor(endMBB);
18492
18493     // Load the offset value into a register
18494     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18495     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18496       .addOperand(Base)
18497       .addOperand(Scale)
18498       .addOperand(Index)
18499       .addDisp(Disp, UseFPOffset ? 4 : 0)
18500       .addOperand(Segment)
18501       .setMemRefs(MMOBegin, MMOEnd);
18502
18503     // Check if there is enough room left to pull this argument.
18504     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18505       .addReg(OffsetReg)
18506       .addImm(MaxOffset + 8 - ArgSizeA8);
18507
18508     // Branch to "overflowMBB" if offset >= max
18509     // Fall through to "offsetMBB" otherwise
18510     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18511       .addMBB(overflowMBB);
18512   }
18513
18514   // In offsetMBB, emit code to use the reg_save_area.
18515   if (offsetMBB) {
18516     assert(OffsetReg != 0);
18517
18518     // Read the reg_save_area address.
18519     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18520     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18521       .addOperand(Base)
18522       .addOperand(Scale)
18523       .addOperand(Index)
18524       .addDisp(Disp, 16)
18525       .addOperand(Segment)
18526       .setMemRefs(MMOBegin, MMOEnd);
18527
18528     // Zero-extend the offset
18529     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18530       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18531         .addImm(0)
18532         .addReg(OffsetReg)
18533         .addImm(X86::sub_32bit);
18534
18535     // Add the offset to the reg_save_area to get the final address.
18536     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18537       .addReg(OffsetReg64)
18538       .addReg(RegSaveReg);
18539
18540     // Compute the offset for the next argument
18541     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18542     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18543       .addReg(OffsetReg)
18544       .addImm(UseFPOffset ? 16 : 8);
18545
18546     // Store it back into the va_list.
18547     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18548       .addOperand(Base)
18549       .addOperand(Scale)
18550       .addOperand(Index)
18551       .addDisp(Disp, UseFPOffset ? 4 : 0)
18552       .addOperand(Segment)
18553       .addReg(NextOffsetReg)
18554       .setMemRefs(MMOBegin, MMOEnd);
18555
18556     // Jump to endMBB
18557     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18558       .addMBB(endMBB);
18559   }
18560
18561   //
18562   // Emit code to use overflow area
18563   //
18564
18565   // Load the overflow_area address into a register.
18566   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18567   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18568     .addOperand(Base)
18569     .addOperand(Scale)
18570     .addOperand(Index)
18571     .addDisp(Disp, 8)
18572     .addOperand(Segment)
18573     .setMemRefs(MMOBegin, MMOEnd);
18574
18575   // If we need to align it, do so. Otherwise, just copy the address
18576   // to OverflowDestReg.
18577   if (NeedsAlign) {
18578     // Align the overflow address
18579     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18580     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18581
18582     // aligned_addr = (addr + (align-1)) & ~(align-1)
18583     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18584       .addReg(OverflowAddrReg)
18585       .addImm(Align-1);
18586
18587     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18588       .addReg(TmpReg)
18589       .addImm(~(uint64_t)(Align-1));
18590   } else {
18591     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18592       .addReg(OverflowAddrReg);
18593   }
18594
18595   // Compute the next overflow address after this argument.
18596   // (the overflow address should be kept 8-byte aligned)
18597   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18598   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18599     .addReg(OverflowDestReg)
18600     .addImm(ArgSizeA8);
18601
18602   // Store the new overflow address.
18603   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18604     .addOperand(Base)
18605     .addOperand(Scale)
18606     .addOperand(Index)
18607     .addDisp(Disp, 8)
18608     .addOperand(Segment)
18609     .addReg(NextAddrReg)
18610     .setMemRefs(MMOBegin, MMOEnd);
18611
18612   // If we branched, emit the PHI to the front of endMBB.
18613   if (offsetMBB) {
18614     BuildMI(*endMBB, endMBB->begin(), DL,
18615             TII->get(X86::PHI), DestReg)
18616       .addReg(OffsetDestReg).addMBB(offsetMBB)
18617       .addReg(OverflowDestReg).addMBB(overflowMBB);
18618   }
18619
18620   // Erase the pseudo instruction
18621   MI->eraseFromParent();
18622
18623   return endMBB;
18624 }
18625
18626 MachineBasicBlock *
18627 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18628                                                  MachineInstr *MI,
18629                                                  MachineBasicBlock *MBB) const {
18630   // Emit code to save XMM registers to the stack. The ABI says that the
18631   // number of registers to save is given in %al, so it's theoretically
18632   // possible to do an indirect jump trick to avoid saving all of them,
18633   // however this code takes a simpler approach and just executes all
18634   // of the stores if %al is non-zero. It's less code, and it's probably
18635   // easier on the hardware branch predictor, and stores aren't all that
18636   // expensive anyway.
18637
18638   // Create the new basic blocks. One block contains all the XMM stores,
18639   // and one block is the final destination regardless of whether any
18640   // stores were performed.
18641   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18642   MachineFunction *F = MBB->getParent();
18643   MachineFunction::iterator MBBIter = MBB;
18644   ++MBBIter;
18645   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18646   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18647   F->insert(MBBIter, XMMSaveMBB);
18648   F->insert(MBBIter, EndMBB);
18649
18650   // Transfer the remainder of MBB and its successor edges to EndMBB.
18651   EndMBB->splice(EndMBB->begin(), MBB,
18652                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18653   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18654
18655   // The original block will now fall through to the XMM save block.
18656   MBB->addSuccessor(XMMSaveMBB);
18657   // The XMMSaveMBB will fall through to the end block.
18658   XMMSaveMBB->addSuccessor(EndMBB);
18659
18660   // Now add the instructions.
18661   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18662   DebugLoc DL = MI->getDebugLoc();
18663
18664   unsigned CountReg = MI->getOperand(0).getReg();
18665   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18666   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18667
18668   if (!Subtarget->isTargetWin64()) {
18669     // If %al is 0, branch around the XMM save block.
18670     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18671     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18672     MBB->addSuccessor(EndMBB);
18673   }
18674
18675   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18676   // that was just emitted, but clearly shouldn't be "saved".
18677   assert((MI->getNumOperands() <= 3 ||
18678           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18679           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18680          && "Expected last argument to be EFLAGS");
18681   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18682   // In the XMM save block, save all the XMM argument registers.
18683   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18684     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18685     MachineMemOperand *MMO =
18686       F->getMachineMemOperand(
18687           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18688         MachineMemOperand::MOStore,
18689         /*Size=*/16, /*Align=*/16);
18690     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18691       .addFrameIndex(RegSaveFrameIndex)
18692       .addImm(/*Scale=*/1)
18693       .addReg(/*IndexReg=*/0)
18694       .addImm(/*Disp=*/Offset)
18695       .addReg(/*Segment=*/0)
18696       .addReg(MI->getOperand(i).getReg())
18697       .addMemOperand(MMO);
18698   }
18699
18700   MI->eraseFromParent();   // The pseudo instruction is gone now.
18701
18702   return EndMBB;
18703 }
18704
18705 // The EFLAGS operand of SelectItr might be missing a kill marker
18706 // because there were multiple uses of EFLAGS, and ISel didn't know
18707 // which to mark. Figure out whether SelectItr should have had a
18708 // kill marker, and set it if it should. Returns the correct kill
18709 // marker value.
18710 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18711                                      MachineBasicBlock* BB,
18712                                      const TargetRegisterInfo* TRI) {
18713   // Scan forward through BB for a use/def of EFLAGS.
18714   MachineBasicBlock::iterator miI(std::next(SelectItr));
18715   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18716     const MachineInstr& mi = *miI;
18717     if (mi.readsRegister(X86::EFLAGS))
18718       return false;
18719     if (mi.definesRegister(X86::EFLAGS))
18720       break; // Should have kill-flag - update below.
18721   }
18722
18723   // If we hit the end of the block, check whether EFLAGS is live into a
18724   // successor.
18725   if (miI == BB->end()) {
18726     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18727                                           sEnd = BB->succ_end();
18728          sItr != sEnd; ++sItr) {
18729       MachineBasicBlock* succ = *sItr;
18730       if (succ->isLiveIn(X86::EFLAGS))
18731         return false;
18732     }
18733   }
18734
18735   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18736   // out. SelectMI should have a kill flag on EFLAGS.
18737   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18738   return true;
18739 }
18740
18741 MachineBasicBlock *
18742 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18743                                      MachineBasicBlock *BB) const {
18744   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18745   DebugLoc DL = MI->getDebugLoc();
18746
18747   // To "insert" a SELECT_CC instruction, we actually have to insert the
18748   // diamond control-flow pattern.  The incoming instruction knows the
18749   // destination vreg to set, the condition code register to branch on, the
18750   // true/false values to select between, and a branch opcode to use.
18751   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18752   MachineFunction::iterator It = BB;
18753   ++It;
18754
18755   //  thisMBB:
18756   //  ...
18757   //   TrueVal = ...
18758   //   cmpTY ccX, r1, r2
18759   //   bCC copy1MBB
18760   //   fallthrough --> copy0MBB
18761   MachineBasicBlock *thisMBB = BB;
18762   MachineFunction *F = BB->getParent();
18763
18764   // We also lower double CMOVs:
18765   //   (CMOV (CMOV F, T, cc1), T, cc2)
18766   // to two successives branches.  For that, we look for another CMOV as the
18767   // following instruction.
18768   //
18769   // Without this, we would add a PHI between the two jumps, which ends up
18770   // creating a few copies all around. For instance, for
18771   //
18772   //    (sitofp (zext (fcmp une)))
18773   //
18774   // we would generate:
18775   //
18776   //         ucomiss %xmm1, %xmm0
18777   //         movss  <1.0f>, %xmm0
18778   //         movaps  %xmm0, %xmm1
18779   //         jne     .LBB5_2
18780   //         xorps   %xmm1, %xmm1
18781   // .LBB5_2:
18782   //         jp      .LBB5_4
18783   //         movaps  %xmm1, %xmm0
18784   // .LBB5_4:
18785   //         retq
18786   //
18787   // because this custom-inserter would have generated:
18788   //
18789   //   A
18790   //   | \
18791   //   |  B
18792   //   | /
18793   //   C
18794   //   | \
18795   //   |  D
18796   //   | /
18797   //   E
18798   //
18799   // A: X = ...; Y = ...
18800   // B: empty
18801   // C: Z = PHI [X, A], [Y, B]
18802   // D: empty
18803   // E: PHI [X, C], [Z, D]
18804   //
18805   // If we lower both CMOVs in a single step, we can instead generate:
18806   //
18807   //   A
18808   //   | \
18809   //   |  C
18810   //   | /|
18811   //   |/ |
18812   //   |  |
18813   //   |  D
18814   //   | /
18815   //   E
18816   //
18817   // A: X = ...; Y = ...
18818   // D: empty
18819   // E: PHI [X, A], [X, C], [Y, D]
18820   //
18821   // Which, in our sitofp/fcmp example, gives us something like:
18822   //
18823   //         ucomiss %xmm1, %xmm0
18824   //         movss  <1.0f>, %xmm0
18825   //         jne     .LBB5_4
18826   //         jp      .LBB5_4
18827   //         xorps   %xmm0, %xmm0
18828   // .LBB5_4:
18829   //         retq
18830   //
18831   MachineInstr *NextCMOV = nullptr;
18832   MachineBasicBlock::iterator NextMIIt =
18833       std::next(MachineBasicBlock::iterator(MI));
18834   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18835       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18836       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18837     NextCMOV = &*NextMIIt;
18838
18839   MachineBasicBlock *jcc1MBB = nullptr;
18840
18841   // If we have a double CMOV, we lower it to two successive branches to
18842   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18843   if (NextCMOV) {
18844     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18845     F->insert(It, jcc1MBB);
18846     jcc1MBB->addLiveIn(X86::EFLAGS);
18847   }
18848
18849   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18850   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18851   F->insert(It, copy0MBB);
18852   F->insert(It, sinkMBB);
18853
18854   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18855   // live into the sink and copy blocks.
18856   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18857
18858   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18859   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18860       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18861     copy0MBB->addLiveIn(X86::EFLAGS);
18862     sinkMBB->addLiveIn(X86::EFLAGS);
18863   }
18864
18865   // Transfer the remainder of BB and its successor edges to sinkMBB.
18866   sinkMBB->splice(sinkMBB->begin(), BB,
18867                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18868   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18869
18870   // Add the true and fallthrough blocks as its successors.
18871   if (NextCMOV) {
18872     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18873     BB->addSuccessor(jcc1MBB);
18874
18875     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18876     // jump to the sinkMBB.
18877     jcc1MBB->addSuccessor(copy0MBB);
18878     jcc1MBB->addSuccessor(sinkMBB);
18879   } else {
18880     BB->addSuccessor(copy0MBB);
18881   }
18882
18883   // The true block target of the first (or only) branch is always sinkMBB.
18884   BB->addSuccessor(sinkMBB);
18885
18886   // Create the conditional branch instruction.
18887   unsigned Opc =
18888     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18889   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18890
18891   if (NextCMOV) {
18892     unsigned Opc2 = X86::GetCondBranchFromCond(
18893         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18894     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18895   }
18896
18897   //  copy0MBB:
18898   //   %FalseValue = ...
18899   //   # fallthrough to sinkMBB
18900   copy0MBB->addSuccessor(sinkMBB);
18901
18902   //  sinkMBB:
18903   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18904   //  ...
18905   MachineInstrBuilder MIB =
18906       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18907               MI->getOperand(0).getReg())
18908           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18909           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18910
18911   // If we have a double CMOV, the second Jcc provides the same incoming
18912   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18913   if (NextCMOV) {
18914     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18915     // Copy the PHI result to the register defined by the second CMOV.
18916     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18917             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18918         .addReg(MI->getOperand(0).getReg());
18919     NextCMOV->eraseFromParent();
18920   }
18921
18922   MI->eraseFromParent();   // The pseudo instruction is gone now.
18923   return sinkMBB;
18924 }
18925
18926 MachineBasicBlock *
18927 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18928                                         MachineBasicBlock *BB) const {
18929   MachineFunction *MF = BB->getParent();
18930   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18931   DebugLoc DL = MI->getDebugLoc();
18932   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18933
18934   assert(MF->shouldSplitStack());
18935
18936   const bool Is64Bit = Subtarget->is64Bit();
18937   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18938
18939   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18940   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18941
18942   // BB:
18943   //  ... [Till the alloca]
18944   // If stacklet is not large enough, jump to mallocMBB
18945   //
18946   // bumpMBB:
18947   //  Allocate by subtracting from RSP
18948   //  Jump to continueMBB
18949   //
18950   // mallocMBB:
18951   //  Allocate by call to runtime
18952   //
18953   // continueMBB:
18954   //  ...
18955   //  [rest of original BB]
18956   //
18957
18958   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18959   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18960   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18961
18962   MachineRegisterInfo &MRI = MF->getRegInfo();
18963   const TargetRegisterClass *AddrRegClass =
18964     getRegClassFor(getPointerTy());
18965
18966   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18967     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18968     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18969     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18970     sizeVReg = MI->getOperand(1).getReg(),
18971     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18972
18973   MachineFunction::iterator MBBIter = BB;
18974   ++MBBIter;
18975
18976   MF->insert(MBBIter, bumpMBB);
18977   MF->insert(MBBIter, mallocMBB);
18978   MF->insert(MBBIter, continueMBB);
18979
18980   continueMBB->splice(continueMBB->begin(), BB,
18981                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18982   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18983
18984   // Add code to the main basic block to check if the stack limit has been hit,
18985   // and if so, jump to mallocMBB otherwise to bumpMBB.
18986   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18987   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18988     .addReg(tmpSPVReg).addReg(sizeVReg);
18989   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18990     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18991     .addReg(SPLimitVReg);
18992   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18993
18994   // bumpMBB simply decreases the stack pointer, since we know the current
18995   // stacklet has enough space.
18996   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18997     .addReg(SPLimitVReg);
18998   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18999     .addReg(SPLimitVReg);
19000   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19001
19002   // Calls into a routine in libgcc to allocate more space from the heap.
19003   const uint32_t *RegMask =
19004       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19005   if (IsLP64) {
19006     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19007       .addReg(sizeVReg);
19008     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19009       .addExternalSymbol("__morestack_allocate_stack_space")
19010       .addRegMask(RegMask)
19011       .addReg(X86::RDI, RegState::Implicit)
19012       .addReg(X86::RAX, RegState::ImplicitDefine);
19013   } else if (Is64Bit) {
19014     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19015       .addReg(sizeVReg);
19016     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19017       .addExternalSymbol("__morestack_allocate_stack_space")
19018       .addRegMask(RegMask)
19019       .addReg(X86::EDI, RegState::Implicit)
19020       .addReg(X86::EAX, RegState::ImplicitDefine);
19021   } else {
19022     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19023       .addImm(12);
19024     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19025     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19026       .addExternalSymbol("__morestack_allocate_stack_space")
19027       .addRegMask(RegMask)
19028       .addReg(X86::EAX, RegState::ImplicitDefine);
19029   }
19030
19031   if (!Is64Bit)
19032     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19033       .addImm(16);
19034
19035   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19036     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19037   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19038
19039   // Set up the CFG correctly.
19040   BB->addSuccessor(bumpMBB);
19041   BB->addSuccessor(mallocMBB);
19042   mallocMBB->addSuccessor(continueMBB);
19043   bumpMBB->addSuccessor(continueMBB);
19044
19045   // Take care of the PHI nodes.
19046   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19047           MI->getOperand(0).getReg())
19048     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19049     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19050
19051   // Delete the original pseudo instruction.
19052   MI->eraseFromParent();
19053
19054   // And we're done.
19055   return continueMBB;
19056 }
19057
19058 MachineBasicBlock *
19059 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19060                                         MachineBasicBlock *BB) const {
19061   DebugLoc DL = MI->getDebugLoc();
19062
19063   assert(!Subtarget->isTargetMachO());
19064
19065   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19066
19067   MI->eraseFromParent();   // The pseudo instruction is gone now.
19068   return BB;
19069 }
19070
19071 MachineBasicBlock *
19072 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19073                                       MachineBasicBlock *BB) const {
19074   // This is pretty easy.  We're taking the value that we received from
19075   // our load from the relocation, sticking it in either RDI (x86-64)
19076   // or EAX and doing an indirect call.  The return value will then
19077   // be in the normal return register.
19078   MachineFunction *F = BB->getParent();
19079   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19080   DebugLoc DL = MI->getDebugLoc();
19081
19082   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19083   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19084
19085   // Get a register mask for the lowered call.
19086   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19087   // proper register mask.
19088   const uint32_t *RegMask =
19089       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19090   if (Subtarget->is64Bit()) {
19091     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19092                                       TII->get(X86::MOV64rm), X86::RDI)
19093     .addReg(X86::RIP)
19094     .addImm(0).addReg(0)
19095     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19096                       MI->getOperand(3).getTargetFlags())
19097     .addReg(0);
19098     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19099     addDirectMem(MIB, X86::RDI);
19100     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19101   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19102     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19103                                       TII->get(X86::MOV32rm), X86::EAX)
19104     .addReg(0)
19105     .addImm(0).addReg(0)
19106     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19107                       MI->getOperand(3).getTargetFlags())
19108     .addReg(0);
19109     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19110     addDirectMem(MIB, X86::EAX);
19111     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19112   } else {
19113     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19114                                       TII->get(X86::MOV32rm), X86::EAX)
19115     .addReg(TII->getGlobalBaseReg(F))
19116     .addImm(0).addReg(0)
19117     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19118                       MI->getOperand(3).getTargetFlags())
19119     .addReg(0);
19120     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19121     addDirectMem(MIB, X86::EAX);
19122     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19123   }
19124
19125   MI->eraseFromParent(); // The pseudo instruction is gone now.
19126   return BB;
19127 }
19128
19129 MachineBasicBlock *
19130 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19131                                     MachineBasicBlock *MBB) const {
19132   DebugLoc DL = MI->getDebugLoc();
19133   MachineFunction *MF = MBB->getParent();
19134   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19135   MachineRegisterInfo &MRI = MF->getRegInfo();
19136
19137   const BasicBlock *BB = MBB->getBasicBlock();
19138   MachineFunction::iterator I = MBB;
19139   ++I;
19140
19141   // Memory Reference
19142   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19143   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19144
19145   unsigned DstReg;
19146   unsigned MemOpndSlot = 0;
19147
19148   unsigned CurOp = 0;
19149
19150   DstReg = MI->getOperand(CurOp++).getReg();
19151   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19152   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19153   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19154   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19155
19156   MemOpndSlot = CurOp;
19157
19158   MVT PVT = getPointerTy();
19159   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19160          "Invalid Pointer Size!");
19161
19162   // For v = setjmp(buf), we generate
19163   //
19164   // thisMBB:
19165   //  buf[LabelOffset] = restoreMBB
19166   //  SjLjSetup restoreMBB
19167   //
19168   // mainMBB:
19169   //  v_main = 0
19170   //
19171   // sinkMBB:
19172   //  v = phi(main, restore)
19173   //
19174   // restoreMBB:
19175   //  if base pointer being used, load it from frame
19176   //  v_restore = 1
19177
19178   MachineBasicBlock *thisMBB = MBB;
19179   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19180   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19181   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19182   MF->insert(I, mainMBB);
19183   MF->insert(I, sinkMBB);
19184   MF->push_back(restoreMBB);
19185
19186   MachineInstrBuilder MIB;
19187
19188   // Transfer the remainder of BB and its successor edges to sinkMBB.
19189   sinkMBB->splice(sinkMBB->begin(), MBB,
19190                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19191   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19192
19193   // thisMBB:
19194   unsigned PtrStoreOpc = 0;
19195   unsigned LabelReg = 0;
19196   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19197   Reloc::Model RM = MF->getTarget().getRelocationModel();
19198   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19199                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19200
19201   // Prepare IP either in reg or imm.
19202   if (!UseImmLabel) {
19203     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19204     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19205     LabelReg = MRI.createVirtualRegister(PtrRC);
19206     if (Subtarget->is64Bit()) {
19207       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19208               .addReg(X86::RIP)
19209               .addImm(0)
19210               .addReg(0)
19211               .addMBB(restoreMBB)
19212               .addReg(0);
19213     } else {
19214       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19215       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19216               .addReg(XII->getGlobalBaseReg(MF))
19217               .addImm(0)
19218               .addReg(0)
19219               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19220               .addReg(0);
19221     }
19222   } else
19223     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19224   // Store IP
19225   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19226   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19227     if (i == X86::AddrDisp)
19228       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19229     else
19230       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19231   }
19232   if (!UseImmLabel)
19233     MIB.addReg(LabelReg);
19234   else
19235     MIB.addMBB(restoreMBB);
19236   MIB.setMemRefs(MMOBegin, MMOEnd);
19237   // Setup
19238   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19239           .addMBB(restoreMBB);
19240
19241   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19242   MIB.addRegMask(RegInfo->getNoPreservedMask());
19243   thisMBB->addSuccessor(mainMBB);
19244   thisMBB->addSuccessor(restoreMBB);
19245
19246   // mainMBB:
19247   //  EAX = 0
19248   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19249   mainMBB->addSuccessor(sinkMBB);
19250
19251   // sinkMBB:
19252   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19253           TII->get(X86::PHI), DstReg)
19254     .addReg(mainDstReg).addMBB(mainMBB)
19255     .addReg(restoreDstReg).addMBB(restoreMBB);
19256
19257   // restoreMBB:
19258   if (RegInfo->hasBasePointer(*MF)) {
19259     const bool Uses64BitFramePtr =
19260         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19261     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19262     X86FI->setRestoreBasePointer(MF);
19263     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19264     unsigned BasePtr = RegInfo->getBaseRegister();
19265     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19266     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19267                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19268       .setMIFlag(MachineInstr::FrameSetup);
19269   }
19270   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19271   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19272   restoreMBB->addSuccessor(sinkMBB);
19273
19274   MI->eraseFromParent();
19275   return sinkMBB;
19276 }
19277
19278 MachineBasicBlock *
19279 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19280                                      MachineBasicBlock *MBB) const {
19281   DebugLoc DL = MI->getDebugLoc();
19282   MachineFunction *MF = MBB->getParent();
19283   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19284   MachineRegisterInfo &MRI = MF->getRegInfo();
19285
19286   // Memory Reference
19287   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19288   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19289
19290   MVT PVT = getPointerTy();
19291   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19292          "Invalid Pointer Size!");
19293
19294   const TargetRegisterClass *RC =
19295     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19296   unsigned Tmp = MRI.createVirtualRegister(RC);
19297   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19298   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19299   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19300   unsigned SP = RegInfo->getStackRegister();
19301
19302   MachineInstrBuilder MIB;
19303
19304   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19305   const int64_t SPOffset = 2 * PVT.getStoreSize();
19306
19307   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19308   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19309
19310   // Reload FP
19311   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19312   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19313     MIB.addOperand(MI->getOperand(i));
19314   MIB.setMemRefs(MMOBegin, MMOEnd);
19315   // Reload IP
19316   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19317   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19318     if (i == X86::AddrDisp)
19319       MIB.addDisp(MI->getOperand(i), LabelOffset);
19320     else
19321       MIB.addOperand(MI->getOperand(i));
19322   }
19323   MIB.setMemRefs(MMOBegin, MMOEnd);
19324   // Reload SP
19325   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19326   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19327     if (i == X86::AddrDisp)
19328       MIB.addDisp(MI->getOperand(i), SPOffset);
19329     else
19330       MIB.addOperand(MI->getOperand(i));
19331   }
19332   MIB.setMemRefs(MMOBegin, MMOEnd);
19333   // Jump
19334   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19335
19336   MI->eraseFromParent();
19337   return MBB;
19338 }
19339
19340 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19341 // accumulator loops. Writing back to the accumulator allows the coalescer
19342 // to remove extra copies in the loop.
19343 MachineBasicBlock *
19344 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19345                                  MachineBasicBlock *MBB) const {
19346   MachineOperand &AddendOp = MI->getOperand(3);
19347
19348   // Bail out early if the addend isn't a register - we can't switch these.
19349   if (!AddendOp.isReg())
19350     return MBB;
19351
19352   MachineFunction &MF = *MBB->getParent();
19353   MachineRegisterInfo &MRI = MF.getRegInfo();
19354
19355   // Check whether the addend is defined by a PHI:
19356   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19357   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19358   if (!AddendDef.isPHI())
19359     return MBB;
19360
19361   // Look for the following pattern:
19362   // loop:
19363   //   %addend = phi [%entry, 0], [%loop, %result]
19364   //   ...
19365   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19366
19367   // Replace with:
19368   //   loop:
19369   //   %addend = phi [%entry, 0], [%loop, %result]
19370   //   ...
19371   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19372
19373   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19374     assert(AddendDef.getOperand(i).isReg());
19375     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19376     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19377     if (&PHISrcInst == MI) {
19378       // Found a matching instruction.
19379       unsigned NewFMAOpc = 0;
19380       switch (MI->getOpcode()) {
19381         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19382         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19383         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19384         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19385         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19386         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19387         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19388         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19389         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19390         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19391         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19392         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19393         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19394         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19395         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19396         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19397         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19398         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19399         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19400         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19401
19402         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19403         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19404         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19405         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19406         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19407         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19408         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19409         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19410         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19411         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19412         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19413         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19414         default: llvm_unreachable("Unrecognized FMA variant.");
19415       }
19416
19417       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19418       MachineInstrBuilder MIB =
19419         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19420         .addOperand(MI->getOperand(0))
19421         .addOperand(MI->getOperand(3))
19422         .addOperand(MI->getOperand(2))
19423         .addOperand(MI->getOperand(1));
19424       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19425       MI->eraseFromParent();
19426     }
19427   }
19428
19429   return MBB;
19430 }
19431
19432 MachineBasicBlock *
19433 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19434                                                MachineBasicBlock *BB) const {
19435   switch (MI->getOpcode()) {
19436   default: llvm_unreachable("Unexpected instr type to insert");
19437   case X86::TAILJMPd64:
19438   case X86::TAILJMPr64:
19439   case X86::TAILJMPm64:
19440   case X86::TAILJMPd64_REX:
19441   case X86::TAILJMPr64_REX:
19442   case X86::TAILJMPm64_REX:
19443     llvm_unreachable("TAILJMP64 would not be touched here.");
19444   case X86::TCRETURNdi64:
19445   case X86::TCRETURNri64:
19446   case X86::TCRETURNmi64:
19447     return BB;
19448   case X86::WIN_ALLOCA:
19449     return EmitLoweredWinAlloca(MI, BB);
19450   case X86::SEG_ALLOCA_32:
19451   case X86::SEG_ALLOCA_64:
19452     return EmitLoweredSegAlloca(MI, BB);
19453   case X86::TLSCall_32:
19454   case X86::TLSCall_64:
19455     return EmitLoweredTLSCall(MI, BB);
19456   case X86::CMOV_GR8:
19457   case X86::CMOV_FR32:
19458   case X86::CMOV_FR64:
19459   case X86::CMOV_V4F32:
19460   case X86::CMOV_V2F64:
19461   case X86::CMOV_V2I64:
19462   case X86::CMOV_V8F32:
19463   case X86::CMOV_V4F64:
19464   case X86::CMOV_V4I64:
19465   case X86::CMOV_V16F32:
19466   case X86::CMOV_V8F64:
19467   case X86::CMOV_V8I64:
19468   case X86::CMOV_GR16:
19469   case X86::CMOV_GR32:
19470   case X86::CMOV_RFP32:
19471   case X86::CMOV_RFP64:
19472   case X86::CMOV_RFP80:
19473   case X86::CMOV_V8I1:
19474   case X86::CMOV_V16I1:
19475   case X86::CMOV_V32I1:
19476   case X86::CMOV_V64I1:
19477     return EmitLoweredSelect(MI, BB);
19478
19479   case X86::FP32_TO_INT16_IN_MEM:
19480   case X86::FP32_TO_INT32_IN_MEM:
19481   case X86::FP32_TO_INT64_IN_MEM:
19482   case X86::FP64_TO_INT16_IN_MEM:
19483   case X86::FP64_TO_INT32_IN_MEM:
19484   case X86::FP64_TO_INT64_IN_MEM:
19485   case X86::FP80_TO_INT16_IN_MEM:
19486   case X86::FP80_TO_INT32_IN_MEM:
19487   case X86::FP80_TO_INT64_IN_MEM: {
19488     MachineFunction *F = BB->getParent();
19489     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19490     DebugLoc DL = MI->getDebugLoc();
19491
19492     // Change the floating point control register to use "round towards zero"
19493     // mode when truncating to an integer value.
19494     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19495     addFrameReference(BuildMI(*BB, MI, DL,
19496                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19497
19498     // Load the old value of the high byte of the control word...
19499     unsigned OldCW =
19500       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19501     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19502                       CWFrameIdx);
19503
19504     // Set the high part to be round to zero...
19505     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19506       .addImm(0xC7F);
19507
19508     // Reload the modified control word now...
19509     addFrameReference(BuildMI(*BB, MI, DL,
19510                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19511
19512     // Restore the memory image of control word to original value
19513     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19514       .addReg(OldCW);
19515
19516     // Get the X86 opcode to use.
19517     unsigned Opc;
19518     switch (MI->getOpcode()) {
19519     default: llvm_unreachable("illegal opcode!");
19520     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19521     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19522     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19523     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19524     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19525     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19526     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19527     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19528     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19529     }
19530
19531     X86AddressMode AM;
19532     MachineOperand &Op = MI->getOperand(0);
19533     if (Op.isReg()) {
19534       AM.BaseType = X86AddressMode::RegBase;
19535       AM.Base.Reg = Op.getReg();
19536     } else {
19537       AM.BaseType = X86AddressMode::FrameIndexBase;
19538       AM.Base.FrameIndex = Op.getIndex();
19539     }
19540     Op = MI->getOperand(1);
19541     if (Op.isImm())
19542       AM.Scale = Op.getImm();
19543     Op = MI->getOperand(2);
19544     if (Op.isImm())
19545       AM.IndexReg = Op.getImm();
19546     Op = MI->getOperand(3);
19547     if (Op.isGlobal()) {
19548       AM.GV = Op.getGlobal();
19549     } else {
19550       AM.Disp = Op.getImm();
19551     }
19552     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19553                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19554
19555     // Reload the original control word now.
19556     addFrameReference(BuildMI(*BB, MI, DL,
19557                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19558
19559     MI->eraseFromParent();   // The pseudo instruction is gone now.
19560     return BB;
19561   }
19562     // String/text processing lowering.
19563   case X86::PCMPISTRM128REG:
19564   case X86::VPCMPISTRM128REG:
19565   case X86::PCMPISTRM128MEM:
19566   case X86::VPCMPISTRM128MEM:
19567   case X86::PCMPESTRM128REG:
19568   case X86::VPCMPESTRM128REG:
19569   case X86::PCMPESTRM128MEM:
19570   case X86::VPCMPESTRM128MEM:
19571     assert(Subtarget->hasSSE42() &&
19572            "Target must have SSE4.2 or AVX features enabled");
19573     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19574
19575   // String/text processing lowering.
19576   case X86::PCMPISTRIREG:
19577   case X86::VPCMPISTRIREG:
19578   case X86::PCMPISTRIMEM:
19579   case X86::VPCMPISTRIMEM:
19580   case X86::PCMPESTRIREG:
19581   case X86::VPCMPESTRIREG:
19582   case X86::PCMPESTRIMEM:
19583   case X86::VPCMPESTRIMEM:
19584     assert(Subtarget->hasSSE42() &&
19585            "Target must have SSE4.2 or AVX features enabled");
19586     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19587
19588   // Thread synchronization.
19589   case X86::MONITOR:
19590     return EmitMonitor(MI, BB, Subtarget);
19591
19592   // xbegin
19593   case X86::XBEGIN:
19594     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19595
19596   case X86::VASTART_SAVE_XMM_REGS:
19597     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19598
19599   case X86::VAARG_64:
19600     return EmitVAARG64WithCustomInserter(MI, BB);
19601
19602   case X86::EH_SjLj_SetJmp32:
19603   case X86::EH_SjLj_SetJmp64:
19604     return emitEHSjLjSetJmp(MI, BB);
19605
19606   case X86::EH_SjLj_LongJmp32:
19607   case X86::EH_SjLj_LongJmp64:
19608     return emitEHSjLjLongJmp(MI, BB);
19609
19610   case TargetOpcode::STATEPOINT:
19611     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19612     // this point in the process.  We diverge later.
19613     return emitPatchPoint(MI, BB);
19614
19615   case TargetOpcode::STACKMAP:
19616   case TargetOpcode::PATCHPOINT:
19617     return emitPatchPoint(MI, BB);
19618
19619   case X86::VFMADDPDr213r:
19620   case X86::VFMADDPSr213r:
19621   case X86::VFMADDSDr213r:
19622   case X86::VFMADDSSr213r:
19623   case X86::VFMSUBPDr213r:
19624   case X86::VFMSUBPSr213r:
19625   case X86::VFMSUBSDr213r:
19626   case X86::VFMSUBSSr213r:
19627   case X86::VFNMADDPDr213r:
19628   case X86::VFNMADDPSr213r:
19629   case X86::VFNMADDSDr213r:
19630   case X86::VFNMADDSSr213r:
19631   case X86::VFNMSUBPDr213r:
19632   case X86::VFNMSUBPSr213r:
19633   case X86::VFNMSUBSDr213r:
19634   case X86::VFNMSUBSSr213r:
19635   case X86::VFMADDSUBPDr213r:
19636   case X86::VFMADDSUBPSr213r:
19637   case X86::VFMSUBADDPDr213r:
19638   case X86::VFMSUBADDPSr213r:
19639   case X86::VFMADDPDr213rY:
19640   case X86::VFMADDPSr213rY:
19641   case X86::VFMSUBPDr213rY:
19642   case X86::VFMSUBPSr213rY:
19643   case X86::VFNMADDPDr213rY:
19644   case X86::VFNMADDPSr213rY:
19645   case X86::VFNMSUBPDr213rY:
19646   case X86::VFNMSUBPSr213rY:
19647   case X86::VFMADDSUBPDr213rY:
19648   case X86::VFMADDSUBPSr213rY:
19649   case X86::VFMSUBADDPDr213rY:
19650   case X86::VFMSUBADDPSr213rY:
19651     return emitFMA3Instr(MI, BB);
19652   }
19653 }
19654
19655 //===----------------------------------------------------------------------===//
19656 //                           X86 Optimization Hooks
19657 //===----------------------------------------------------------------------===//
19658
19659 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19660                                                       APInt &KnownZero,
19661                                                       APInt &KnownOne,
19662                                                       const SelectionDAG &DAG,
19663                                                       unsigned Depth) const {
19664   unsigned BitWidth = KnownZero.getBitWidth();
19665   unsigned Opc = Op.getOpcode();
19666   assert((Opc >= ISD::BUILTIN_OP_END ||
19667           Opc == ISD::INTRINSIC_WO_CHAIN ||
19668           Opc == ISD::INTRINSIC_W_CHAIN ||
19669           Opc == ISD::INTRINSIC_VOID) &&
19670          "Should use MaskedValueIsZero if you don't know whether Op"
19671          " is a target node!");
19672
19673   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19674   switch (Opc) {
19675   default: break;
19676   case X86ISD::ADD:
19677   case X86ISD::SUB:
19678   case X86ISD::ADC:
19679   case X86ISD::SBB:
19680   case X86ISD::SMUL:
19681   case X86ISD::UMUL:
19682   case X86ISD::INC:
19683   case X86ISD::DEC:
19684   case X86ISD::OR:
19685   case X86ISD::XOR:
19686   case X86ISD::AND:
19687     // These nodes' second result is a boolean.
19688     if (Op.getResNo() == 0)
19689       break;
19690     // Fallthrough
19691   case X86ISD::SETCC:
19692     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19693     break;
19694   case ISD::INTRINSIC_WO_CHAIN: {
19695     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19696     unsigned NumLoBits = 0;
19697     switch (IntId) {
19698     default: break;
19699     case Intrinsic::x86_sse_movmsk_ps:
19700     case Intrinsic::x86_avx_movmsk_ps_256:
19701     case Intrinsic::x86_sse2_movmsk_pd:
19702     case Intrinsic::x86_avx_movmsk_pd_256:
19703     case Intrinsic::x86_mmx_pmovmskb:
19704     case Intrinsic::x86_sse2_pmovmskb_128:
19705     case Intrinsic::x86_avx2_pmovmskb: {
19706       // High bits of movmskp{s|d}, pmovmskb are known zero.
19707       switch (IntId) {
19708         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19709         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19710         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19711         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19712         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19713         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19714         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19715         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19716       }
19717       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19718       break;
19719     }
19720     }
19721     break;
19722   }
19723   }
19724 }
19725
19726 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19727   SDValue Op,
19728   const SelectionDAG &,
19729   unsigned Depth) const {
19730   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19731   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19732     return Op.getValueType().getScalarType().getSizeInBits();
19733
19734   // Fallback case.
19735   return 1;
19736 }
19737
19738 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19739 /// node is a GlobalAddress + offset.
19740 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19741                                        const GlobalValue* &GA,
19742                                        int64_t &Offset) const {
19743   if (N->getOpcode() == X86ISD::Wrapper) {
19744     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19745       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19746       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19747       return true;
19748     }
19749   }
19750   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19751 }
19752
19753 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19754 /// same as extracting the high 128-bit part of 256-bit vector and then
19755 /// inserting the result into the low part of a new 256-bit vector
19756 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19757   EVT VT = SVOp->getValueType(0);
19758   unsigned NumElems = VT.getVectorNumElements();
19759
19760   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19761   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19762     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19763         SVOp->getMaskElt(j) >= 0)
19764       return false;
19765
19766   return true;
19767 }
19768
19769 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19770 /// same as extracting the low 128-bit part of 256-bit vector and then
19771 /// inserting the result into the high part of a new 256-bit vector
19772 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19773   EVT VT = SVOp->getValueType(0);
19774   unsigned NumElems = VT.getVectorNumElements();
19775
19776   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19777   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19778     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19779         SVOp->getMaskElt(j) >= 0)
19780       return false;
19781
19782   return true;
19783 }
19784
19785 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19786 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19787                                         TargetLowering::DAGCombinerInfo &DCI,
19788                                         const X86Subtarget* Subtarget) {
19789   SDLoc dl(N);
19790   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19791   SDValue V1 = SVOp->getOperand(0);
19792   SDValue V2 = SVOp->getOperand(1);
19793   EVT VT = SVOp->getValueType(0);
19794   unsigned NumElems = VT.getVectorNumElements();
19795
19796   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19797       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19798     //
19799     //                   0,0,0,...
19800     //                      |
19801     //    V      UNDEF    BUILD_VECTOR    UNDEF
19802     //     \      /           \           /
19803     //  CONCAT_VECTOR         CONCAT_VECTOR
19804     //         \                  /
19805     //          \                /
19806     //          RESULT: V + zero extended
19807     //
19808     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19809         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19810         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19811       return SDValue();
19812
19813     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19814       return SDValue();
19815
19816     // To match the shuffle mask, the first half of the mask should
19817     // be exactly the first vector, and all the rest a splat with the
19818     // first element of the second one.
19819     for (unsigned i = 0; i != NumElems/2; ++i)
19820       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19821           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19822         return SDValue();
19823
19824     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19825     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19826       if (Ld->hasNUsesOfValue(1, 0)) {
19827         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19828         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19829         SDValue ResNode =
19830           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19831                                   Ld->getMemoryVT(),
19832                                   Ld->getPointerInfo(),
19833                                   Ld->getAlignment(),
19834                                   false/*isVolatile*/, true/*ReadMem*/,
19835                                   false/*WriteMem*/);
19836
19837         // Make sure the newly-created LOAD is in the same position as Ld in
19838         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19839         // and update uses of Ld's output chain to use the TokenFactor.
19840         if (Ld->hasAnyUseOfValue(1)) {
19841           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19842                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19843           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19844           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19845                                  SDValue(ResNode.getNode(), 1));
19846         }
19847
19848         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19849       }
19850     }
19851
19852     // Emit a zeroed vector and insert the desired subvector on its
19853     // first half.
19854     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19855     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19856     return DCI.CombineTo(N, InsV);
19857   }
19858
19859   //===--------------------------------------------------------------------===//
19860   // Combine some shuffles into subvector extracts and inserts:
19861   //
19862
19863   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19864   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19865     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19866     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19867     return DCI.CombineTo(N, InsV);
19868   }
19869
19870   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19871   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19872     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19873     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19874     return DCI.CombineTo(N, InsV);
19875   }
19876
19877   return SDValue();
19878 }
19879
19880 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19881 /// possible.
19882 ///
19883 /// This is the leaf of the recursive combinine below. When we have found some
19884 /// chain of single-use x86 shuffle instructions and accumulated the combined
19885 /// shuffle mask represented by them, this will try to pattern match that mask
19886 /// into either a single instruction if there is a special purpose instruction
19887 /// for this operation, or into a PSHUFB instruction which is a fully general
19888 /// instruction but should only be used to replace chains over a certain depth.
19889 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19890                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19891                                    TargetLowering::DAGCombinerInfo &DCI,
19892                                    const X86Subtarget *Subtarget) {
19893   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19894
19895   // Find the operand that enters the chain. Note that multiple uses are OK
19896   // here, we're not going to remove the operand we find.
19897   SDValue Input = Op.getOperand(0);
19898   while (Input.getOpcode() == ISD::BITCAST)
19899     Input = Input.getOperand(0);
19900
19901   MVT VT = Input.getSimpleValueType();
19902   MVT RootVT = Root.getSimpleValueType();
19903   SDLoc DL(Root);
19904
19905   // Just remove no-op shuffle masks.
19906   if (Mask.size() == 1) {
19907     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19908                   /*AddTo*/ true);
19909     return true;
19910   }
19911
19912   // Use the float domain if the operand type is a floating point type.
19913   bool FloatDomain = VT.isFloatingPoint();
19914
19915   // For floating point shuffles, we don't have free copies in the shuffle
19916   // instructions or the ability to load as part of the instruction, so
19917   // canonicalize their shuffles to UNPCK or MOV variants.
19918   //
19919   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19920   // vectors because it can have a load folded into it that UNPCK cannot. This
19921   // doesn't preclude something switching to the shorter encoding post-RA.
19922   //
19923   // FIXME: Should teach these routines about AVX vector widths.
19924   if (FloatDomain && VT.getSizeInBits() == 128) {
19925     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19926       bool Lo = Mask.equals({0, 0});
19927       unsigned Shuffle;
19928       MVT ShuffleVT;
19929       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19930       // is no slower than UNPCKLPD but has the option to fold the input operand
19931       // into even an unaligned memory load.
19932       if (Lo && Subtarget->hasSSE3()) {
19933         Shuffle = X86ISD::MOVDDUP;
19934         ShuffleVT = MVT::v2f64;
19935       } else {
19936         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19937         // than the UNPCK variants.
19938         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19939         ShuffleVT = MVT::v4f32;
19940       }
19941       if (Depth == 1 && Root->getOpcode() == Shuffle)
19942         return false; // Nothing to do!
19943       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19944       DCI.AddToWorklist(Op.getNode());
19945       if (Shuffle == X86ISD::MOVDDUP)
19946         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19947       else
19948         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19949       DCI.AddToWorklist(Op.getNode());
19950       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19951                     /*AddTo*/ true);
19952       return true;
19953     }
19954     if (Subtarget->hasSSE3() &&
19955         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19956       bool Lo = Mask.equals({0, 0, 2, 2});
19957       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19958       MVT ShuffleVT = MVT::v4f32;
19959       if (Depth == 1 && Root->getOpcode() == Shuffle)
19960         return false; // Nothing to do!
19961       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19962       DCI.AddToWorklist(Op.getNode());
19963       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19964       DCI.AddToWorklist(Op.getNode());
19965       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19966                     /*AddTo*/ true);
19967       return true;
19968     }
19969     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19970       bool Lo = Mask.equals({0, 0, 1, 1});
19971       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19972       MVT ShuffleVT = MVT::v4f32;
19973       if (Depth == 1 && Root->getOpcode() == Shuffle)
19974         return false; // Nothing to do!
19975       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19976       DCI.AddToWorklist(Op.getNode());
19977       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19978       DCI.AddToWorklist(Op.getNode());
19979       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19980                     /*AddTo*/ true);
19981       return true;
19982     }
19983   }
19984
19985   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19986   // variants as none of these have single-instruction variants that are
19987   // superior to the UNPCK formulation.
19988   if (!FloatDomain && VT.getSizeInBits() == 128 &&
19989       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19990        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19991        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19992        Mask.equals(
19993            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19994     bool Lo = Mask[0] == 0;
19995     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19996     if (Depth == 1 && Root->getOpcode() == Shuffle)
19997       return false; // Nothing to do!
19998     MVT ShuffleVT;
19999     switch (Mask.size()) {
20000     case 8:
20001       ShuffleVT = MVT::v8i16;
20002       break;
20003     case 16:
20004       ShuffleVT = MVT::v16i8;
20005       break;
20006     default:
20007       llvm_unreachable("Impossible mask size!");
20008     };
20009     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20010     DCI.AddToWorklist(Op.getNode());
20011     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20012     DCI.AddToWorklist(Op.getNode());
20013     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20014                   /*AddTo*/ true);
20015     return true;
20016   }
20017
20018   // Don't try to re-form single instruction chains under any circumstances now
20019   // that we've done encoding canonicalization for them.
20020   if (Depth < 2)
20021     return false;
20022
20023   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20024   // can replace them with a single PSHUFB instruction profitably. Intel's
20025   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20026   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20027   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20028     SmallVector<SDValue, 16> PSHUFBMask;
20029     int NumBytes = VT.getSizeInBits() / 8;
20030     int Ratio = NumBytes / Mask.size();
20031     for (int i = 0; i < NumBytes; ++i) {
20032       if (Mask[i / Ratio] == SM_SentinelUndef) {
20033         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20034         continue;
20035       }
20036       int M = Mask[i / Ratio] != SM_SentinelZero
20037                   ? Ratio * Mask[i / Ratio] + i % Ratio
20038                   : 255;
20039       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20040     }
20041     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20042     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20043     DCI.AddToWorklist(Op.getNode());
20044     SDValue PSHUFBMaskOp =
20045         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20046     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20047     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20048     DCI.AddToWorklist(Op.getNode());
20049     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20050                   /*AddTo*/ true);
20051     return true;
20052   }
20053
20054   // Failed to find any combines.
20055   return false;
20056 }
20057
20058 /// \brief Fully generic combining of x86 shuffle instructions.
20059 ///
20060 /// This should be the last combine run over the x86 shuffle instructions. Once
20061 /// they have been fully optimized, this will recursively consider all chains
20062 /// of single-use shuffle instructions, build a generic model of the cumulative
20063 /// shuffle operation, and check for simpler instructions which implement this
20064 /// operation. We use this primarily for two purposes:
20065 ///
20066 /// 1) Collapse generic shuffles to specialized single instructions when
20067 ///    equivalent. In most cases, this is just an encoding size win, but
20068 ///    sometimes we will collapse multiple generic shuffles into a single
20069 ///    special-purpose shuffle.
20070 /// 2) Look for sequences of shuffle instructions with 3 or more total
20071 ///    instructions, and replace them with the slightly more expensive SSSE3
20072 ///    PSHUFB instruction if available. We do this as the last combining step
20073 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20074 ///    a suitable short sequence of other instructions. The PHUFB will either
20075 ///    use a register or have to read from memory and so is slightly (but only
20076 ///    slightly) more expensive than the other shuffle instructions.
20077 ///
20078 /// Because this is inherently a quadratic operation (for each shuffle in
20079 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20080 /// This should never be an issue in practice as the shuffle lowering doesn't
20081 /// produce sequences of more than 8 instructions.
20082 ///
20083 /// FIXME: We will currently miss some cases where the redundant shuffling
20084 /// would simplify under the threshold for PSHUFB formation because of
20085 /// combine-ordering. To fix this, we should do the redundant instruction
20086 /// combining in this recursive walk.
20087 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20088                                           ArrayRef<int> RootMask,
20089                                           int Depth, bool HasPSHUFB,
20090                                           SelectionDAG &DAG,
20091                                           TargetLowering::DAGCombinerInfo &DCI,
20092                                           const X86Subtarget *Subtarget) {
20093   // Bound the depth of our recursive combine because this is ultimately
20094   // quadratic in nature.
20095   if (Depth > 8)
20096     return false;
20097
20098   // Directly rip through bitcasts to find the underlying operand.
20099   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20100     Op = Op.getOperand(0);
20101
20102   MVT VT = Op.getSimpleValueType();
20103   if (!VT.isVector())
20104     return false; // Bail if we hit a non-vector.
20105
20106   assert(Root.getSimpleValueType().isVector() &&
20107          "Shuffles operate on vector types!");
20108   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20109          "Can only combine shuffles of the same vector register size.");
20110
20111   if (!isTargetShuffle(Op.getOpcode()))
20112     return false;
20113   SmallVector<int, 16> OpMask;
20114   bool IsUnary;
20115   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20116   // We only can combine unary shuffles which we can decode the mask for.
20117   if (!HaveMask || !IsUnary)
20118     return false;
20119
20120   assert(VT.getVectorNumElements() == OpMask.size() &&
20121          "Different mask size from vector size!");
20122   assert(((RootMask.size() > OpMask.size() &&
20123            RootMask.size() % OpMask.size() == 0) ||
20124           (OpMask.size() > RootMask.size() &&
20125            OpMask.size() % RootMask.size() == 0) ||
20126           OpMask.size() == RootMask.size()) &&
20127          "The smaller number of elements must divide the larger.");
20128   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20129   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20130   assert(((RootRatio == 1 && OpRatio == 1) ||
20131           (RootRatio == 1) != (OpRatio == 1)) &&
20132          "Must not have a ratio for both incoming and op masks!");
20133
20134   SmallVector<int, 16> Mask;
20135   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20136
20137   // Merge this shuffle operation's mask into our accumulated mask. Note that
20138   // this shuffle's mask will be the first applied to the input, followed by the
20139   // root mask to get us all the way to the root value arrangement. The reason
20140   // for this order is that we are recursing up the operation chain.
20141   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20142     int RootIdx = i / RootRatio;
20143     if (RootMask[RootIdx] < 0) {
20144       // This is a zero or undef lane, we're done.
20145       Mask.push_back(RootMask[RootIdx]);
20146       continue;
20147     }
20148
20149     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20150     int OpIdx = RootMaskedIdx / OpRatio;
20151     if (OpMask[OpIdx] < 0) {
20152       // The incoming lanes are zero or undef, it doesn't matter which ones we
20153       // are using.
20154       Mask.push_back(OpMask[OpIdx]);
20155       continue;
20156     }
20157
20158     // Ok, we have non-zero lanes, map them through.
20159     Mask.push_back(OpMask[OpIdx] * OpRatio +
20160                    RootMaskedIdx % OpRatio);
20161   }
20162
20163   // See if we can recurse into the operand to combine more things.
20164   switch (Op.getOpcode()) {
20165     case X86ISD::PSHUFB:
20166       HasPSHUFB = true;
20167     case X86ISD::PSHUFD:
20168     case X86ISD::PSHUFHW:
20169     case X86ISD::PSHUFLW:
20170       if (Op.getOperand(0).hasOneUse() &&
20171           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20172                                         HasPSHUFB, DAG, DCI, Subtarget))
20173         return true;
20174       break;
20175
20176     case X86ISD::UNPCKL:
20177     case X86ISD::UNPCKH:
20178       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20179       // We can't check for single use, we have to check that this shuffle is the only user.
20180       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20181           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20182                                         HasPSHUFB, DAG, DCI, Subtarget))
20183           return true;
20184       break;
20185   }
20186
20187   // Minor canonicalization of the accumulated shuffle mask to make it easier
20188   // to match below. All this does is detect masks with squential pairs of
20189   // elements, and shrink them to the half-width mask. It does this in a loop
20190   // so it will reduce the size of the mask to the minimal width mask which
20191   // performs an equivalent shuffle.
20192   SmallVector<int, 16> WidenedMask;
20193   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20194     Mask = std::move(WidenedMask);
20195     WidenedMask.clear();
20196   }
20197
20198   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20199                                 Subtarget);
20200 }
20201
20202 /// \brief Get the PSHUF-style mask from PSHUF node.
20203 ///
20204 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20205 /// PSHUF-style masks that can be reused with such instructions.
20206 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20207   MVT VT = N.getSimpleValueType();
20208   SmallVector<int, 4> Mask;
20209   bool IsUnary;
20210   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20211   (void)HaveMask;
20212   assert(HaveMask);
20213
20214   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20215   // matter. Check that the upper masks are repeats and remove them.
20216   if (VT.getSizeInBits() > 128) {
20217     int LaneElts = 128 / VT.getScalarSizeInBits();
20218 #ifndef NDEBUG
20219     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20220       for (int j = 0; j < LaneElts; ++j)
20221         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20222                "Mask doesn't repeat in high 128-bit lanes!");
20223 #endif
20224     Mask.resize(LaneElts);
20225   }
20226
20227   switch (N.getOpcode()) {
20228   case X86ISD::PSHUFD:
20229     return Mask;
20230   case X86ISD::PSHUFLW:
20231     Mask.resize(4);
20232     return Mask;
20233   case X86ISD::PSHUFHW:
20234     Mask.erase(Mask.begin(), Mask.begin() + 4);
20235     for (int &M : Mask)
20236       M -= 4;
20237     return Mask;
20238   default:
20239     llvm_unreachable("No valid shuffle instruction found!");
20240   }
20241 }
20242
20243 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20244 ///
20245 /// We walk up the chain and look for a combinable shuffle, skipping over
20246 /// shuffles that we could hoist this shuffle's transformation past without
20247 /// altering anything.
20248 static SDValue
20249 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20250                              SelectionDAG &DAG,
20251                              TargetLowering::DAGCombinerInfo &DCI) {
20252   assert(N.getOpcode() == X86ISD::PSHUFD &&
20253          "Called with something other than an x86 128-bit half shuffle!");
20254   SDLoc DL(N);
20255
20256   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20257   // of the shuffles in the chain so that we can form a fresh chain to replace
20258   // this one.
20259   SmallVector<SDValue, 8> Chain;
20260   SDValue V = N.getOperand(0);
20261   for (; V.hasOneUse(); V = V.getOperand(0)) {
20262     switch (V.getOpcode()) {
20263     default:
20264       return SDValue(); // Nothing combined!
20265
20266     case ISD::BITCAST:
20267       // Skip bitcasts as we always know the type for the target specific
20268       // instructions.
20269       continue;
20270
20271     case X86ISD::PSHUFD:
20272       // Found another dword shuffle.
20273       break;
20274
20275     case X86ISD::PSHUFLW:
20276       // Check that the low words (being shuffled) are the identity in the
20277       // dword shuffle, and the high words are self-contained.
20278       if (Mask[0] != 0 || Mask[1] != 1 ||
20279           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20280         return SDValue();
20281
20282       Chain.push_back(V);
20283       continue;
20284
20285     case X86ISD::PSHUFHW:
20286       // Check that the high words (being shuffled) are the identity in the
20287       // dword shuffle, and the low words are self-contained.
20288       if (Mask[2] != 2 || Mask[3] != 3 ||
20289           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20290         return SDValue();
20291
20292       Chain.push_back(V);
20293       continue;
20294
20295     case X86ISD::UNPCKL:
20296     case X86ISD::UNPCKH:
20297       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20298       // shuffle into a preceding word shuffle.
20299       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20300           V.getSimpleValueType().getScalarType() != MVT::i16)
20301         return SDValue();
20302
20303       // Search for a half-shuffle which we can combine with.
20304       unsigned CombineOp =
20305           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20306       if (V.getOperand(0) != V.getOperand(1) ||
20307           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20308         return SDValue();
20309       Chain.push_back(V);
20310       V = V.getOperand(0);
20311       do {
20312         switch (V.getOpcode()) {
20313         default:
20314           return SDValue(); // Nothing to combine.
20315
20316         case X86ISD::PSHUFLW:
20317         case X86ISD::PSHUFHW:
20318           if (V.getOpcode() == CombineOp)
20319             break;
20320
20321           Chain.push_back(V);
20322
20323           // Fallthrough!
20324         case ISD::BITCAST:
20325           V = V.getOperand(0);
20326           continue;
20327         }
20328         break;
20329       } while (V.hasOneUse());
20330       break;
20331     }
20332     // Break out of the loop if we break out of the switch.
20333     break;
20334   }
20335
20336   if (!V.hasOneUse())
20337     // We fell out of the loop without finding a viable combining instruction.
20338     return SDValue();
20339
20340   // Merge this node's mask and our incoming mask.
20341   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20342   for (int &M : Mask)
20343     M = VMask[M];
20344   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20345                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20346
20347   // Rebuild the chain around this new shuffle.
20348   while (!Chain.empty()) {
20349     SDValue W = Chain.pop_back_val();
20350
20351     if (V.getValueType() != W.getOperand(0).getValueType())
20352       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20353
20354     switch (W.getOpcode()) {
20355     default:
20356       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20357
20358     case X86ISD::UNPCKL:
20359     case X86ISD::UNPCKH:
20360       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20361       break;
20362
20363     case X86ISD::PSHUFD:
20364     case X86ISD::PSHUFLW:
20365     case X86ISD::PSHUFHW:
20366       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20367       break;
20368     }
20369   }
20370   if (V.getValueType() != N.getValueType())
20371     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20372
20373   // Return the new chain to replace N.
20374   return V;
20375 }
20376
20377 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20378 ///
20379 /// We walk up the chain, skipping shuffles of the other half and looking
20380 /// through shuffles which switch halves trying to find a shuffle of the same
20381 /// pair of dwords.
20382 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20383                                         SelectionDAG &DAG,
20384                                         TargetLowering::DAGCombinerInfo &DCI) {
20385   assert(
20386       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20387       "Called with something other than an x86 128-bit half shuffle!");
20388   SDLoc DL(N);
20389   unsigned CombineOpcode = N.getOpcode();
20390
20391   // Walk up a single-use chain looking for a combinable shuffle.
20392   SDValue V = N.getOperand(0);
20393   for (; V.hasOneUse(); V = V.getOperand(0)) {
20394     switch (V.getOpcode()) {
20395     default:
20396       return false; // Nothing combined!
20397
20398     case ISD::BITCAST:
20399       // Skip bitcasts as we always know the type for the target specific
20400       // instructions.
20401       continue;
20402
20403     case X86ISD::PSHUFLW:
20404     case X86ISD::PSHUFHW:
20405       if (V.getOpcode() == CombineOpcode)
20406         break;
20407
20408       // Other-half shuffles are no-ops.
20409       continue;
20410     }
20411     // Break out of the loop if we break out of the switch.
20412     break;
20413   }
20414
20415   if (!V.hasOneUse())
20416     // We fell out of the loop without finding a viable combining instruction.
20417     return false;
20418
20419   // Combine away the bottom node as its shuffle will be accumulated into
20420   // a preceding shuffle.
20421   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20422
20423   // Record the old value.
20424   SDValue Old = V;
20425
20426   // Merge this node's mask and our incoming mask (adjusted to account for all
20427   // the pshufd instructions encountered).
20428   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20429   for (int &M : Mask)
20430     M = VMask[M];
20431   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20432                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20433
20434   // Check that the shuffles didn't cancel each other out. If not, we need to
20435   // combine to the new one.
20436   if (Old != V)
20437     // Replace the combinable shuffle with the combined one, updating all users
20438     // so that we re-evaluate the chain here.
20439     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20440
20441   return true;
20442 }
20443
20444 /// \brief Try to combine x86 target specific shuffles.
20445 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20446                                            TargetLowering::DAGCombinerInfo &DCI,
20447                                            const X86Subtarget *Subtarget) {
20448   SDLoc DL(N);
20449   MVT VT = N.getSimpleValueType();
20450   SmallVector<int, 4> Mask;
20451
20452   switch (N.getOpcode()) {
20453   case X86ISD::PSHUFD:
20454   case X86ISD::PSHUFLW:
20455   case X86ISD::PSHUFHW:
20456     Mask = getPSHUFShuffleMask(N);
20457     assert(Mask.size() == 4);
20458     break;
20459   default:
20460     return SDValue();
20461   }
20462
20463   // Nuke no-op shuffles that show up after combining.
20464   if (isNoopShuffleMask(Mask))
20465     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20466
20467   // Look for simplifications involving one or two shuffle instructions.
20468   SDValue V = N.getOperand(0);
20469   switch (N.getOpcode()) {
20470   default:
20471     break;
20472   case X86ISD::PSHUFLW:
20473   case X86ISD::PSHUFHW:
20474     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20475
20476     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20477       return SDValue(); // We combined away this shuffle, so we're done.
20478
20479     // See if this reduces to a PSHUFD which is no more expensive and can
20480     // combine with more operations. Note that it has to at least flip the
20481     // dwords as otherwise it would have been removed as a no-op.
20482     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20483       int DMask[] = {0, 1, 2, 3};
20484       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20485       DMask[DOffset + 0] = DOffset + 1;
20486       DMask[DOffset + 1] = DOffset + 0;
20487       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20488       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20489       DCI.AddToWorklist(V.getNode());
20490       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20491                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20492       DCI.AddToWorklist(V.getNode());
20493       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20494     }
20495
20496     // Look for shuffle patterns which can be implemented as a single unpack.
20497     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20498     // only works when we have a PSHUFD followed by two half-shuffles.
20499     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20500         (V.getOpcode() == X86ISD::PSHUFLW ||
20501          V.getOpcode() == X86ISD::PSHUFHW) &&
20502         V.getOpcode() != N.getOpcode() &&
20503         V.hasOneUse()) {
20504       SDValue D = V.getOperand(0);
20505       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20506         D = D.getOperand(0);
20507       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20508         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20509         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20510         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20511         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20512         int WordMask[8];
20513         for (int i = 0; i < 4; ++i) {
20514           WordMask[i + NOffset] = Mask[i] + NOffset;
20515           WordMask[i + VOffset] = VMask[i] + VOffset;
20516         }
20517         // Map the word mask through the DWord mask.
20518         int MappedMask[8];
20519         for (int i = 0; i < 8; ++i)
20520           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20521         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20522             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20523           // We can replace all three shuffles with an unpack.
20524           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20525           DCI.AddToWorklist(V.getNode());
20526           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20527                                                 : X86ISD::UNPCKH,
20528                              DL, VT, V, V);
20529         }
20530       }
20531     }
20532
20533     break;
20534
20535   case X86ISD::PSHUFD:
20536     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20537       return NewN;
20538
20539     break;
20540   }
20541
20542   return SDValue();
20543 }
20544
20545 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20546 ///
20547 /// We combine this directly on the abstract vector shuffle nodes so it is
20548 /// easier to generically match. We also insert dummy vector shuffle nodes for
20549 /// the operands which explicitly discard the lanes which are unused by this
20550 /// operation to try to flow through the rest of the combiner the fact that
20551 /// they're unused.
20552 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20553   SDLoc DL(N);
20554   EVT VT = N->getValueType(0);
20555
20556   // We only handle target-independent shuffles.
20557   // FIXME: It would be easy and harmless to use the target shuffle mask
20558   // extraction tool to support more.
20559   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20560     return SDValue();
20561
20562   auto *SVN = cast<ShuffleVectorSDNode>(N);
20563   ArrayRef<int> Mask = SVN->getMask();
20564   SDValue V1 = N->getOperand(0);
20565   SDValue V2 = N->getOperand(1);
20566
20567   // We require the first shuffle operand to be the SUB node, and the second to
20568   // be the ADD node.
20569   // FIXME: We should support the commuted patterns.
20570   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20571     return SDValue();
20572
20573   // If there are other uses of these operations we can't fold them.
20574   if (!V1->hasOneUse() || !V2->hasOneUse())
20575     return SDValue();
20576
20577   // Ensure that both operations have the same operands. Note that we can
20578   // commute the FADD operands.
20579   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20580   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20581       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20582     return SDValue();
20583
20584   // We're looking for blends between FADD and FSUB nodes. We insist on these
20585   // nodes being lined up in a specific expected pattern.
20586   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20587         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20588         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20589     return SDValue();
20590
20591   // Only specific types are legal at this point, assert so we notice if and
20592   // when these change.
20593   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20594           VT == MVT::v4f64) &&
20595          "Unknown vector type encountered!");
20596
20597   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20598 }
20599
20600 /// PerformShuffleCombine - Performs several different shuffle combines.
20601 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20602                                      TargetLowering::DAGCombinerInfo &DCI,
20603                                      const X86Subtarget *Subtarget) {
20604   SDLoc dl(N);
20605   SDValue N0 = N->getOperand(0);
20606   SDValue N1 = N->getOperand(1);
20607   EVT VT = N->getValueType(0);
20608
20609   // Don't create instructions with illegal types after legalize types has run.
20610   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20611   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20612     return SDValue();
20613
20614   // If we have legalized the vector types, look for blends of FADD and FSUB
20615   // nodes that we can fuse into an ADDSUB node.
20616   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20617     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20618       return AddSub;
20619
20620   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20621   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20622       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20623     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20624
20625   // During Type Legalization, when promoting illegal vector types,
20626   // the backend might introduce new shuffle dag nodes and bitcasts.
20627   //
20628   // This code performs the following transformation:
20629   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20630   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20631   //
20632   // We do this only if both the bitcast and the BINOP dag nodes have
20633   // one use. Also, perform this transformation only if the new binary
20634   // operation is legal. This is to avoid introducing dag nodes that
20635   // potentially need to be further expanded (or custom lowered) into a
20636   // less optimal sequence of dag nodes.
20637   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20638       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20639       N0.getOpcode() == ISD::BITCAST) {
20640     SDValue BC0 = N0.getOperand(0);
20641     EVT SVT = BC0.getValueType();
20642     unsigned Opcode = BC0.getOpcode();
20643     unsigned NumElts = VT.getVectorNumElements();
20644
20645     if (BC0.hasOneUse() && SVT.isVector() &&
20646         SVT.getVectorNumElements() * 2 == NumElts &&
20647         TLI.isOperationLegal(Opcode, VT)) {
20648       bool CanFold = false;
20649       switch (Opcode) {
20650       default : break;
20651       case ISD::ADD :
20652       case ISD::FADD :
20653       case ISD::SUB :
20654       case ISD::FSUB :
20655       case ISD::MUL :
20656       case ISD::FMUL :
20657         CanFold = true;
20658       }
20659
20660       unsigned SVTNumElts = SVT.getVectorNumElements();
20661       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20662       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20663         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20664       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20665         CanFold = SVOp->getMaskElt(i) < 0;
20666
20667       if (CanFold) {
20668         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20669         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20670         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20671         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20672       }
20673     }
20674   }
20675
20676   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20677   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20678   // consecutive, non-overlapping, and in the right order.
20679   SmallVector<SDValue, 16> Elts;
20680   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20681     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20682
20683   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20684   if (LD.getNode())
20685     return LD;
20686
20687   if (isTargetShuffle(N->getOpcode())) {
20688     SDValue Shuffle =
20689         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20690     if (Shuffle.getNode())
20691       return Shuffle;
20692
20693     // Try recursively combining arbitrary sequences of x86 shuffle
20694     // instructions into higher-order shuffles. We do this after combining
20695     // specific PSHUF instruction sequences into their minimal form so that we
20696     // can evaluate how many specialized shuffle instructions are involved in
20697     // a particular chain.
20698     SmallVector<int, 1> NonceMask; // Just a placeholder.
20699     NonceMask.push_back(0);
20700     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20701                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20702                                       DCI, Subtarget))
20703       return SDValue(); // This routine will use CombineTo to replace N.
20704   }
20705
20706   return SDValue();
20707 }
20708
20709 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20710 /// specific shuffle of a load can be folded into a single element load.
20711 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20712 /// shuffles have been custom lowered so we need to handle those here.
20713 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20714                                          TargetLowering::DAGCombinerInfo &DCI) {
20715   if (DCI.isBeforeLegalizeOps())
20716     return SDValue();
20717
20718   SDValue InVec = N->getOperand(0);
20719   SDValue EltNo = N->getOperand(1);
20720
20721   if (!isa<ConstantSDNode>(EltNo))
20722     return SDValue();
20723
20724   EVT OriginalVT = InVec.getValueType();
20725
20726   if (InVec.getOpcode() == ISD::BITCAST) {
20727     // Don't duplicate a load with other uses.
20728     if (!InVec.hasOneUse())
20729       return SDValue();
20730     EVT BCVT = InVec.getOperand(0).getValueType();
20731     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20732       return SDValue();
20733     InVec = InVec.getOperand(0);
20734   }
20735
20736   EVT CurrentVT = InVec.getValueType();
20737
20738   if (!isTargetShuffle(InVec.getOpcode()))
20739     return SDValue();
20740
20741   // Don't duplicate a load with other uses.
20742   if (!InVec.hasOneUse())
20743     return SDValue();
20744
20745   SmallVector<int, 16> ShuffleMask;
20746   bool UnaryShuffle;
20747   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20748                             ShuffleMask, UnaryShuffle))
20749     return SDValue();
20750
20751   // Select the input vector, guarding against out of range extract vector.
20752   unsigned NumElems = CurrentVT.getVectorNumElements();
20753   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20754   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20755   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20756                                          : InVec.getOperand(1);
20757
20758   // If inputs to shuffle are the same for both ops, then allow 2 uses
20759   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20760                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20761
20762   if (LdNode.getOpcode() == ISD::BITCAST) {
20763     // Don't duplicate a load with other uses.
20764     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20765       return SDValue();
20766
20767     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20768     LdNode = LdNode.getOperand(0);
20769   }
20770
20771   if (!ISD::isNormalLoad(LdNode.getNode()))
20772     return SDValue();
20773
20774   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20775
20776   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20777     return SDValue();
20778
20779   EVT EltVT = N->getValueType(0);
20780   // If there's a bitcast before the shuffle, check if the load type and
20781   // alignment is valid.
20782   unsigned Align = LN0->getAlignment();
20783   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20784   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20785       EltVT.getTypeForEVT(*DAG.getContext()));
20786
20787   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20788     return SDValue();
20789
20790   // All checks match so transform back to vector_shuffle so that DAG combiner
20791   // can finish the job
20792   SDLoc dl(N);
20793
20794   // Create shuffle node taking into account the case that its a unary shuffle
20795   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20796                                    : InVec.getOperand(1);
20797   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20798                                  InVec.getOperand(0), Shuffle,
20799                                  &ShuffleMask[0]);
20800   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20801   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20802                      EltNo);
20803 }
20804
20805 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20806 /// special and don't usually play with other vector types, it's better to
20807 /// handle them early to be sure we emit efficient code by avoiding
20808 /// store-load conversions.
20809 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20810   if (N->getValueType(0) != MVT::x86mmx ||
20811       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20812       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20813     return SDValue();
20814
20815   SDValue V = N->getOperand(0);
20816   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20817   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20818     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20819                        N->getValueType(0), V.getOperand(0));
20820
20821   return SDValue();
20822 }
20823
20824 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20825 /// generation and convert it from being a bunch of shuffles and extracts
20826 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20827 /// storing the value and loading scalars back, while for x64 we should
20828 /// use 64-bit extracts and shifts.
20829 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20830                                          TargetLowering::DAGCombinerInfo &DCI) {
20831   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20832   if (NewOp.getNode())
20833     return NewOp;
20834
20835   SDValue InputVector = N->getOperand(0);
20836
20837   // Detect mmx to i32 conversion through a v2i32 elt extract.
20838   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20839       N->getValueType(0) == MVT::i32 &&
20840       InputVector.getValueType() == MVT::v2i32) {
20841
20842     // The bitcast source is a direct mmx result.
20843     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20844     if (MMXSrc.getValueType() == MVT::x86mmx)
20845       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20846                          N->getValueType(0),
20847                          InputVector.getNode()->getOperand(0));
20848
20849     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20850     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20851     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20852         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20853         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20854         MMXSrcOp.getValueType() == MVT::v1i64 &&
20855         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20856       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20857                          N->getValueType(0),
20858                          MMXSrcOp.getOperand(0));
20859   }
20860
20861   // Only operate on vectors of 4 elements, where the alternative shuffling
20862   // gets to be more expensive.
20863   if (InputVector.getValueType() != MVT::v4i32)
20864     return SDValue();
20865
20866   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20867   // single use which is a sign-extend or zero-extend, and all elements are
20868   // used.
20869   SmallVector<SDNode *, 4> Uses;
20870   unsigned ExtractedElements = 0;
20871   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20872        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20873     if (UI.getUse().getResNo() != InputVector.getResNo())
20874       return SDValue();
20875
20876     SDNode *Extract = *UI;
20877     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20878       return SDValue();
20879
20880     if (Extract->getValueType(0) != MVT::i32)
20881       return SDValue();
20882     if (!Extract->hasOneUse())
20883       return SDValue();
20884     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20885         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20886       return SDValue();
20887     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20888       return SDValue();
20889
20890     // Record which element was extracted.
20891     ExtractedElements |=
20892       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20893
20894     Uses.push_back(Extract);
20895   }
20896
20897   // If not all the elements were used, this may not be worthwhile.
20898   if (ExtractedElements != 15)
20899     return SDValue();
20900
20901   // Ok, we've now decided to do the transformation.
20902   // If 64-bit shifts are legal, use the extract-shift sequence,
20903   // otherwise bounce the vector off the cache.
20904   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20905   SDValue Vals[4];
20906   SDLoc dl(InputVector);
20907
20908   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20909     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20910     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20911     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20912       DAG.getConstant(0, dl, VecIdxTy));
20913     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20914       DAG.getConstant(1, dl, VecIdxTy));
20915
20916     SDValue ShAmt = DAG.getConstant(32, dl,
20917       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20918     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20919     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20920       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20921     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20922     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20923       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20924   } else {
20925     // Store the value to a temporary stack slot.
20926     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20927     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20928       MachinePointerInfo(), false, false, 0);
20929
20930     EVT ElementType = InputVector.getValueType().getVectorElementType();
20931     unsigned EltSize = ElementType.getSizeInBits() / 8;
20932
20933     // Replace each use (extract) with a load of the appropriate element.
20934     for (unsigned i = 0; i < 4; ++i) {
20935       uint64_t Offset = EltSize * i;
20936       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
20937
20938       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20939                                        StackPtr, OffsetVal);
20940
20941       // Load the scalar.
20942       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20943                             ScalarAddr, MachinePointerInfo(),
20944                             false, false, false, 0);
20945
20946     }
20947   }
20948
20949   // Replace the extracts
20950   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20951     UE = Uses.end(); UI != UE; ++UI) {
20952     SDNode *Extract = *UI;
20953
20954     SDValue Idx = Extract->getOperand(1);
20955     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20956     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20957   }
20958
20959   // The replacement was made in place; don't return anything.
20960   return SDValue();
20961 }
20962
20963 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20964 static std::pair<unsigned, bool>
20965 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20966                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20967   if (!VT.isVector())
20968     return std::make_pair(0, false);
20969
20970   bool NeedSplit = false;
20971   switch (VT.getSimpleVT().SimpleTy) {
20972   default: return std::make_pair(0, false);
20973   case MVT::v4i64:
20974   case MVT::v2i64:
20975     if (!Subtarget->hasVLX())
20976       return std::make_pair(0, false);
20977     break;
20978   case MVT::v64i8:
20979   case MVT::v32i16:
20980     if (!Subtarget->hasBWI())
20981       return std::make_pair(0, false);
20982     break;
20983   case MVT::v16i32:
20984   case MVT::v8i64:
20985     if (!Subtarget->hasAVX512())
20986       return std::make_pair(0, false);
20987     break;
20988   case MVT::v32i8:
20989   case MVT::v16i16:
20990   case MVT::v8i32:
20991     if (!Subtarget->hasAVX2())
20992       NeedSplit = true;
20993     if (!Subtarget->hasAVX())
20994       return std::make_pair(0, false);
20995     break;
20996   case MVT::v16i8:
20997   case MVT::v8i16:
20998   case MVT::v4i32:
20999     if (!Subtarget->hasSSE2())
21000       return std::make_pair(0, false);
21001   }
21002
21003   // SSE2 has only a small subset of the operations.
21004   bool hasUnsigned = Subtarget->hasSSE41() ||
21005                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21006   bool hasSigned = Subtarget->hasSSE41() ||
21007                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21008
21009   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21010
21011   unsigned Opc = 0;
21012   // Check for x CC y ? x : y.
21013   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21014       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21015     switch (CC) {
21016     default: break;
21017     case ISD::SETULT:
21018     case ISD::SETULE:
21019       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21020     case ISD::SETUGT:
21021     case ISD::SETUGE:
21022       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21023     case ISD::SETLT:
21024     case ISD::SETLE:
21025       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21026     case ISD::SETGT:
21027     case ISD::SETGE:
21028       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21029     }
21030   // Check for x CC y ? y : x -- a min/max with reversed arms.
21031   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21032              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21033     switch (CC) {
21034     default: break;
21035     case ISD::SETULT:
21036     case ISD::SETULE:
21037       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21038     case ISD::SETUGT:
21039     case ISD::SETUGE:
21040       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21041     case ISD::SETLT:
21042     case ISD::SETLE:
21043       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21044     case ISD::SETGT:
21045     case ISD::SETGE:
21046       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21047     }
21048   }
21049
21050   return std::make_pair(Opc, NeedSplit);
21051 }
21052
21053 static SDValue
21054 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21055                                       const X86Subtarget *Subtarget) {
21056   SDLoc dl(N);
21057   SDValue Cond = N->getOperand(0);
21058   SDValue LHS = N->getOperand(1);
21059   SDValue RHS = N->getOperand(2);
21060
21061   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21062     SDValue CondSrc = Cond->getOperand(0);
21063     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21064       Cond = CondSrc->getOperand(0);
21065   }
21066
21067   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21068     return SDValue();
21069
21070   // A vselect where all conditions and data are constants can be optimized into
21071   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21072   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21073       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21074     return SDValue();
21075
21076   unsigned MaskValue = 0;
21077   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21078     return SDValue();
21079
21080   MVT VT = N->getSimpleValueType(0);
21081   unsigned NumElems = VT.getVectorNumElements();
21082   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21083   for (unsigned i = 0; i < NumElems; ++i) {
21084     // Be sure we emit undef where we can.
21085     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21086       ShuffleMask[i] = -1;
21087     else
21088       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21089   }
21090
21091   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21092   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21093     return SDValue();
21094   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21095 }
21096
21097 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21098 /// nodes.
21099 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21100                                     TargetLowering::DAGCombinerInfo &DCI,
21101                                     const X86Subtarget *Subtarget) {
21102   SDLoc DL(N);
21103   SDValue Cond = N->getOperand(0);
21104   // Get the LHS/RHS of the select.
21105   SDValue LHS = N->getOperand(1);
21106   SDValue RHS = N->getOperand(2);
21107   EVT VT = LHS.getValueType();
21108   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21109
21110   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21111   // instructions match the semantics of the common C idiom x<y?x:y but not
21112   // x<=y?x:y, because of how they handle negative zero (which can be
21113   // ignored in unsafe-math mode).
21114   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21115   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21116       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21117       (Subtarget->hasSSE2() ||
21118        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21119     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21120
21121     unsigned Opcode = 0;
21122     // Check for x CC y ? x : y.
21123     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21124         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21125       switch (CC) {
21126       default: break;
21127       case ISD::SETULT:
21128         // Converting this to a min would handle NaNs incorrectly, and swapping
21129         // the operands would cause it to handle comparisons between positive
21130         // and negative zero incorrectly.
21131         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21132           if (!DAG.getTarget().Options.UnsafeFPMath &&
21133               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21134             break;
21135           std::swap(LHS, RHS);
21136         }
21137         Opcode = X86ISD::FMIN;
21138         break;
21139       case ISD::SETOLE:
21140         // Converting this to a min would handle comparisons between positive
21141         // and negative zero incorrectly.
21142         if (!DAG.getTarget().Options.UnsafeFPMath &&
21143             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21144           break;
21145         Opcode = X86ISD::FMIN;
21146         break;
21147       case ISD::SETULE:
21148         // Converting this to a min would handle both negative zeros and NaNs
21149         // incorrectly, but we can swap the operands to fix both.
21150         std::swap(LHS, RHS);
21151       case ISD::SETOLT:
21152       case ISD::SETLT:
21153       case ISD::SETLE:
21154         Opcode = X86ISD::FMIN;
21155         break;
21156
21157       case ISD::SETOGE:
21158         // Converting this to a max would handle comparisons between positive
21159         // and negative zero incorrectly.
21160         if (!DAG.getTarget().Options.UnsafeFPMath &&
21161             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21162           break;
21163         Opcode = X86ISD::FMAX;
21164         break;
21165       case ISD::SETUGT:
21166         // Converting this to a max would handle NaNs incorrectly, and swapping
21167         // the operands would cause it to handle comparisons between positive
21168         // and negative zero incorrectly.
21169         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21170           if (!DAG.getTarget().Options.UnsafeFPMath &&
21171               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21172             break;
21173           std::swap(LHS, RHS);
21174         }
21175         Opcode = X86ISD::FMAX;
21176         break;
21177       case ISD::SETUGE:
21178         // Converting this to a max would handle both negative zeros and NaNs
21179         // incorrectly, but we can swap the operands to fix both.
21180         std::swap(LHS, RHS);
21181       case ISD::SETOGT:
21182       case ISD::SETGT:
21183       case ISD::SETGE:
21184         Opcode = X86ISD::FMAX;
21185         break;
21186       }
21187     // Check for x CC y ? y : x -- a min/max with reversed arms.
21188     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21189                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21190       switch (CC) {
21191       default: break;
21192       case ISD::SETOGE:
21193         // Converting this to a min would handle comparisons between positive
21194         // and negative zero incorrectly, and swapping the operands would
21195         // cause it to handle NaNs incorrectly.
21196         if (!DAG.getTarget().Options.UnsafeFPMath &&
21197             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21198           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21199             break;
21200           std::swap(LHS, RHS);
21201         }
21202         Opcode = X86ISD::FMIN;
21203         break;
21204       case ISD::SETUGT:
21205         // Converting this to a min would handle NaNs incorrectly.
21206         if (!DAG.getTarget().Options.UnsafeFPMath &&
21207             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21208           break;
21209         Opcode = X86ISD::FMIN;
21210         break;
21211       case ISD::SETUGE:
21212         // Converting this to a min would handle both negative zeros and NaNs
21213         // incorrectly, but we can swap the operands to fix both.
21214         std::swap(LHS, RHS);
21215       case ISD::SETOGT:
21216       case ISD::SETGT:
21217       case ISD::SETGE:
21218         Opcode = X86ISD::FMIN;
21219         break;
21220
21221       case ISD::SETULT:
21222         // Converting this to a max would handle NaNs incorrectly.
21223         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21224           break;
21225         Opcode = X86ISD::FMAX;
21226         break;
21227       case ISD::SETOLE:
21228         // Converting this to a max would handle comparisons between positive
21229         // and negative zero incorrectly, and swapping the operands would
21230         // cause it to handle NaNs incorrectly.
21231         if (!DAG.getTarget().Options.UnsafeFPMath &&
21232             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21233           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21234             break;
21235           std::swap(LHS, RHS);
21236         }
21237         Opcode = X86ISD::FMAX;
21238         break;
21239       case ISD::SETULE:
21240         // Converting this to a max would handle both negative zeros and NaNs
21241         // incorrectly, but we can swap the operands to fix both.
21242         std::swap(LHS, RHS);
21243       case ISD::SETOLT:
21244       case ISD::SETLT:
21245       case ISD::SETLE:
21246         Opcode = X86ISD::FMAX;
21247         break;
21248       }
21249     }
21250
21251     if (Opcode)
21252       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21253   }
21254
21255   EVT CondVT = Cond.getValueType();
21256   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21257       CondVT.getVectorElementType() == MVT::i1) {
21258     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21259     // lowering on KNL. In this case we convert it to
21260     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21261     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21262     // Since SKX these selects have a proper lowering.
21263     EVT OpVT = LHS.getValueType();
21264     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21265         (OpVT.getVectorElementType() == MVT::i8 ||
21266          OpVT.getVectorElementType() == MVT::i16) &&
21267         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21268       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21269       DCI.AddToWorklist(Cond.getNode());
21270       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21271     }
21272   }
21273   // If this is a select between two integer constants, try to do some
21274   // optimizations.
21275   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21276     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21277       // Don't do this for crazy integer types.
21278       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21279         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21280         // so that TrueC (the true value) is larger than FalseC.
21281         bool NeedsCondInvert = false;
21282
21283         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21284             // Efficiently invertible.
21285             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21286              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21287               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21288           NeedsCondInvert = true;
21289           std::swap(TrueC, FalseC);
21290         }
21291
21292         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21293         if (FalseC->getAPIntValue() == 0 &&
21294             TrueC->getAPIntValue().isPowerOf2()) {
21295           if (NeedsCondInvert) // Invert the condition if needed.
21296             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21297                                DAG.getConstant(1, DL, Cond.getValueType()));
21298
21299           // Zero extend the condition if needed.
21300           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21301
21302           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21303           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21304                              DAG.getConstant(ShAmt, DL, MVT::i8));
21305         }
21306
21307         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21308         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21309           if (NeedsCondInvert) // Invert the condition if needed.
21310             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21311                                DAG.getConstant(1, DL, Cond.getValueType()));
21312
21313           // Zero extend the condition if needed.
21314           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21315                              FalseC->getValueType(0), Cond);
21316           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21317                              SDValue(FalseC, 0));
21318         }
21319
21320         // Optimize cases that will turn into an LEA instruction.  This requires
21321         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21322         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21323           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21324           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21325
21326           bool isFastMultiplier = false;
21327           if (Diff < 10) {
21328             switch ((unsigned char)Diff) {
21329               default: break;
21330               case 1:  // result = add base, cond
21331               case 2:  // result = lea base(    , cond*2)
21332               case 3:  // result = lea base(cond, cond*2)
21333               case 4:  // result = lea base(    , cond*4)
21334               case 5:  // result = lea base(cond, cond*4)
21335               case 8:  // result = lea base(    , cond*8)
21336               case 9:  // result = lea base(cond, cond*8)
21337                 isFastMultiplier = true;
21338                 break;
21339             }
21340           }
21341
21342           if (isFastMultiplier) {
21343             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21344             if (NeedsCondInvert) // Invert the condition if needed.
21345               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21346                                  DAG.getConstant(1, DL, Cond.getValueType()));
21347
21348             // Zero extend the condition if needed.
21349             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21350                                Cond);
21351             // Scale the condition by the difference.
21352             if (Diff != 1)
21353               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21354                                  DAG.getConstant(Diff, DL,
21355                                                  Cond.getValueType()));
21356
21357             // Add the base if non-zero.
21358             if (FalseC->getAPIntValue() != 0)
21359               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21360                                  SDValue(FalseC, 0));
21361             return Cond;
21362           }
21363         }
21364       }
21365   }
21366
21367   // Canonicalize max and min:
21368   // (x > y) ? x : y -> (x >= y) ? x : y
21369   // (x < y) ? x : y -> (x <= y) ? x : y
21370   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21371   // the need for an extra compare
21372   // against zero. e.g.
21373   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21374   // subl   %esi, %edi
21375   // testl  %edi, %edi
21376   // movl   $0, %eax
21377   // cmovgl %edi, %eax
21378   // =>
21379   // xorl   %eax, %eax
21380   // subl   %esi, $edi
21381   // cmovsl %eax, %edi
21382   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21383       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21384       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21385     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21386     switch (CC) {
21387     default: break;
21388     case ISD::SETLT:
21389     case ISD::SETGT: {
21390       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21391       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21392                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21393       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21394     }
21395     }
21396   }
21397
21398   // Early exit check
21399   if (!TLI.isTypeLegal(VT))
21400     return SDValue();
21401
21402   // Match VSELECTs into subs with unsigned saturation.
21403   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21404       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21405       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21406        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21407     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21408
21409     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21410     // left side invert the predicate to simplify logic below.
21411     SDValue Other;
21412     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21413       Other = RHS;
21414       CC = ISD::getSetCCInverse(CC, true);
21415     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21416       Other = LHS;
21417     }
21418
21419     if (Other.getNode() && Other->getNumOperands() == 2 &&
21420         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21421       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21422       SDValue CondRHS = Cond->getOperand(1);
21423
21424       // Look for a general sub with unsigned saturation first.
21425       // x >= y ? x-y : 0 --> subus x, y
21426       // x >  y ? x-y : 0 --> subus x, y
21427       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21428           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21429         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21430
21431       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21432         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21433           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21434             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21435               // If the RHS is a constant we have to reverse the const
21436               // canonicalization.
21437               // x > C-1 ? x+-C : 0 --> subus x, C
21438               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21439                   CondRHSConst->getAPIntValue() ==
21440                       (-OpRHSConst->getAPIntValue() - 1))
21441                 return DAG.getNode(
21442                     X86ISD::SUBUS, DL, VT, OpLHS,
21443                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21444
21445           // Another special case: If C was a sign bit, the sub has been
21446           // canonicalized into a xor.
21447           // FIXME: Would it be better to use computeKnownBits to determine
21448           //        whether it's safe to decanonicalize the xor?
21449           // x s< 0 ? x^C : 0 --> subus x, C
21450           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21451               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21452               OpRHSConst->getAPIntValue().isSignBit())
21453             // Note that we have to rebuild the RHS constant here to ensure we
21454             // don't rely on particular values of undef lanes.
21455             return DAG.getNode(
21456                 X86ISD::SUBUS, DL, VT, OpLHS,
21457                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21458         }
21459     }
21460   }
21461
21462   // Try to match a min/max vector operation.
21463   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21464     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21465     unsigned Opc = ret.first;
21466     bool NeedSplit = ret.second;
21467
21468     if (Opc && NeedSplit) {
21469       unsigned NumElems = VT.getVectorNumElements();
21470       // Extract the LHS vectors
21471       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21472       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21473
21474       // Extract the RHS vectors
21475       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21476       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21477
21478       // Create min/max for each subvector
21479       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21480       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21481
21482       // Merge the result
21483       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21484     } else if (Opc)
21485       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21486   }
21487
21488   // Simplify vector selection if condition value type matches vselect
21489   // operand type
21490   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21491     assert(Cond.getValueType().isVector() &&
21492            "vector select expects a vector selector!");
21493
21494     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21495     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21496
21497     // Try invert the condition if true value is not all 1s and false value
21498     // is not all 0s.
21499     if (!TValIsAllOnes && !FValIsAllZeros &&
21500         // Check if the selector will be produced by CMPP*/PCMP*
21501         Cond.getOpcode() == ISD::SETCC &&
21502         // Check if SETCC has already been promoted
21503         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21504       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21505       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21506
21507       if (TValIsAllZeros || FValIsAllOnes) {
21508         SDValue CC = Cond.getOperand(2);
21509         ISD::CondCode NewCC =
21510           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21511                                Cond.getOperand(0).getValueType().isInteger());
21512         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21513         std::swap(LHS, RHS);
21514         TValIsAllOnes = FValIsAllOnes;
21515         FValIsAllZeros = TValIsAllZeros;
21516       }
21517     }
21518
21519     if (TValIsAllOnes || FValIsAllZeros) {
21520       SDValue Ret;
21521
21522       if (TValIsAllOnes && FValIsAllZeros)
21523         Ret = Cond;
21524       else if (TValIsAllOnes)
21525         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21526                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21527       else if (FValIsAllZeros)
21528         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21529                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21530
21531       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21532     }
21533   }
21534
21535   // We should generate an X86ISD::BLENDI from a vselect if its argument
21536   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21537   // constants. This specific pattern gets generated when we split a
21538   // selector for a 512 bit vector in a machine without AVX512 (but with
21539   // 256-bit vectors), during legalization:
21540   //
21541   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21542   //
21543   // Iff we find this pattern and the build_vectors are built from
21544   // constants, we translate the vselect into a shuffle_vector that we
21545   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21546   if ((N->getOpcode() == ISD::VSELECT ||
21547        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21548       !DCI.isBeforeLegalize()) {
21549     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21550     if (Shuffle.getNode())
21551       return Shuffle;
21552   }
21553
21554   // If this is a *dynamic* select (non-constant condition) and we can match
21555   // this node with one of the variable blend instructions, restructure the
21556   // condition so that the blends can use the high bit of each element and use
21557   // SimplifyDemandedBits to simplify the condition operand.
21558   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21559       !DCI.isBeforeLegalize() &&
21560       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21561     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21562
21563     // Don't optimize vector selects that map to mask-registers.
21564     if (BitWidth == 1)
21565       return SDValue();
21566
21567     // We can only handle the cases where VSELECT is directly legal on the
21568     // subtarget. We custom lower VSELECT nodes with constant conditions and
21569     // this makes it hard to see whether a dynamic VSELECT will correctly
21570     // lower, so we both check the operation's status and explicitly handle the
21571     // cases where a *dynamic* blend will fail even though a constant-condition
21572     // blend could be custom lowered.
21573     // FIXME: We should find a better way to handle this class of problems.
21574     // Potentially, we should combine constant-condition vselect nodes
21575     // pre-legalization into shuffles and not mark as many types as custom
21576     // lowered.
21577     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21578       return SDValue();
21579     // FIXME: We don't support i16-element blends currently. We could and
21580     // should support them by making *all* the bits in the condition be set
21581     // rather than just the high bit and using an i8-element blend.
21582     if (VT.getScalarType() == MVT::i16)
21583       return SDValue();
21584     // Dynamic blending was only available from SSE4.1 onward.
21585     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21586       return SDValue();
21587     // Byte blends are only available in AVX2
21588     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21589         !Subtarget->hasAVX2())
21590       return SDValue();
21591
21592     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21593     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21594
21595     APInt KnownZero, KnownOne;
21596     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21597                                           DCI.isBeforeLegalizeOps());
21598     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21599         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21600                                  TLO)) {
21601       // If we changed the computation somewhere in the DAG, this change
21602       // will affect all users of Cond.
21603       // Make sure it is fine and update all the nodes so that we do not
21604       // use the generic VSELECT anymore. Otherwise, we may perform
21605       // wrong optimizations as we messed up with the actual expectation
21606       // for the vector boolean values.
21607       if (Cond != TLO.Old) {
21608         // Check all uses of that condition operand to check whether it will be
21609         // consumed by non-BLEND instructions, which may depend on all bits are
21610         // set properly.
21611         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21612              I != E; ++I)
21613           if (I->getOpcode() != ISD::VSELECT)
21614             // TODO: Add other opcodes eventually lowered into BLEND.
21615             return SDValue();
21616
21617         // Update all the users of the condition, before committing the change,
21618         // so that the VSELECT optimizations that expect the correct vector
21619         // boolean value will not be triggered.
21620         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21621              I != E; ++I)
21622           DAG.ReplaceAllUsesOfValueWith(
21623               SDValue(*I, 0),
21624               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21625                           Cond, I->getOperand(1), I->getOperand(2)));
21626         DCI.CommitTargetLoweringOpt(TLO);
21627         return SDValue();
21628       }
21629       // At this point, only Cond is changed. Change the condition
21630       // just for N to keep the opportunity to optimize all other
21631       // users their own way.
21632       DAG.ReplaceAllUsesOfValueWith(
21633           SDValue(N, 0),
21634           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21635                       TLO.New, N->getOperand(1), N->getOperand(2)));
21636       return SDValue();
21637     }
21638   }
21639
21640   return SDValue();
21641 }
21642
21643 // Check whether a boolean test is testing a boolean value generated by
21644 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21645 // code.
21646 //
21647 // Simplify the following patterns:
21648 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21649 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21650 // to (Op EFLAGS Cond)
21651 //
21652 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21653 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21654 // to (Op EFLAGS !Cond)
21655 //
21656 // where Op could be BRCOND or CMOV.
21657 //
21658 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21659   // Quit if not CMP and SUB with its value result used.
21660   if (Cmp.getOpcode() != X86ISD::CMP &&
21661       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21662       return SDValue();
21663
21664   // Quit if not used as a boolean value.
21665   if (CC != X86::COND_E && CC != X86::COND_NE)
21666     return SDValue();
21667
21668   // Check CMP operands. One of them should be 0 or 1 and the other should be
21669   // an SetCC or extended from it.
21670   SDValue Op1 = Cmp.getOperand(0);
21671   SDValue Op2 = Cmp.getOperand(1);
21672
21673   SDValue SetCC;
21674   const ConstantSDNode* C = nullptr;
21675   bool needOppositeCond = (CC == X86::COND_E);
21676   bool checkAgainstTrue = false; // Is it a comparison against 1?
21677
21678   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21679     SetCC = Op2;
21680   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21681     SetCC = Op1;
21682   else // Quit if all operands are not constants.
21683     return SDValue();
21684
21685   if (C->getZExtValue() == 1) {
21686     needOppositeCond = !needOppositeCond;
21687     checkAgainstTrue = true;
21688   } else if (C->getZExtValue() != 0)
21689     // Quit if the constant is neither 0 or 1.
21690     return SDValue();
21691
21692   bool truncatedToBoolWithAnd = false;
21693   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21694   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21695          SetCC.getOpcode() == ISD::TRUNCATE ||
21696          SetCC.getOpcode() == ISD::AND) {
21697     if (SetCC.getOpcode() == ISD::AND) {
21698       int OpIdx = -1;
21699       ConstantSDNode *CS;
21700       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21701           CS->getZExtValue() == 1)
21702         OpIdx = 1;
21703       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21704           CS->getZExtValue() == 1)
21705         OpIdx = 0;
21706       if (OpIdx == -1)
21707         break;
21708       SetCC = SetCC.getOperand(OpIdx);
21709       truncatedToBoolWithAnd = true;
21710     } else
21711       SetCC = SetCC.getOperand(0);
21712   }
21713
21714   switch (SetCC.getOpcode()) {
21715   case X86ISD::SETCC_CARRY:
21716     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21717     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21718     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21719     // truncated to i1 using 'and'.
21720     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21721       break;
21722     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21723            "Invalid use of SETCC_CARRY!");
21724     // FALL THROUGH
21725   case X86ISD::SETCC:
21726     // Set the condition code or opposite one if necessary.
21727     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21728     if (needOppositeCond)
21729       CC = X86::GetOppositeBranchCondition(CC);
21730     return SetCC.getOperand(1);
21731   case X86ISD::CMOV: {
21732     // Check whether false/true value has canonical one, i.e. 0 or 1.
21733     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21734     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21735     // Quit if true value is not a constant.
21736     if (!TVal)
21737       return SDValue();
21738     // Quit if false value is not a constant.
21739     if (!FVal) {
21740       SDValue Op = SetCC.getOperand(0);
21741       // Skip 'zext' or 'trunc' node.
21742       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21743           Op.getOpcode() == ISD::TRUNCATE)
21744         Op = Op.getOperand(0);
21745       // A special case for rdrand/rdseed, where 0 is set if false cond is
21746       // found.
21747       if ((Op.getOpcode() != X86ISD::RDRAND &&
21748            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21749         return SDValue();
21750     }
21751     // Quit if false value is not the constant 0 or 1.
21752     bool FValIsFalse = true;
21753     if (FVal && FVal->getZExtValue() != 0) {
21754       if (FVal->getZExtValue() != 1)
21755         return SDValue();
21756       // If FVal is 1, opposite cond is needed.
21757       needOppositeCond = !needOppositeCond;
21758       FValIsFalse = false;
21759     }
21760     // Quit if TVal is not the constant opposite of FVal.
21761     if (FValIsFalse && TVal->getZExtValue() != 1)
21762       return SDValue();
21763     if (!FValIsFalse && TVal->getZExtValue() != 0)
21764       return SDValue();
21765     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21766     if (needOppositeCond)
21767       CC = X86::GetOppositeBranchCondition(CC);
21768     return SetCC.getOperand(3);
21769   }
21770   }
21771
21772   return SDValue();
21773 }
21774
21775 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21776 /// Match:
21777 ///   (X86or (X86setcc) (X86setcc))
21778 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21779 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21780                                            X86::CondCode &CC1, SDValue &Flags,
21781                                            bool &isAnd) {
21782   if (Cond->getOpcode() == X86ISD::CMP) {
21783     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21784     if (!CondOp1C || !CondOp1C->isNullValue())
21785       return false;
21786
21787     Cond = Cond->getOperand(0);
21788   }
21789
21790   isAnd = false;
21791
21792   SDValue SetCC0, SetCC1;
21793   switch (Cond->getOpcode()) {
21794   default: return false;
21795   case ISD::AND:
21796   case X86ISD::AND:
21797     isAnd = true;
21798     // fallthru
21799   case ISD::OR:
21800   case X86ISD::OR:
21801     SetCC0 = Cond->getOperand(0);
21802     SetCC1 = Cond->getOperand(1);
21803     break;
21804   };
21805
21806   // Make sure we have SETCC nodes, using the same flags value.
21807   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21808       SetCC1.getOpcode() != X86ISD::SETCC ||
21809       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21810     return false;
21811
21812   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21813   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21814   Flags = SetCC0->getOperand(1);
21815   return true;
21816 }
21817
21818 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21819 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21820                                   TargetLowering::DAGCombinerInfo &DCI,
21821                                   const X86Subtarget *Subtarget) {
21822   SDLoc DL(N);
21823
21824   // If the flag operand isn't dead, don't touch this CMOV.
21825   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21826     return SDValue();
21827
21828   SDValue FalseOp = N->getOperand(0);
21829   SDValue TrueOp = N->getOperand(1);
21830   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21831   SDValue Cond = N->getOperand(3);
21832
21833   if (CC == X86::COND_E || CC == X86::COND_NE) {
21834     switch (Cond.getOpcode()) {
21835     default: break;
21836     case X86ISD::BSR:
21837     case X86ISD::BSF:
21838       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21839       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21840         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21841     }
21842   }
21843
21844   SDValue Flags;
21845
21846   Flags = checkBoolTestSetCCCombine(Cond, CC);
21847   if (Flags.getNode() &&
21848       // Extra check as FCMOV only supports a subset of X86 cond.
21849       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21850     SDValue Ops[] = { FalseOp, TrueOp,
21851                       DAG.getConstant(CC, DL, MVT::i8), Flags };
21852     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21853   }
21854
21855   // If this is a select between two integer constants, try to do some
21856   // optimizations.  Note that the operands are ordered the opposite of SELECT
21857   // operands.
21858   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21859     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21860       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21861       // larger than FalseC (the false value).
21862       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21863         CC = X86::GetOppositeBranchCondition(CC);
21864         std::swap(TrueC, FalseC);
21865         std::swap(TrueOp, FalseOp);
21866       }
21867
21868       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21869       // This is efficient for any integer data type (including i8/i16) and
21870       // shift amount.
21871       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21872         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21873                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21874
21875         // Zero extend the condition if needed.
21876         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21877
21878         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21879         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21880                            DAG.getConstant(ShAmt, DL, MVT::i8));
21881         if (N->getNumValues() == 2)  // Dead flag value?
21882           return DCI.CombineTo(N, Cond, SDValue());
21883         return Cond;
21884       }
21885
21886       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21887       // for any integer data type, including i8/i16.
21888       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21889         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21890                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21891
21892         // Zero extend the condition if needed.
21893         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21894                            FalseC->getValueType(0), Cond);
21895         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21896                            SDValue(FalseC, 0));
21897
21898         if (N->getNumValues() == 2)  // Dead flag value?
21899           return DCI.CombineTo(N, Cond, SDValue());
21900         return Cond;
21901       }
21902
21903       // Optimize cases that will turn into an LEA instruction.  This requires
21904       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21905       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21906         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21907         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21908
21909         bool isFastMultiplier = false;
21910         if (Diff < 10) {
21911           switch ((unsigned char)Diff) {
21912           default: break;
21913           case 1:  // result = add base, cond
21914           case 2:  // result = lea base(    , cond*2)
21915           case 3:  // result = lea base(cond, cond*2)
21916           case 4:  // result = lea base(    , cond*4)
21917           case 5:  // result = lea base(cond, cond*4)
21918           case 8:  // result = lea base(    , cond*8)
21919           case 9:  // result = lea base(cond, cond*8)
21920             isFastMultiplier = true;
21921             break;
21922           }
21923         }
21924
21925         if (isFastMultiplier) {
21926           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21927           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21928                              DAG.getConstant(CC, DL, MVT::i8), Cond);
21929           // Zero extend the condition if needed.
21930           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21931                              Cond);
21932           // Scale the condition by the difference.
21933           if (Diff != 1)
21934             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21935                                DAG.getConstant(Diff, DL, Cond.getValueType()));
21936
21937           // Add the base if non-zero.
21938           if (FalseC->getAPIntValue() != 0)
21939             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21940                                SDValue(FalseC, 0));
21941           if (N->getNumValues() == 2)  // Dead flag value?
21942             return DCI.CombineTo(N, Cond, SDValue());
21943           return Cond;
21944         }
21945       }
21946     }
21947   }
21948
21949   // Handle these cases:
21950   //   (select (x != c), e, c) -> select (x != c), e, x),
21951   //   (select (x == c), c, e) -> select (x == c), x, e)
21952   // where the c is an integer constant, and the "select" is the combination
21953   // of CMOV and CMP.
21954   //
21955   // The rationale for this change is that the conditional-move from a constant
21956   // needs two instructions, however, conditional-move from a register needs
21957   // only one instruction.
21958   //
21959   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21960   //  some instruction-combining opportunities. This opt needs to be
21961   //  postponed as late as possible.
21962   //
21963   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21964     // the DCI.xxxx conditions are provided to postpone the optimization as
21965     // late as possible.
21966
21967     ConstantSDNode *CmpAgainst = nullptr;
21968     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21969         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21970         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21971
21972       if (CC == X86::COND_NE &&
21973           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21974         CC = X86::GetOppositeBranchCondition(CC);
21975         std::swap(TrueOp, FalseOp);
21976       }
21977
21978       if (CC == X86::COND_E &&
21979           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21980         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21981                           DAG.getConstant(CC, DL, MVT::i8), Cond };
21982         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21983       }
21984     }
21985   }
21986
21987   // Fold and/or of setcc's to double CMOV:
21988   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21989   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21990   //
21991   // This combine lets us generate:
21992   //   cmovcc1 (jcc1 if we don't have CMOV)
21993   //   cmovcc2 (same)
21994   // instead of:
21995   //   setcc1
21996   //   setcc2
21997   //   and/or
21998   //   cmovne (jne if we don't have CMOV)
21999   // When we can't use the CMOV instruction, it might increase branch
22000   // mispredicts.
22001   // When we can use CMOV, or when there is no mispredict, this improves
22002   // throughput and reduces register pressure.
22003   //
22004   if (CC == X86::COND_NE) {
22005     SDValue Flags;
22006     X86::CondCode CC0, CC1;
22007     bool isAndSetCC;
22008     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22009       if (isAndSetCC) {
22010         std::swap(FalseOp, TrueOp);
22011         CC0 = X86::GetOppositeBranchCondition(CC0);
22012         CC1 = X86::GetOppositeBranchCondition(CC1);
22013       }
22014
22015       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22016         Flags};
22017       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22018       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22019       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22020       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22021       return CMOV;
22022     }
22023   }
22024
22025   return SDValue();
22026 }
22027
22028 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22029                                                 const X86Subtarget *Subtarget) {
22030   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22031   switch (IntNo) {
22032   default: return SDValue();
22033   // SSE/AVX/AVX2 blend intrinsics.
22034   case Intrinsic::x86_avx2_pblendvb:
22035     // Don't try to simplify this intrinsic if we don't have AVX2.
22036     if (!Subtarget->hasAVX2())
22037       return SDValue();
22038     // FALL-THROUGH
22039   case Intrinsic::x86_avx_blendv_pd_256:
22040   case Intrinsic::x86_avx_blendv_ps_256:
22041     // Don't try to simplify this intrinsic if we don't have AVX.
22042     if (!Subtarget->hasAVX())
22043       return SDValue();
22044     // FALL-THROUGH
22045   case Intrinsic::x86_sse41_blendvps:
22046   case Intrinsic::x86_sse41_blendvpd:
22047   case Intrinsic::x86_sse41_pblendvb: {
22048     SDValue Op0 = N->getOperand(1);
22049     SDValue Op1 = N->getOperand(2);
22050     SDValue Mask = N->getOperand(3);
22051
22052     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22053     if (!Subtarget->hasSSE41())
22054       return SDValue();
22055
22056     // fold (blend A, A, Mask) -> A
22057     if (Op0 == Op1)
22058       return Op0;
22059     // fold (blend A, B, allZeros) -> A
22060     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22061       return Op0;
22062     // fold (blend A, B, allOnes) -> B
22063     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22064       return Op1;
22065
22066     // Simplify the case where the mask is a constant i32 value.
22067     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22068       if (C->isNullValue())
22069         return Op0;
22070       if (C->isAllOnesValue())
22071         return Op1;
22072     }
22073
22074     return SDValue();
22075   }
22076
22077   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22078   case Intrinsic::x86_sse2_psrai_w:
22079   case Intrinsic::x86_sse2_psrai_d:
22080   case Intrinsic::x86_avx2_psrai_w:
22081   case Intrinsic::x86_avx2_psrai_d:
22082   case Intrinsic::x86_sse2_psra_w:
22083   case Intrinsic::x86_sse2_psra_d:
22084   case Intrinsic::x86_avx2_psra_w:
22085   case Intrinsic::x86_avx2_psra_d: {
22086     SDValue Op0 = N->getOperand(1);
22087     SDValue Op1 = N->getOperand(2);
22088     EVT VT = Op0.getValueType();
22089     assert(VT.isVector() && "Expected a vector type!");
22090
22091     if (isa<BuildVectorSDNode>(Op1))
22092       Op1 = Op1.getOperand(0);
22093
22094     if (!isa<ConstantSDNode>(Op1))
22095       return SDValue();
22096
22097     EVT SVT = VT.getVectorElementType();
22098     unsigned SVTBits = SVT.getSizeInBits();
22099
22100     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22101     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22102     uint64_t ShAmt = C.getZExtValue();
22103
22104     // Don't try to convert this shift into a ISD::SRA if the shift
22105     // count is bigger than or equal to the element size.
22106     if (ShAmt >= SVTBits)
22107       return SDValue();
22108
22109     // Trivial case: if the shift count is zero, then fold this
22110     // into the first operand.
22111     if (ShAmt == 0)
22112       return Op0;
22113
22114     // Replace this packed shift intrinsic with a target independent
22115     // shift dag node.
22116     SDLoc DL(N);
22117     SDValue Splat = DAG.getConstant(C, DL, VT);
22118     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22119   }
22120   }
22121 }
22122
22123 /// PerformMulCombine - Optimize a single multiply with constant into two
22124 /// in order to implement it with two cheaper instructions, e.g.
22125 /// LEA + SHL, LEA + LEA.
22126 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22127                                  TargetLowering::DAGCombinerInfo &DCI) {
22128   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22129     return SDValue();
22130
22131   EVT VT = N->getValueType(0);
22132   if (VT != MVT::i64 && VT != MVT::i32)
22133     return SDValue();
22134
22135   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22136   if (!C)
22137     return SDValue();
22138   uint64_t MulAmt = C->getZExtValue();
22139   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22140     return SDValue();
22141
22142   uint64_t MulAmt1 = 0;
22143   uint64_t MulAmt2 = 0;
22144   if ((MulAmt % 9) == 0) {
22145     MulAmt1 = 9;
22146     MulAmt2 = MulAmt / 9;
22147   } else if ((MulAmt % 5) == 0) {
22148     MulAmt1 = 5;
22149     MulAmt2 = MulAmt / 5;
22150   } else if ((MulAmt % 3) == 0) {
22151     MulAmt1 = 3;
22152     MulAmt2 = MulAmt / 3;
22153   }
22154   if (MulAmt2 &&
22155       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22156     SDLoc DL(N);
22157
22158     if (isPowerOf2_64(MulAmt2) &&
22159         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22160       // If second multiplifer is pow2, issue it first. We want the multiply by
22161       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22162       // is an add.
22163       std::swap(MulAmt1, MulAmt2);
22164
22165     SDValue NewMul;
22166     if (isPowerOf2_64(MulAmt1))
22167       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22168                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22169     else
22170       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22171                            DAG.getConstant(MulAmt1, DL, VT));
22172
22173     if (isPowerOf2_64(MulAmt2))
22174       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22175                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22176     else
22177       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22178                            DAG.getConstant(MulAmt2, DL, VT));
22179
22180     // Do not add new nodes to DAG combiner worklist.
22181     DCI.CombineTo(N, NewMul, false);
22182   }
22183   return SDValue();
22184 }
22185
22186 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22187   SDValue N0 = N->getOperand(0);
22188   SDValue N1 = N->getOperand(1);
22189   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22190   EVT VT = N0.getValueType();
22191
22192   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22193   // since the result of setcc_c is all zero's or all ones.
22194   if (VT.isInteger() && !VT.isVector() &&
22195       N1C && N0.getOpcode() == ISD::AND &&
22196       N0.getOperand(1).getOpcode() == ISD::Constant) {
22197     SDValue N00 = N0.getOperand(0);
22198     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22199         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22200           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22201          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22202       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22203       APInt ShAmt = N1C->getAPIntValue();
22204       Mask = Mask.shl(ShAmt);
22205       if (Mask != 0) {
22206         SDLoc DL(N);
22207         return DAG.getNode(ISD::AND, DL, VT,
22208                            N00, DAG.getConstant(Mask, DL, VT));
22209       }
22210     }
22211   }
22212
22213   // Hardware support for vector shifts is sparse which makes us scalarize the
22214   // vector operations in many cases. Also, on sandybridge ADD is faster than
22215   // shl.
22216   // (shl V, 1) -> add V,V
22217   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22218     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22219       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22220       // We shift all of the values by one. In many cases we do not have
22221       // hardware support for this operation. This is better expressed as an ADD
22222       // of two values.
22223       if (N1SplatC->getZExtValue() == 1)
22224         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22225     }
22226
22227   return SDValue();
22228 }
22229
22230 /// \brief Returns a vector of 0s if the node in input is a vector logical
22231 /// shift by a constant amount which is known to be bigger than or equal
22232 /// to the vector element size in bits.
22233 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22234                                       const X86Subtarget *Subtarget) {
22235   EVT VT = N->getValueType(0);
22236
22237   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22238       (!Subtarget->hasInt256() ||
22239        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22240     return SDValue();
22241
22242   SDValue Amt = N->getOperand(1);
22243   SDLoc DL(N);
22244   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22245     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22246       APInt ShiftAmt = AmtSplat->getAPIntValue();
22247       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22248
22249       // SSE2/AVX2 logical shifts always return a vector of 0s
22250       // if the shift amount is bigger than or equal to
22251       // the element size. The constant shift amount will be
22252       // encoded as a 8-bit immediate.
22253       if (ShiftAmt.trunc(8).uge(MaxAmount))
22254         return getZeroVector(VT, Subtarget, DAG, DL);
22255     }
22256
22257   return SDValue();
22258 }
22259
22260 /// PerformShiftCombine - Combine shifts.
22261 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22262                                    TargetLowering::DAGCombinerInfo &DCI,
22263                                    const X86Subtarget *Subtarget) {
22264   if (N->getOpcode() == ISD::SHL) {
22265     SDValue V = PerformSHLCombine(N, DAG);
22266     if (V.getNode()) return V;
22267   }
22268
22269   if (N->getOpcode() != ISD::SRA) {
22270     // Try to fold this logical shift into a zero vector.
22271     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22272     if (V.getNode()) return V;
22273   }
22274
22275   return SDValue();
22276 }
22277
22278 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22279 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22280 // and friends.  Likewise for OR -> CMPNEQSS.
22281 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22282                             TargetLowering::DAGCombinerInfo &DCI,
22283                             const X86Subtarget *Subtarget) {
22284   unsigned opcode;
22285
22286   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22287   // we're requiring SSE2 for both.
22288   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22289     SDValue N0 = N->getOperand(0);
22290     SDValue N1 = N->getOperand(1);
22291     SDValue CMP0 = N0->getOperand(1);
22292     SDValue CMP1 = N1->getOperand(1);
22293     SDLoc DL(N);
22294
22295     // The SETCCs should both refer to the same CMP.
22296     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22297       return SDValue();
22298
22299     SDValue CMP00 = CMP0->getOperand(0);
22300     SDValue CMP01 = CMP0->getOperand(1);
22301     EVT     VT    = CMP00.getValueType();
22302
22303     if (VT == MVT::f32 || VT == MVT::f64) {
22304       bool ExpectingFlags = false;
22305       // Check for any users that want flags:
22306       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22307            !ExpectingFlags && UI != UE; ++UI)
22308         switch (UI->getOpcode()) {
22309         default:
22310         case ISD::BR_CC:
22311         case ISD::BRCOND:
22312         case ISD::SELECT:
22313           ExpectingFlags = true;
22314           break;
22315         case ISD::CopyToReg:
22316         case ISD::SIGN_EXTEND:
22317         case ISD::ZERO_EXTEND:
22318         case ISD::ANY_EXTEND:
22319           break;
22320         }
22321
22322       if (!ExpectingFlags) {
22323         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22324         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22325
22326         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22327           X86::CondCode tmp = cc0;
22328           cc0 = cc1;
22329           cc1 = tmp;
22330         }
22331
22332         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22333             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22334           // FIXME: need symbolic constants for these magic numbers.
22335           // See X86ATTInstPrinter.cpp:printSSECC().
22336           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22337           if (Subtarget->hasAVX512()) {
22338             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22339                                          CMP01,
22340                                          DAG.getConstant(x86cc, DL, MVT::i8));
22341             if (N->getValueType(0) != MVT::i1)
22342               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22343                                  FSetCC);
22344             return FSetCC;
22345           }
22346           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22347                                               CMP00.getValueType(), CMP00, CMP01,
22348                                               DAG.getConstant(x86cc, DL,
22349                                                               MVT::i8));
22350
22351           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22352           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22353
22354           if (is64BitFP && !Subtarget->is64Bit()) {
22355             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22356             // 64-bit integer, since that's not a legal type. Since
22357             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22358             // bits, but can do this little dance to extract the lowest 32 bits
22359             // and work with those going forward.
22360             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22361                                            OnesOrZeroesF);
22362             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22363                                            Vector64);
22364             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22365                                         Vector32, DAG.getIntPtrConstant(0, DL));
22366             IntVT = MVT::i32;
22367           }
22368
22369           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22370                                               OnesOrZeroesF);
22371           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22372                                       DAG.getConstant(1, DL, IntVT));
22373           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22374                                               ANDed);
22375           return OneBitOfTruth;
22376         }
22377       }
22378     }
22379   }
22380   return SDValue();
22381 }
22382
22383 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22384 /// so it can be folded inside ANDNP.
22385 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22386   EVT VT = N->getValueType(0);
22387
22388   // Match direct AllOnes for 128 and 256-bit vectors
22389   if (ISD::isBuildVectorAllOnes(N))
22390     return true;
22391
22392   // Look through a bit convert.
22393   if (N->getOpcode() == ISD::BITCAST)
22394     N = N->getOperand(0).getNode();
22395
22396   // Sometimes the operand may come from a insert_subvector building a 256-bit
22397   // allones vector
22398   if (VT.is256BitVector() &&
22399       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22400     SDValue V1 = N->getOperand(0);
22401     SDValue V2 = N->getOperand(1);
22402
22403     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22404         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22405         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22406         ISD::isBuildVectorAllOnes(V2.getNode()))
22407       return true;
22408   }
22409
22410   return false;
22411 }
22412
22413 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22414 // register. In most cases we actually compare or select YMM-sized registers
22415 // and mixing the two types creates horrible code. This method optimizes
22416 // some of the transition sequences.
22417 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22418                                  TargetLowering::DAGCombinerInfo &DCI,
22419                                  const X86Subtarget *Subtarget) {
22420   EVT VT = N->getValueType(0);
22421   if (!VT.is256BitVector())
22422     return SDValue();
22423
22424   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22425           N->getOpcode() == ISD::ZERO_EXTEND ||
22426           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22427
22428   SDValue Narrow = N->getOperand(0);
22429   EVT NarrowVT = Narrow->getValueType(0);
22430   if (!NarrowVT.is128BitVector())
22431     return SDValue();
22432
22433   if (Narrow->getOpcode() != ISD::XOR &&
22434       Narrow->getOpcode() != ISD::AND &&
22435       Narrow->getOpcode() != ISD::OR)
22436     return SDValue();
22437
22438   SDValue N0  = Narrow->getOperand(0);
22439   SDValue N1  = Narrow->getOperand(1);
22440   SDLoc DL(Narrow);
22441
22442   // The Left side has to be a trunc.
22443   if (N0.getOpcode() != ISD::TRUNCATE)
22444     return SDValue();
22445
22446   // The type of the truncated inputs.
22447   EVT WideVT = N0->getOperand(0)->getValueType(0);
22448   if (WideVT != VT)
22449     return SDValue();
22450
22451   // The right side has to be a 'trunc' or a constant vector.
22452   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22453   ConstantSDNode *RHSConstSplat = nullptr;
22454   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22455     RHSConstSplat = RHSBV->getConstantSplatNode();
22456   if (!RHSTrunc && !RHSConstSplat)
22457     return SDValue();
22458
22459   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22460
22461   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22462     return SDValue();
22463
22464   // Set N0 and N1 to hold the inputs to the new wide operation.
22465   N0 = N0->getOperand(0);
22466   if (RHSConstSplat) {
22467     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22468                      SDValue(RHSConstSplat, 0));
22469     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22470     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22471   } else if (RHSTrunc) {
22472     N1 = N1->getOperand(0);
22473   }
22474
22475   // Generate the wide operation.
22476   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22477   unsigned Opcode = N->getOpcode();
22478   switch (Opcode) {
22479   case ISD::ANY_EXTEND:
22480     return Op;
22481   case ISD::ZERO_EXTEND: {
22482     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22483     APInt Mask = APInt::getAllOnesValue(InBits);
22484     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22485     return DAG.getNode(ISD::AND, DL, VT,
22486                        Op, DAG.getConstant(Mask, DL, VT));
22487   }
22488   case ISD::SIGN_EXTEND:
22489     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22490                        Op, DAG.getValueType(NarrowVT));
22491   default:
22492     llvm_unreachable("Unexpected opcode");
22493   }
22494 }
22495
22496 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22497                                  TargetLowering::DAGCombinerInfo &DCI,
22498                                  const X86Subtarget *Subtarget) {
22499   SDValue N0 = N->getOperand(0);
22500   SDValue N1 = N->getOperand(1);
22501   SDLoc DL(N);
22502
22503   // A vector zext_in_reg may be represented as a shuffle,
22504   // feeding into a bitcast (this represents anyext) feeding into
22505   // an and with a mask.
22506   // We'd like to try to combine that into a shuffle with zero
22507   // plus a bitcast, removing the and.
22508   if (N0.getOpcode() != ISD::BITCAST ||
22509       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22510     return SDValue();
22511
22512   // The other side of the AND should be a splat of 2^C, where C
22513   // is the number of bits in the source type.
22514   if (N1.getOpcode() == ISD::BITCAST)
22515     N1 = N1.getOperand(0);
22516   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22517     return SDValue();
22518   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22519
22520   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22521   EVT SrcType = Shuffle->getValueType(0);
22522
22523   // We expect a single-source shuffle
22524   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22525     return SDValue();
22526
22527   unsigned SrcSize = SrcType.getScalarSizeInBits();
22528
22529   APInt SplatValue, SplatUndef;
22530   unsigned SplatBitSize;
22531   bool HasAnyUndefs;
22532   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22533                                 SplatBitSize, HasAnyUndefs))
22534     return SDValue();
22535
22536   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22537   // Make sure the splat matches the mask we expect
22538   if (SplatBitSize > ResSize ||
22539       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22540     return SDValue();
22541
22542   // Make sure the input and output size make sense
22543   if (SrcSize >= ResSize || ResSize % SrcSize)
22544     return SDValue();
22545
22546   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22547   // The number of u's between each two values depends on the ratio between
22548   // the source and dest type.
22549   unsigned ZextRatio = ResSize / SrcSize;
22550   bool IsZext = true;
22551   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22552     if (i % ZextRatio) {
22553       if (Shuffle->getMaskElt(i) > 0) {
22554         // Expected undef
22555         IsZext = false;
22556         break;
22557       }
22558     } else {
22559       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22560         // Expected element number
22561         IsZext = false;
22562         break;
22563       }
22564     }
22565   }
22566
22567   if (!IsZext)
22568     return SDValue();
22569
22570   // Ok, perform the transformation - replace the shuffle with
22571   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22572   // (instead of undef) where the k elements come from the zero vector.
22573   SmallVector<int, 8> Mask;
22574   unsigned NumElems = SrcType.getVectorNumElements();
22575   for (unsigned i = 0; i < NumElems; ++i)
22576     if (i % ZextRatio)
22577       Mask.push_back(NumElems);
22578     else
22579       Mask.push_back(i / ZextRatio);
22580
22581   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22582     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22583   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22584 }
22585
22586 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22587                                  TargetLowering::DAGCombinerInfo &DCI,
22588                                  const X86Subtarget *Subtarget) {
22589   if (DCI.isBeforeLegalizeOps())
22590     return SDValue();
22591
22592   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22593     return Zext;
22594
22595   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22596     return R;
22597
22598   EVT VT = N->getValueType(0);
22599   SDValue N0 = N->getOperand(0);
22600   SDValue N1 = N->getOperand(1);
22601   SDLoc DL(N);
22602
22603   // Create BEXTR instructions
22604   // BEXTR is ((X >> imm) & (2**size-1))
22605   if (VT == MVT::i32 || VT == MVT::i64) {
22606     // Check for BEXTR.
22607     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22608         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22609       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22610       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22611       if (MaskNode && ShiftNode) {
22612         uint64_t Mask = MaskNode->getZExtValue();
22613         uint64_t Shift = ShiftNode->getZExtValue();
22614         if (isMask_64(Mask)) {
22615           uint64_t MaskSize = countPopulation(Mask);
22616           if (Shift + MaskSize <= VT.getSizeInBits())
22617             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22618                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22619                                                VT));
22620         }
22621       }
22622     } // BEXTR
22623
22624     return SDValue();
22625   }
22626
22627   // Want to form ANDNP nodes:
22628   // 1) In the hopes of then easily combining them with OR and AND nodes
22629   //    to form PBLEND/PSIGN.
22630   // 2) To match ANDN packed intrinsics
22631   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22632     return SDValue();
22633
22634   // Check LHS for vnot
22635   if (N0.getOpcode() == ISD::XOR &&
22636       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22637       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22638     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22639
22640   // Check RHS for vnot
22641   if (N1.getOpcode() == ISD::XOR &&
22642       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22643       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22644     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22645
22646   return SDValue();
22647 }
22648
22649 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22650                                 TargetLowering::DAGCombinerInfo &DCI,
22651                                 const X86Subtarget *Subtarget) {
22652   if (DCI.isBeforeLegalizeOps())
22653     return SDValue();
22654
22655   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22656   if (R.getNode())
22657     return R;
22658
22659   SDValue N0 = N->getOperand(0);
22660   SDValue N1 = N->getOperand(1);
22661   EVT VT = N->getValueType(0);
22662
22663   // look for psign/blend
22664   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22665     if (!Subtarget->hasSSSE3() ||
22666         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22667       return SDValue();
22668
22669     // Canonicalize pandn to RHS
22670     if (N0.getOpcode() == X86ISD::ANDNP)
22671       std::swap(N0, N1);
22672     // or (and (m, y), (pandn m, x))
22673     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22674       SDValue Mask = N1.getOperand(0);
22675       SDValue X    = N1.getOperand(1);
22676       SDValue Y;
22677       if (N0.getOperand(0) == Mask)
22678         Y = N0.getOperand(1);
22679       if (N0.getOperand(1) == Mask)
22680         Y = N0.getOperand(0);
22681
22682       // Check to see if the mask appeared in both the AND and ANDNP and
22683       if (!Y.getNode())
22684         return SDValue();
22685
22686       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22687       // Look through mask bitcast.
22688       if (Mask.getOpcode() == ISD::BITCAST)
22689         Mask = Mask.getOperand(0);
22690       if (X.getOpcode() == ISD::BITCAST)
22691         X = X.getOperand(0);
22692       if (Y.getOpcode() == ISD::BITCAST)
22693         Y = Y.getOperand(0);
22694
22695       EVT MaskVT = Mask.getValueType();
22696
22697       // Validate that the Mask operand is a vector sra node.
22698       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22699       // there is no psrai.b
22700       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22701       unsigned SraAmt = ~0;
22702       if (Mask.getOpcode() == ISD::SRA) {
22703         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22704           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22705             SraAmt = AmtConst->getZExtValue();
22706       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22707         SDValue SraC = Mask.getOperand(1);
22708         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22709       }
22710       if ((SraAmt + 1) != EltBits)
22711         return SDValue();
22712
22713       SDLoc DL(N);
22714
22715       // Now we know we at least have a plendvb with the mask val.  See if
22716       // we can form a psignb/w/d.
22717       // psign = x.type == y.type == mask.type && y = sub(0, x);
22718       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22719           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22720           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22721         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22722                "Unsupported VT for PSIGN");
22723         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22724         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22725       }
22726       // PBLENDVB only available on SSE 4.1
22727       if (!Subtarget->hasSSE41())
22728         return SDValue();
22729
22730       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22731
22732       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22733       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22734       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22735       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22736       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22737     }
22738   }
22739
22740   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22741     return SDValue();
22742
22743   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22744   MachineFunction &MF = DAG.getMachineFunction();
22745   bool OptForSize =
22746       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22747
22748   // SHLD/SHRD instructions have lower register pressure, but on some
22749   // platforms they have higher latency than the equivalent
22750   // series of shifts/or that would otherwise be generated.
22751   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22752   // have higher latencies and we are not optimizing for size.
22753   if (!OptForSize && Subtarget->isSHLDSlow())
22754     return SDValue();
22755
22756   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22757     std::swap(N0, N1);
22758   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22759     return SDValue();
22760   if (!N0.hasOneUse() || !N1.hasOneUse())
22761     return SDValue();
22762
22763   SDValue ShAmt0 = N0.getOperand(1);
22764   if (ShAmt0.getValueType() != MVT::i8)
22765     return SDValue();
22766   SDValue ShAmt1 = N1.getOperand(1);
22767   if (ShAmt1.getValueType() != MVT::i8)
22768     return SDValue();
22769   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22770     ShAmt0 = ShAmt0.getOperand(0);
22771   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22772     ShAmt1 = ShAmt1.getOperand(0);
22773
22774   SDLoc DL(N);
22775   unsigned Opc = X86ISD::SHLD;
22776   SDValue Op0 = N0.getOperand(0);
22777   SDValue Op1 = N1.getOperand(0);
22778   if (ShAmt0.getOpcode() == ISD::SUB) {
22779     Opc = X86ISD::SHRD;
22780     std::swap(Op0, Op1);
22781     std::swap(ShAmt0, ShAmt1);
22782   }
22783
22784   unsigned Bits = VT.getSizeInBits();
22785   if (ShAmt1.getOpcode() == ISD::SUB) {
22786     SDValue Sum = ShAmt1.getOperand(0);
22787     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22788       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22789       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22790         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22791       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22792         return DAG.getNode(Opc, DL, VT,
22793                            Op0, Op1,
22794                            DAG.getNode(ISD::TRUNCATE, DL,
22795                                        MVT::i8, ShAmt0));
22796     }
22797   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22798     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22799     if (ShAmt0C &&
22800         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22801       return DAG.getNode(Opc, DL, VT,
22802                          N0.getOperand(0), N1.getOperand(0),
22803                          DAG.getNode(ISD::TRUNCATE, DL,
22804                                        MVT::i8, ShAmt0));
22805   }
22806
22807   return SDValue();
22808 }
22809
22810 // Generate NEG and CMOV for integer abs.
22811 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22812   EVT VT = N->getValueType(0);
22813
22814   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22815   // 8-bit integer abs to NEG and CMOV.
22816   if (VT.isInteger() && VT.getSizeInBits() == 8)
22817     return SDValue();
22818
22819   SDValue N0 = N->getOperand(0);
22820   SDValue N1 = N->getOperand(1);
22821   SDLoc DL(N);
22822
22823   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22824   // and change it to SUB and CMOV.
22825   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22826       N0.getOpcode() == ISD::ADD &&
22827       N0.getOperand(1) == N1 &&
22828       N1.getOpcode() == ISD::SRA &&
22829       N1.getOperand(0) == N0.getOperand(0))
22830     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22831       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22832         // Generate SUB & CMOV.
22833         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22834                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
22835
22836         SDValue Ops[] = { N0.getOperand(0), Neg,
22837                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22838                           SDValue(Neg.getNode(), 1) };
22839         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22840       }
22841   return SDValue();
22842 }
22843
22844 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22845 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22846                                  TargetLowering::DAGCombinerInfo &DCI,
22847                                  const X86Subtarget *Subtarget) {
22848   if (DCI.isBeforeLegalizeOps())
22849     return SDValue();
22850
22851   if (Subtarget->hasCMov()) {
22852     SDValue RV = performIntegerAbsCombine(N, DAG);
22853     if (RV.getNode())
22854       return RV;
22855   }
22856
22857   return SDValue();
22858 }
22859
22860 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22861 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22862                                   TargetLowering::DAGCombinerInfo &DCI,
22863                                   const X86Subtarget *Subtarget) {
22864   LoadSDNode *Ld = cast<LoadSDNode>(N);
22865   EVT RegVT = Ld->getValueType(0);
22866   EVT MemVT = Ld->getMemoryVT();
22867   SDLoc dl(Ld);
22868   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22869
22870   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22871   // into two 16-byte operations.
22872   ISD::LoadExtType Ext = Ld->getExtensionType();
22873   unsigned Alignment = Ld->getAlignment();
22874   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22875   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22876       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22877     unsigned NumElems = RegVT.getVectorNumElements();
22878     if (NumElems < 2)
22879       return SDValue();
22880
22881     SDValue Ptr = Ld->getBasePtr();
22882     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
22883
22884     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22885                                   NumElems/2);
22886     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22887                                 Ld->getPointerInfo(), Ld->isVolatile(),
22888                                 Ld->isNonTemporal(), Ld->isInvariant(),
22889                                 Alignment);
22890     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22891     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22892                                 Ld->getPointerInfo(), Ld->isVolatile(),
22893                                 Ld->isNonTemporal(), Ld->isInvariant(),
22894                                 std::min(16U, Alignment));
22895     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22896                              Load1.getValue(1),
22897                              Load2.getValue(1));
22898
22899     SDValue NewVec = DAG.getUNDEF(RegVT);
22900     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22901     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22902     return DCI.CombineTo(N, NewVec, TF, true);
22903   }
22904
22905   return SDValue();
22906 }
22907
22908 /// PerformMLOADCombine - Resolve extending loads
22909 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22910                                    TargetLowering::DAGCombinerInfo &DCI,
22911                                    const X86Subtarget *Subtarget) {
22912   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22913   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22914     return SDValue();
22915
22916   EVT VT = Mld->getValueType(0);
22917   unsigned NumElems = VT.getVectorNumElements();
22918   EVT LdVT = Mld->getMemoryVT();
22919   SDLoc dl(Mld);
22920
22921   assert(LdVT != VT && "Cannot extend to the same type");
22922   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22923   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22924   // From, To sizes and ElemCount must be pow of two
22925   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22926     "Unexpected size for extending masked load");
22927
22928   unsigned SizeRatio  = ToSz / FromSz;
22929   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22930
22931   // Create a type on which we perform the shuffle
22932   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22933           LdVT.getScalarType(), NumElems*SizeRatio);
22934   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22935
22936   // Convert Src0 value
22937   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22938   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22939     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22940     for (unsigned i = 0; i != NumElems; ++i)
22941       ShuffleVec[i] = i * SizeRatio;
22942
22943     // Can't shuffle using an illegal type.
22944     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22945             && "WideVecVT should be legal");
22946     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22947                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22948   }
22949   // Prepare the new mask
22950   SDValue NewMask;
22951   SDValue Mask = Mld->getMask();
22952   if (Mask.getValueType() == VT) {
22953     // Mask and original value have the same type
22954     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22955     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22956     for (unsigned i = 0; i != NumElems; ++i)
22957       ShuffleVec[i] = i * SizeRatio;
22958     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22959       ShuffleVec[i] = NumElems*SizeRatio;
22960     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22961                                    DAG.getConstant(0, dl, WideVecVT),
22962                                    &ShuffleVec[0]);
22963   }
22964   else {
22965     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22966     unsigned WidenNumElts = NumElems*SizeRatio;
22967     unsigned MaskNumElts = VT.getVectorNumElements();
22968     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22969                                      WidenNumElts);
22970
22971     unsigned NumConcat = WidenNumElts / MaskNumElts;
22972     SmallVector<SDValue, 16> Ops(NumConcat);
22973     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
22974     Ops[0] = Mask;
22975     for (unsigned i = 1; i != NumConcat; ++i)
22976       Ops[i] = ZeroVal;
22977
22978     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22979   }
22980
22981   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22982                                      Mld->getBasePtr(), NewMask, WideSrc0,
22983                                      Mld->getMemoryVT(), Mld->getMemOperand(),
22984                                      ISD::NON_EXTLOAD);
22985   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22986   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22987
22988 }
22989 /// PerformMSTORECombine - Resolve truncating stores
22990 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22991                                     const X86Subtarget *Subtarget) {
22992   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22993   if (!Mst->isTruncatingStore())
22994     return SDValue();
22995
22996   EVT VT = Mst->getValue().getValueType();
22997   unsigned NumElems = VT.getVectorNumElements();
22998   EVT StVT = Mst->getMemoryVT();
22999   SDLoc dl(Mst);
23000
23001   assert(StVT != VT && "Cannot truncate to the same type");
23002   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23003   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23004
23005   // From, To sizes and ElemCount must be pow of two
23006   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23007     "Unexpected size for truncating masked store");
23008   // We are going to use the original vector elt for storing.
23009   // Accumulated smaller vector elements must be a multiple of the store size.
23010   assert (((NumElems * FromSz) % ToSz) == 0 &&
23011           "Unexpected ratio for truncating masked store");
23012
23013   unsigned SizeRatio  = FromSz / ToSz;
23014   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23015
23016   // Create a type on which we perform the shuffle
23017   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23018           StVT.getScalarType(), NumElems*SizeRatio);
23019
23020   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23021
23022   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23023   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23024   for (unsigned i = 0; i != NumElems; ++i)
23025     ShuffleVec[i] = i * SizeRatio;
23026
23027   // Can't shuffle using an illegal type.
23028   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23029           && "WideVecVT should be legal");
23030
23031   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23032                                         DAG.getUNDEF(WideVecVT),
23033                                         &ShuffleVec[0]);
23034
23035   SDValue NewMask;
23036   SDValue Mask = Mst->getMask();
23037   if (Mask.getValueType() == VT) {
23038     // Mask and original value have the same type
23039     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23040     for (unsigned i = 0; i != NumElems; ++i)
23041       ShuffleVec[i] = i * SizeRatio;
23042     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23043       ShuffleVec[i] = NumElems*SizeRatio;
23044     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23045                                    DAG.getConstant(0, dl, WideVecVT),
23046                                    &ShuffleVec[0]);
23047   }
23048   else {
23049     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23050     unsigned WidenNumElts = NumElems*SizeRatio;
23051     unsigned MaskNumElts = VT.getVectorNumElements();
23052     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23053                                      WidenNumElts);
23054
23055     unsigned NumConcat = WidenNumElts / MaskNumElts;
23056     SmallVector<SDValue, 16> Ops(NumConcat);
23057     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23058     Ops[0] = Mask;
23059     for (unsigned i = 1; i != NumConcat; ++i)
23060       Ops[i] = ZeroVal;
23061
23062     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23063   }
23064
23065   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23066                             NewMask, StVT, Mst->getMemOperand(), false);
23067 }
23068 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23069 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23070                                    const X86Subtarget *Subtarget) {
23071   StoreSDNode *St = cast<StoreSDNode>(N);
23072   EVT VT = St->getValue().getValueType();
23073   EVT StVT = St->getMemoryVT();
23074   SDLoc dl(St);
23075   SDValue StoredVal = St->getOperand(1);
23076   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23077
23078   // If we are saving a concatenation of two XMM registers and 32-byte stores
23079   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23080   unsigned Alignment = St->getAlignment();
23081   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23082   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23083       StVT == VT && !IsAligned) {
23084     unsigned NumElems = VT.getVectorNumElements();
23085     if (NumElems < 2)
23086       return SDValue();
23087
23088     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23089     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23090
23091     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23092     SDValue Ptr0 = St->getBasePtr();
23093     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23094
23095     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23096                                 St->getPointerInfo(), St->isVolatile(),
23097                                 St->isNonTemporal(), Alignment);
23098     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23099                                 St->getPointerInfo(), St->isVolatile(),
23100                                 St->isNonTemporal(),
23101                                 std::min(16U, Alignment));
23102     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23103   }
23104
23105   // Optimize trunc store (of multiple scalars) to shuffle and store.
23106   // First, pack all of the elements in one place. Next, store to memory
23107   // in fewer chunks.
23108   if (St->isTruncatingStore() && VT.isVector()) {
23109     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23110     unsigned NumElems = VT.getVectorNumElements();
23111     assert(StVT != VT && "Cannot truncate to the same type");
23112     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23113     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23114
23115     // From, To sizes and ElemCount must be pow of two
23116     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23117     // We are going to use the original vector elt for storing.
23118     // Accumulated smaller vector elements must be a multiple of the store size.
23119     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23120
23121     unsigned SizeRatio  = FromSz / ToSz;
23122
23123     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23124
23125     // Create a type on which we perform the shuffle
23126     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23127             StVT.getScalarType(), NumElems*SizeRatio);
23128
23129     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23130
23131     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23132     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23133     for (unsigned i = 0; i != NumElems; ++i)
23134       ShuffleVec[i] = i * SizeRatio;
23135
23136     // Can't shuffle using an illegal type.
23137     if (!TLI.isTypeLegal(WideVecVT))
23138       return SDValue();
23139
23140     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23141                                          DAG.getUNDEF(WideVecVT),
23142                                          &ShuffleVec[0]);
23143     // At this point all of the data is stored at the bottom of the
23144     // register. We now need to save it to mem.
23145
23146     // Find the largest store unit
23147     MVT StoreType = MVT::i8;
23148     for (MVT Tp : MVT::integer_valuetypes()) {
23149       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23150         StoreType = Tp;
23151     }
23152
23153     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23154     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23155         (64 <= NumElems * ToSz))
23156       StoreType = MVT::f64;
23157
23158     // Bitcast the original vector into a vector of store-size units
23159     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23160             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23161     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23162     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23163     SmallVector<SDValue, 8> Chains;
23164     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23165                                         TLI.getPointerTy());
23166     SDValue Ptr = St->getBasePtr();
23167
23168     // Perform one or more big stores into memory.
23169     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23170       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23171                                    StoreType, ShuffWide,
23172                                    DAG.getIntPtrConstant(i, dl));
23173       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23174                                 St->getPointerInfo(), St->isVolatile(),
23175                                 St->isNonTemporal(), St->getAlignment());
23176       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23177       Chains.push_back(Ch);
23178     }
23179
23180     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23181   }
23182
23183   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23184   // the FP state in cases where an emms may be missing.
23185   // A preferable solution to the general problem is to figure out the right
23186   // places to insert EMMS.  This qualifies as a quick hack.
23187
23188   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23189   if (VT.getSizeInBits() != 64)
23190     return SDValue();
23191
23192   const Function *F = DAG.getMachineFunction().getFunction();
23193   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23194   bool F64IsLegal =
23195       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23196   if ((VT.isVector() ||
23197        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23198       isa<LoadSDNode>(St->getValue()) &&
23199       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23200       St->getChain().hasOneUse() && !St->isVolatile()) {
23201     SDNode* LdVal = St->getValue().getNode();
23202     LoadSDNode *Ld = nullptr;
23203     int TokenFactorIndex = -1;
23204     SmallVector<SDValue, 8> Ops;
23205     SDNode* ChainVal = St->getChain().getNode();
23206     // Must be a store of a load.  We currently handle two cases:  the load
23207     // is a direct child, and it's under an intervening TokenFactor.  It is
23208     // possible to dig deeper under nested TokenFactors.
23209     if (ChainVal == LdVal)
23210       Ld = cast<LoadSDNode>(St->getChain());
23211     else if (St->getValue().hasOneUse() &&
23212              ChainVal->getOpcode() == ISD::TokenFactor) {
23213       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23214         if (ChainVal->getOperand(i).getNode() == LdVal) {
23215           TokenFactorIndex = i;
23216           Ld = cast<LoadSDNode>(St->getValue());
23217         } else
23218           Ops.push_back(ChainVal->getOperand(i));
23219       }
23220     }
23221
23222     if (!Ld || !ISD::isNormalLoad(Ld))
23223       return SDValue();
23224
23225     // If this is not the MMX case, i.e. we are just turning i64 load/store
23226     // into f64 load/store, avoid the transformation if there are multiple
23227     // uses of the loaded value.
23228     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23229       return SDValue();
23230
23231     SDLoc LdDL(Ld);
23232     SDLoc StDL(N);
23233     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23234     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23235     // pair instead.
23236     if (Subtarget->is64Bit() || F64IsLegal) {
23237       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23238       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23239                                   Ld->getPointerInfo(), Ld->isVolatile(),
23240                                   Ld->isNonTemporal(), Ld->isInvariant(),
23241                                   Ld->getAlignment());
23242       SDValue NewChain = NewLd.getValue(1);
23243       if (TokenFactorIndex != -1) {
23244         Ops.push_back(NewChain);
23245         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23246       }
23247       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23248                           St->getPointerInfo(),
23249                           St->isVolatile(), St->isNonTemporal(),
23250                           St->getAlignment());
23251     }
23252
23253     // Otherwise, lower to two pairs of 32-bit loads / stores.
23254     SDValue LoAddr = Ld->getBasePtr();
23255     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23256                                  DAG.getConstant(4, LdDL, MVT::i32));
23257
23258     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23259                                Ld->getPointerInfo(),
23260                                Ld->isVolatile(), Ld->isNonTemporal(),
23261                                Ld->isInvariant(), Ld->getAlignment());
23262     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23263                                Ld->getPointerInfo().getWithOffset(4),
23264                                Ld->isVolatile(), Ld->isNonTemporal(),
23265                                Ld->isInvariant(),
23266                                MinAlign(Ld->getAlignment(), 4));
23267
23268     SDValue NewChain = LoLd.getValue(1);
23269     if (TokenFactorIndex != -1) {
23270       Ops.push_back(LoLd);
23271       Ops.push_back(HiLd);
23272       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23273     }
23274
23275     LoAddr = St->getBasePtr();
23276     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23277                          DAG.getConstant(4, StDL, MVT::i32));
23278
23279     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23280                                 St->getPointerInfo(),
23281                                 St->isVolatile(), St->isNonTemporal(),
23282                                 St->getAlignment());
23283     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23284                                 St->getPointerInfo().getWithOffset(4),
23285                                 St->isVolatile(),
23286                                 St->isNonTemporal(),
23287                                 MinAlign(St->getAlignment(), 4));
23288     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23289   }
23290
23291   // This is similar to the above case, but here we handle a scalar 64-bit
23292   // integer store that is extracted from a vector on a 32-bit target.
23293   // If we have SSE2, then we can treat it like a floating-point double
23294   // to get past legalization. The execution dependencies fixup pass will
23295   // choose the optimal machine instruction for the store if this really is
23296   // an integer or v2f32 rather than an f64.
23297   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23298       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23299     SDValue OldExtract = St->getOperand(1);
23300     SDValue ExtOp0 = OldExtract.getOperand(0);
23301     unsigned VecSize = ExtOp0.getValueSizeInBits();
23302     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23303     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23304     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23305                                      BitCast, OldExtract.getOperand(1));
23306     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23307                         St->getPointerInfo(), St->isVolatile(),
23308                         St->isNonTemporal(), St->getAlignment());
23309   }
23310
23311   return SDValue();
23312 }
23313
23314 /// Return 'true' if this vector operation is "horizontal"
23315 /// and return the operands for the horizontal operation in LHS and RHS.  A
23316 /// horizontal operation performs the binary operation on successive elements
23317 /// of its first operand, then on successive elements of its second operand,
23318 /// returning the resulting values in a vector.  For example, if
23319 ///   A = < float a0, float a1, float a2, float a3 >
23320 /// and
23321 ///   B = < float b0, float b1, float b2, float b3 >
23322 /// then the result of doing a horizontal operation on A and B is
23323 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23324 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23325 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23326 /// set to A, RHS to B, and the routine returns 'true'.
23327 /// Note that the binary operation should have the property that if one of the
23328 /// operands is UNDEF then the result is UNDEF.
23329 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23330   // Look for the following pattern: if
23331   //   A = < float a0, float a1, float a2, float a3 >
23332   //   B = < float b0, float b1, float b2, float b3 >
23333   // and
23334   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23335   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23336   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23337   // which is A horizontal-op B.
23338
23339   // At least one of the operands should be a vector shuffle.
23340   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23341       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23342     return false;
23343
23344   MVT VT = LHS.getSimpleValueType();
23345
23346   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23347          "Unsupported vector type for horizontal add/sub");
23348
23349   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23350   // operate independently on 128-bit lanes.
23351   unsigned NumElts = VT.getVectorNumElements();
23352   unsigned NumLanes = VT.getSizeInBits()/128;
23353   unsigned NumLaneElts = NumElts / NumLanes;
23354   assert((NumLaneElts % 2 == 0) &&
23355          "Vector type should have an even number of elements in each lane");
23356   unsigned HalfLaneElts = NumLaneElts/2;
23357
23358   // View LHS in the form
23359   //   LHS = VECTOR_SHUFFLE A, B, LMask
23360   // If LHS is not a shuffle then pretend it is the shuffle
23361   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23362   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23363   // type VT.
23364   SDValue A, B;
23365   SmallVector<int, 16> LMask(NumElts);
23366   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23367     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23368       A = LHS.getOperand(0);
23369     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23370       B = LHS.getOperand(1);
23371     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23372     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23373   } else {
23374     if (LHS.getOpcode() != ISD::UNDEF)
23375       A = LHS;
23376     for (unsigned i = 0; i != NumElts; ++i)
23377       LMask[i] = i;
23378   }
23379
23380   // Likewise, view RHS in the form
23381   //   RHS = VECTOR_SHUFFLE C, D, RMask
23382   SDValue C, D;
23383   SmallVector<int, 16> RMask(NumElts);
23384   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23385     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23386       C = RHS.getOperand(0);
23387     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23388       D = RHS.getOperand(1);
23389     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23390     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23391   } else {
23392     if (RHS.getOpcode() != ISD::UNDEF)
23393       C = RHS;
23394     for (unsigned i = 0; i != NumElts; ++i)
23395       RMask[i] = i;
23396   }
23397
23398   // Check that the shuffles are both shuffling the same vectors.
23399   if (!(A == C && B == D) && !(A == D && B == C))
23400     return false;
23401
23402   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23403   if (!A.getNode() && !B.getNode())
23404     return false;
23405
23406   // If A and B occur in reverse order in RHS, then "swap" them (which means
23407   // rewriting the mask).
23408   if (A != C)
23409     ShuffleVectorSDNode::commuteMask(RMask);
23410
23411   // At this point LHS and RHS are equivalent to
23412   //   LHS = VECTOR_SHUFFLE A, B, LMask
23413   //   RHS = VECTOR_SHUFFLE A, B, RMask
23414   // Check that the masks correspond to performing a horizontal operation.
23415   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23416     for (unsigned i = 0; i != NumLaneElts; ++i) {
23417       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23418
23419       // Ignore any UNDEF components.
23420       if (LIdx < 0 || RIdx < 0 ||
23421           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23422           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23423         continue;
23424
23425       // Check that successive elements are being operated on.  If not, this is
23426       // not a horizontal operation.
23427       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23428       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23429       if (!(LIdx == Index && RIdx == Index + 1) &&
23430           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23431         return false;
23432     }
23433   }
23434
23435   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23436   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23437   return true;
23438 }
23439
23440 /// Do target-specific dag combines on floating point adds.
23441 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23442                                   const X86Subtarget *Subtarget) {
23443   EVT VT = N->getValueType(0);
23444   SDValue LHS = N->getOperand(0);
23445   SDValue RHS = N->getOperand(1);
23446
23447   // Try to synthesize horizontal adds from adds of shuffles.
23448   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23449        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23450       isHorizontalBinOp(LHS, RHS, true))
23451     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23452   return SDValue();
23453 }
23454
23455 /// Do target-specific dag combines on floating point subs.
23456 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23457                                   const X86Subtarget *Subtarget) {
23458   EVT VT = N->getValueType(0);
23459   SDValue LHS = N->getOperand(0);
23460   SDValue RHS = N->getOperand(1);
23461
23462   // Try to synthesize horizontal subs from subs of shuffles.
23463   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23464        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23465       isHorizontalBinOp(LHS, RHS, false))
23466     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23467   return SDValue();
23468 }
23469
23470 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23471 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23472   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23473
23474   // F[X]OR(0.0, x) -> x
23475   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23476     if (C->getValueAPF().isPosZero())
23477       return N->getOperand(1);
23478
23479   // F[X]OR(x, 0.0) -> x
23480   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23481     if (C->getValueAPF().isPosZero())
23482       return N->getOperand(0);
23483   return SDValue();
23484 }
23485
23486 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23487 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23488   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23489
23490   // Only perform optimizations if UnsafeMath is used.
23491   if (!DAG.getTarget().Options.UnsafeFPMath)
23492     return SDValue();
23493
23494   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23495   // into FMINC and FMAXC, which are Commutative operations.
23496   unsigned NewOp = 0;
23497   switch (N->getOpcode()) {
23498     default: llvm_unreachable("unknown opcode");
23499     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23500     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23501   }
23502
23503   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23504                      N->getOperand(0), N->getOperand(1));
23505 }
23506
23507 /// Do target-specific dag combines on X86ISD::FAND nodes.
23508 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23509   // FAND(0.0, x) -> 0.0
23510   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23511     if (C->getValueAPF().isPosZero())
23512       return N->getOperand(0);
23513
23514   // FAND(x, 0.0) -> 0.0
23515   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23516     if (C->getValueAPF().isPosZero())
23517       return N->getOperand(1);
23518
23519   return SDValue();
23520 }
23521
23522 /// Do target-specific dag combines on X86ISD::FANDN nodes
23523 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23524   // FANDN(0.0, x) -> x
23525   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23526     if (C->getValueAPF().isPosZero())
23527       return N->getOperand(1);
23528
23529   // FANDN(x, 0.0) -> 0.0
23530   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23531     if (C->getValueAPF().isPosZero())
23532       return N->getOperand(1);
23533
23534   return SDValue();
23535 }
23536
23537 static SDValue PerformBTCombine(SDNode *N,
23538                                 SelectionDAG &DAG,
23539                                 TargetLowering::DAGCombinerInfo &DCI) {
23540   // BT ignores high bits in the bit index operand.
23541   SDValue Op1 = N->getOperand(1);
23542   if (Op1.hasOneUse()) {
23543     unsigned BitWidth = Op1.getValueSizeInBits();
23544     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23545     APInt KnownZero, KnownOne;
23546     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23547                                           !DCI.isBeforeLegalizeOps());
23548     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23549     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23550         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23551       DCI.CommitTargetLoweringOpt(TLO);
23552   }
23553   return SDValue();
23554 }
23555
23556 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23557   SDValue Op = N->getOperand(0);
23558   if (Op.getOpcode() == ISD::BITCAST)
23559     Op = Op.getOperand(0);
23560   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23561   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23562       VT.getVectorElementType().getSizeInBits() ==
23563       OpVT.getVectorElementType().getSizeInBits()) {
23564     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23565   }
23566   return SDValue();
23567 }
23568
23569 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23570                                                const X86Subtarget *Subtarget) {
23571   EVT VT = N->getValueType(0);
23572   if (!VT.isVector())
23573     return SDValue();
23574
23575   SDValue N0 = N->getOperand(0);
23576   SDValue N1 = N->getOperand(1);
23577   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23578   SDLoc dl(N);
23579
23580   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23581   // both SSE and AVX2 since there is no sign-extended shift right
23582   // operation on a vector with 64-bit elements.
23583   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23584   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23585   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23586       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23587     SDValue N00 = N0.getOperand(0);
23588
23589     // EXTLOAD has a better solution on AVX2,
23590     // it may be replaced with X86ISD::VSEXT node.
23591     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23592       if (!ISD::isNormalLoad(N00.getNode()))
23593         return SDValue();
23594
23595     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23596         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23597                                   N00, N1);
23598       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23599     }
23600   }
23601   return SDValue();
23602 }
23603
23604 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23605                                   TargetLowering::DAGCombinerInfo &DCI,
23606                                   const X86Subtarget *Subtarget) {
23607   SDValue N0 = N->getOperand(0);
23608   EVT VT = N->getValueType(0);
23609
23610   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23611   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23612   // This exposes the sext to the sdivrem lowering, so that it directly extends
23613   // from AH (which we otherwise need to do contortions to access).
23614   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23615       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23616     SDLoc dl(N);
23617     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23618     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23619                             N0.getOperand(0), N0.getOperand(1));
23620     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23621     return R.getValue(1);
23622   }
23623
23624   if (!DCI.isBeforeLegalizeOps())
23625     return SDValue();
23626
23627   if (!Subtarget->hasFp256())
23628     return SDValue();
23629
23630   if (VT.isVector() && VT.getSizeInBits() == 256) {
23631     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23632     if (R.getNode())
23633       return R;
23634   }
23635
23636   return SDValue();
23637 }
23638
23639 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23640                                  const X86Subtarget* Subtarget) {
23641   SDLoc dl(N);
23642   EVT VT = N->getValueType(0);
23643
23644   // Let legalize expand this if it isn't a legal type yet.
23645   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23646     return SDValue();
23647
23648   EVT ScalarVT = VT.getScalarType();
23649   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23650       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23651     return SDValue();
23652
23653   SDValue A = N->getOperand(0);
23654   SDValue B = N->getOperand(1);
23655   SDValue C = N->getOperand(2);
23656
23657   bool NegA = (A.getOpcode() == ISD::FNEG);
23658   bool NegB = (B.getOpcode() == ISD::FNEG);
23659   bool NegC = (C.getOpcode() == ISD::FNEG);
23660
23661   // Negative multiplication when NegA xor NegB
23662   bool NegMul = (NegA != NegB);
23663   if (NegA)
23664     A = A.getOperand(0);
23665   if (NegB)
23666     B = B.getOperand(0);
23667   if (NegC)
23668     C = C.getOperand(0);
23669
23670   unsigned Opcode;
23671   if (!NegMul)
23672     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23673   else
23674     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23675
23676   return DAG.getNode(Opcode, dl, VT, A, B, C);
23677 }
23678
23679 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23680                                   TargetLowering::DAGCombinerInfo &DCI,
23681                                   const X86Subtarget *Subtarget) {
23682   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23683   //           (and (i32 x86isd::setcc_carry), 1)
23684   // This eliminates the zext. This transformation is necessary because
23685   // ISD::SETCC is always legalized to i8.
23686   SDLoc dl(N);
23687   SDValue N0 = N->getOperand(0);
23688   EVT VT = N->getValueType(0);
23689
23690   if (N0.getOpcode() == ISD::AND &&
23691       N0.hasOneUse() &&
23692       N0.getOperand(0).hasOneUse()) {
23693     SDValue N00 = N0.getOperand(0);
23694     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23695       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23696       if (!C || C->getZExtValue() != 1)
23697         return SDValue();
23698       return DAG.getNode(ISD::AND, dl, VT,
23699                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23700                                      N00.getOperand(0), N00.getOperand(1)),
23701                          DAG.getConstant(1, dl, VT));
23702     }
23703   }
23704
23705   if (N0.getOpcode() == ISD::TRUNCATE &&
23706       N0.hasOneUse() &&
23707       N0.getOperand(0).hasOneUse()) {
23708     SDValue N00 = N0.getOperand(0);
23709     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23710       return DAG.getNode(ISD::AND, dl, VT,
23711                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23712                                      N00.getOperand(0), N00.getOperand(1)),
23713                          DAG.getConstant(1, dl, VT));
23714     }
23715   }
23716   if (VT.is256BitVector()) {
23717     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23718     if (R.getNode())
23719       return R;
23720   }
23721
23722   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23723   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23724   // This exposes the zext to the udivrem lowering, so that it directly extends
23725   // from AH (which we otherwise need to do contortions to access).
23726   if (N0.getOpcode() == ISD::UDIVREM &&
23727       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23728       (VT == MVT::i32 || VT == MVT::i64)) {
23729     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23730     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23731                             N0.getOperand(0), N0.getOperand(1));
23732     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23733     return R.getValue(1);
23734   }
23735
23736   return SDValue();
23737 }
23738
23739 // Optimize x == -y --> x+y == 0
23740 //          x != -y --> x+y != 0
23741 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23742                                       const X86Subtarget* Subtarget) {
23743   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23744   SDValue LHS = N->getOperand(0);
23745   SDValue RHS = N->getOperand(1);
23746   EVT VT = N->getValueType(0);
23747   SDLoc DL(N);
23748
23749   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23750     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23751       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23752         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23753                                    LHS.getOperand(1));
23754         return DAG.getSetCC(DL, N->getValueType(0), addV,
23755                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23756       }
23757   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23758     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23759       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23760         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23761                                    RHS.getOperand(1));
23762         return DAG.getSetCC(DL, N->getValueType(0), addV,
23763                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23764       }
23765
23766   if (VT.getScalarType() == MVT::i1 &&
23767       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23768     bool IsSEXT0 =
23769         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23770         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23771     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23772
23773     if (!IsSEXT0 || !IsVZero1) {
23774       // Swap the operands and update the condition code.
23775       std::swap(LHS, RHS);
23776       CC = ISD::getSetCCSwappedOperands(CC);
23777
23778       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23779                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23780       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23781     }
23782
23783     if (IsSEXT0 && IsVZero1) {
23784       assert(VT == LHS.getOperand(0).getValueType() &&
23785              "Uexpected operand type");
23786       if (CC == ISD::SETGT)
23787         return DAG.getConstant(0, DL, VT);
23788       if (CC == ISD::SETLE)
23789         return DAG.getConstant(1, DL, VT);
23790       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23791         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23792
23793       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23794              "Unexpected condition code!");
23795       return LHS.getOperand(0);
23796     }
23797   }
23798
23799   return SDValue();
23800 }
23801
23802 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23803                                          SelectionDAG &DAG) {
23804   SDLoc dl(Load);
23805   MVT VT = Load->getSimpleValueType(0);
23806   MVT EVT = VT.getVectorElementType();
23807   SDValue Addr = Load->getOperand(1);
23808   SDValue NewAddr = DAG.getNode(
23809       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23810       DAG.getConstant(Index * EVT.getStoreSize(), dl,
23811                       Addr.getSimpleValueType()));
23812
23813   SDValue NewLoad =
23814       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23815                   DAG.getMachineFunction().getMachineMemOperand(
23816                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23817   return NewLoad;
23818 }
23819
23820 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23821                                       const X86Subtarget *Subtarget) {
23822   SDLoc dl(N);
23823   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23824   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23825          "X86insertps is only defined for v4x32");
23826
23827   SDValue Ld = N->getOperand(1);
23828   if (MayFoldLoad(Ld)) {
23829     // Extract the countS bits from the immediate so we can get the proper
23830     // address when narrowing the vector load to a specific element.
23831     // When the second source op is a memory address, insertps doesn't use
23832     // countS and just gets an f32 from that address.
23833     unsigned DestIndex =
23834         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23835
23836     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23837
23838     // Create this as a scalar to vector to match the instruction pattern.
23839     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23840     // countS bits are ignored when loading from memory on insertps, which
23841     // means we don't need to explicitly set them to 0.
23842     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23843                        LoadScalarToVector, N->getOperand(2));
23844   }
23845   return SDValue();
23846 }
23847
23848 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23849   SDValue V0 = N->getOperand(0);
23850   SDValue V1 = N->getOperand(1);
23851   SDLoc DL(N);
23852   EVT VT = N->getValueType(0);
23853
23854   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23855   // operands and changing the mask to 1. This saves us a bunch of
23856   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23857   // x86InstrInfo knows how to commute this back after instruction selection
23858   // if it would help register allocation.
23859
23860   // TODO: If optimizing for size or a processor that doesn't suffer from
23861   // partial register update stalls, this should be transformed into a MOVSD
23862   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23863
23864   if (VT == MVT::v2f64)
23865     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23866       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23867         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23868         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23869       }
23870
23871   return SDValue();
23872 }
23873
23874 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23875 // as "sbb reg,reg", since it can be extended without zext and produces
23876 // an all-ones bit which is more useful than 0/1 in some cases.
23877 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23878                                MVT VT) {
23879   if (VT == MVT::i8)
23880     return DAG.getNode(ISD::AND, DL, VT,
23881                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23882                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
23883                                    EFLAGS),
23884                        DAG.getConstant(1, DL, VT));
23885   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23886   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23887                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23888                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
23889                                  EFLAGS));
23890 }
23891
23892 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23893 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23894                                    TargetLowering::DAGCombinerInfo &DCI,
23895                                    const X86Subtarget *Subtarget) {
23896   SDLoc DL(N);
23897   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23898   SDValue EFLAGS = N->getOperand(1);
23899
23900   if (CC == X86::COND_A) {
23901     // Try to convert COND_A into COND_B in an attempt to facilitate
23902     // materializing "setb reg".
23903     //
23904     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23905     // cannot take an immediate as its first operand.
23906     //
23907     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23908         EFLAGS.getValueType().isInteger() &&
23909         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23910       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23911                                    EFLAGS.getNode()->getVTList(),
23912                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23913       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23914       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23915     }
23916   }
23917
23918   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23919   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23920   // cases.
23921   if (CC == X86::COND_B)
23922     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23923
23924   SDValue Flags;
23925
23926   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23927   if (Flags.getNode()) {
23928     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23929     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23930   }
23931
23932   return SDValue();
23933 }
23934
23935 // Optimize branch condition evaluation.
23936 //
23937 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23938                                     TargetLowering::DAGCombinerInfo &DCI,
23939                                     const X86Subtarget *Subtarget) {
23940   SDLoc DL(N);
23941   SDValue Chain = N->getOperand(0);
23942   SDValue Dest = N->getOperand(1);
23943   SDValue EFLAGS = N->getOperand(3);
23944   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23945
23946   SDValue Flags;
23947
23948   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23949   if (Flags.getNode()) {
23950     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23951     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23952                        Flags);
23953   }
23954
23955   return SDValue();
23956 }
23957
23958 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23959                                                          SelectionDAG &DAG) {
23960   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23961   // optimize away operation when it's from a constant.
23962   //
23963   // The general transformation is:
23964   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23965   //       AND(VECTOR_CMP(x,y), constant2)
23966   //    constant2 = UNARYOP(constant)
23967
23968   // Early exit if this isn't a vector operation, the operand of the
23969   // unary operation isn't a bitwise AND, or if the sizes of the operations
23970   // aren't the same.
23971   EVT VT = N->getValueType(0);
23972   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23973       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23974       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23975     return SDValue();
23976
23977   // Now check that the other operand of the AND is a constant. We could
23978   // make the transformation for non-constant splats as well, but it's unclear
23979   // that would be a benefit as it would not eliminate any operations, just
23980   // perform one more step in scalar code before moving to the vector unit.
23981   if (BuildVectorSDNode *BV =
23982           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23983     // Bail out if the vector isn't a constant.
23984     if (!BV->isConstant())
23985       return SDValue();
23986
23987     // Everything checks out. Build up the new and improved node.
23988     SDLoc DL(N);
23989     EVT IntVT = BV->getValueType(0);
23990     // Create a new constant of the appropriate type for the transformed
23991     // DAG.
23992     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23993     // The AND node needs bitcasts to/from an integer vector type around it.
23994     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23995     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23996                                  N->getOperand(0)->getOperand(0), MaskConst);
23997     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23998     return Res;
23999   }
24000
24001   return SDValue();
24002 }
24003
24004 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24005                                         const X86Subtarget *Subtarget) {
24006   // First try to optimize away the conversion entirely when it's
24007   // conditionally from a constant. Vectors only.
24008   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24009   if (Res != SDValue())
24010     return Res;
24011
24012   // Now move on to more general possibilities.
24013   SDValue Op0 = N->getOperand(0);
24014   EVT InVT = Op0->getValueType(0);
24015
24016   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24017   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24018     SDLoc dl(N);
24019     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24020     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24021     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24022   }
24023
24024   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24025   // a 32-bit target where SSE doesn't support i64->FP operations.
24026   if (Op0.getOpcode() == ISD::LOAD) {
24027     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24028     EVT VT = Ld->getValueType(0);
24029
24030     // This transformation is not supported if the result type is f16
24031     if (N->getValueType(0) == MVT::f16)
24032       return SDValue();
24033
24034     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24035         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24036         !Subtarget->is64Bit() && VT == MVT::i64) {
24037       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24038           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24039       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24040       return FILDChain;
24041     }
24042   }
24043   return SDValue();
24044 }
24045
24046 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24047 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24048                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24049   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24050   // the result is either zero or one (depending on the input carry bit).
24051   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24052   if (X86::isZeroNode(N->getOperand(0)) &&
24053       X86::isZeroNode(N->getOperand(1)) &&
24054       // We don't have a good way to replace an EFLAGS use, so only do this when
24055       // dead right now.
24056       SDValue(N, 1).use_empty()) {
24057     SDLoc DL(N);
24058     EVT VT = N->getValueType(0);
24059     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24060     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24061                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24062                                            DAG.getConstant(X86::COND_B, DL,
24063                                                            MVT::i8),
24064                                            N->getOperand(2)),
24065                                DAG.getConstant(1, DL, VT));
24066     return DCI.CombineTo(N, Res1, CarryOut);
24067   }
24068
24069   return SDValue();
24070 }
24071
24072 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24073 //      (add Y, (setne X, 0)) -> sbb -1, Y
24074 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24075 //      (sub (setne X, 0), Y) -> adc -1, Y
24076 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24077   SDLoc DL(N);
24078
24079   // Look through ZExts.
24080   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24081   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24082     return SDValue();
24083
24084   SDValue SetCC = Ext.getOperand(0);
24085   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24086     return SDValue();
24087
24088   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24089   if (CC != X86::COND_E && CC != X86::COND_NE)
24090     return SDValue();
24091
24092   SDValue Cmp = SetCC.getOperand(1);
24093   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24094       !X86::isZeroNode(Cmp.getOperand(1)) ||
24095       !Cmp.getOperand(0).getValueType().isInteger())
24096     return SDValue();
24097
24098   SDValue CmpOp0 = Cmp.getOperand(0);
24099   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24100                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24101
24102   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24103   if (CC == X86::COND_NE)
24104     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24105                        DL, OtherVal.getValueType(), OtherVal,
24106                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24107                        NewCmp);
24108   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24109                      DL, OtherVal.getValueType(), OtherVal,
24110                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24111 }
24112
24113 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24114 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24115                                  const X86Subtarget *Subtarget) {
24116   EVT VT = N->getValueType(0);
24117   SDValue Op0 = N->getOperand(0);
24118   SDValue Op1 = N->getOperand(1);
24119
24120   // Try to synthesize horizontal adds from adds of shuffles.
24121   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24122        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24123       isHorizontalBinOp(Op0, Op1, true))
24124     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24125
24126   return OptimizeConditionalInDecrement(N, DAG);
24127 }
24128
24129 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24130                                  const X86Subtarget *Subtarget) {
24131   SDValue Op0 = N->getOperand(0);
24132   SDValue Op1 = N->getOperand(1);
24133
24134   // X86 can't encode an immediate LHS of a sub. See if we can push the
24135   // negation into a preceding instruction.
24136   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24137     // If the RHS of the sub is a XOR with one use and a constant, invert the
24138     // immediate. Then add one to the LHS of the sub so we can turn
24139     // X-Y -> X+~Y+1, saving one register.
24140     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24141         isa<ConstantSDNode>(Op1.getOperand(1))) {
24142       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24143       EVT VT = Op0.getValueType();
24144       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24145                                    Op1.getOperand(0),
24146                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24147       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24148                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24149     }
24150   }
24151
24152   // Try to synthesize horizontal adds from adds of shuffles.
24153   EVT VT = N->getValueType(0);
24154   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24155        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24156       isHorizontalBinOp(Op0, Op1, true))
24157     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24158
24159   return OptimizeConditionalInDecrement(N, DAG);
24160 }
24161
24162 /// performVZEXTCombine - Performs build vector combines
24163 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24164                                    TargetLowering::DAGCombinerInfo &DCI,
24165                                    const X86Subtarget *Subtarget) {
24166   SDLoc DL(N);
24167   MVT VT = N->getSimpleValueType(0);
24168   SDValue Op = N->getOperand(0);
24169   MVT OpVT = Op.getSimpleValueType();
24170   MVT OpEltVT = OpVT.getVectorElementType();
24171   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24172
24173   // (vzext (bitcast (vzext (x)) -> (vzext x)
24174   SDValue V = Op;
24175   while (V.getOpcode() == ISD::BITCAST)
24176     V = V.getOperand(0);
24177
24178   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24179     MVT InnerVT = V.getSimpleValueType();
24180     MVT InnerEltVT = InnerVT.getVectorElementType();
24181
24182     // If the element sizes match exactly, we can just do one larger vzext. This
24183     // is always an exact type match as vzext operates on integer types.
24184     if (OpEltVT == InnerEltVT) {
24185       assert(OpVT == InnerVT && "Types must match for vzext!");
24186       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24187     }
24188
24189     // The only other way we can combine them is if only a single element of the
24190     // inner vzext is used in the input to the outer vzext.
24191     if (InnerEltVT.getSizeInBits() < InputBits)
24192       return SDValue();
24193
24194     // In this case, the inner vzext is completely dead because we're going to
24195     // only look at bits inside of the low element. Just do the outer vzext on
24196     // a bitcast of the input to the inner.
24197     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24198                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24199   }
24200
24201   // Check if we can bypass extracting and re-inserting an element of an input
24202   // vector. Essentialy:
24203   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24204   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24205       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24206       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24207     SDValue ExtractedV = V.getOperand(0);
24208     SDValue OrigV = ExtractedV.getOperand(0);
24209     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24210       if (ExtractIdx->getZExtValue() == 0) {
24211         MVT OrigVT = OrigV.getSimpleValueType();
24212         // Extract a subvector if necessary...
24213         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24214           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24215           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24216                                     OrigVT.getVectorNumElements() / Ratio);
24217           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24218                               DAG.getIntPtrConstant(0, DL));
24219         }
24220         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24221         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24222       }
24223   }
24224
24225   return SDValue();
24226 }
24227
24228 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24229                                              DAGCombinerInfo &DCI) const {
24230   SelectionDAG &DAG = DCI.DAG;
24231   switch (N->getOpcode()) {
24232   default: break;
24233   case ISD::EXTRACT_VECTOR_ELT:
24234     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24235   case ISD::VSELECT:
24236   case ISD::SELECT:
24237   case X86ISD::SHRUNKBLEND:
24238     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24239   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24240   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24241   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24242   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24243   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24244   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24245   case ISD::SHL:
24246   case ISD::SRA:
24247   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24248   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24249   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24250   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24251   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24252   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24253   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24254   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24255   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24256   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24257   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24258   case X86ISD::FXOR:
24259   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24260   case X86ISD::FMIN:
24261   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24262   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24263   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24264   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24265   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24266   case ISD::ANY_EXTEND:
24267   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24268   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24269   case ISD::SIGN_EXTEND_INREG:
24270     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24271   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24272   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24273   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24274   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24275   case X86ISD::SHUFP:       // Handle all target specific shuffles
24276   case X86ISD::PALIGNR:
24277   case X86ISD::UNPCKH:
24278   case X86ISD::UNPCKL:
24279   case X86ISD::MOVHLPS:
24280   case X86ISD::MOVLHPS:
24281   case X86ISD::PSHUFB:
24282   case X86ISD::PSHUFD:
24283   case X86ISD::PSHUFHW:
24284   case X86ISD::PSHUFLW:
24285   case X86ISD::MOVSS:
24286   case X86ISD::MOVSD:
24287   case X86ISD::VPERMILPI:
24288   case X86ISD::VPERM2X128:
24289   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24290   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24291   case ISD::INTRINSIC_WO_CHAIN:
24292     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24293   case X86ISD::INSERTPS: {
24294     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24295       return PerformINSERTPSCombine(N, DAG, Subtarget);
24296     break;
24297   }
24298   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24299   }
24300
24301   return SDValue();
24302 }
24303
24304 /// isTypeDesirableForOp - Return true if the target has native support for
24305 /// the specified value type and it is 'desirable' to use the type for the
24306 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24307 /// instruction encodings are longer and some i16 instructions are slow.
24308 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24309   if (!isTypeLegal(VT))
24310     return false;
24311   if (VT != MVT::i16)
24312     return true;
24313
24314   switch (Opc) {
24315   default:
24316     return true;
24317   case ISD::LOAD:
24318   case ISD::SIGN_EXTEND:
24319   case ISD::ZERO_EXTEND:
24320   case ISD::ANY_EXTEND:
24321   case ISD::SHL:
24322   case ISD::SRL:
24323   case ISD::SUB:
24324   case ISD::ADD:
24325   case ISD::MUL:
24326   case ISD::AND:
24327   case ISD::OR:
24328   case ISD::XOR:
24329     return false;
24330   }
24331 }
24332
24333 /// IsDesirableToPromoteOp - This method query the target whether it is
24334 /// beneficial for dag combiner to promote the specified node. If true, it
24335 /// should return the desired promotion type by reference.
24336 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24337   EVT VT = Op.getValueType();
24338   if (VT != MVT::i16)
24339     return false;
24340
24341   bool Promote = false;
24342   bool Commute = false;
24343   switch (Op.getOpcode()) {
24344   default: break;
24345   case ISD::LOAD: {
24346     LoadSDNode *LD = cast<LoadSDNode>(Op);
24347     // If the non-extending load has a single use and it's not live out, then it
24348     // might be folded.
24349     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24350                                                      Op.hasOneUse()*/) {
24351       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24352              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24353         // The only case where we'd want to promote LOAD (rather then it being
24354         // promoted as an operand is when it's only use is liveout.
24355         if (UI->getOpcode() != ISD::CopyToReg)
24356           return false;
24357       }
24358     }
24359     Promote = true;
24360     break;
24361   }
24362   case ISD::SIGN_EXTEND:
24363   case ISD::ZERO_EXTEND:
24364   case ISD::ANY_EXTEND:
24365     Promote = true;
24366     break;
24367   case ISD::SHL:
24368   case ISD::SRL: {
24369     SDValue N0 = Op.getOperand(0);
24370     // Look out for (store (shl (load), x)).
24371     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24372       return false;
24373     Promote = true;
24374     break;
24375   }
24376   case ISD::ADD:
24377   case ISD::MUL:
24378   case ISD::AND:
24379   case ISD::OR:
24380   case ISD::XOR:
24381     Commute = true;
24382     // fallthrough
24383   case ISD::SUB: {
24384     SDValue N0 = Op.getOperand(0);
24385     SDValue N1 = Op.getOperand(1);
24386     if (!Commute && MayFoldLoad(N1))
24387       return false;
24388     // Avoid disabling potential load folding opportunities.
24389     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24390       return false;
24391     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24392       return false;
24393     Promote = true;
24394   }
24395   }
24396
24397   PVT = MVT::i32;
24398   return Promote;
24399 }
24400
24401 //===----------------------------------------------------------------------===//
24402 //                           X86 Inline Assembly Support
24403 //===----------------------------------------------------------------------===//
24404
24405 // Helper to match a string separated by whitespace.
24406 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24407   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24408
24409   for (StringRef Piece : Pieces) {
24410     if (!S.startswith(Piece)) // Check if the piece matches.
24411       return false;
24412
24413     S = S.substr(Piece.size());
24414     StringRef::size_type Pos = S.find_first_not_of(" \t");
24415     if (Pos == 0) // We matched a prefix.
24416       return false;
24417
24418     S = S.substr(Pos);
24419   }
24420
24421   return S.empty();
24422 }
24423
24424 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24425
24426   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24427     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24428         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24429         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24430
24431       if (AsmPieces.size() == 3)
24432         return true;
24433       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24434         return true;
24435     }
24436   }
24437   return false;
24438 }
24439
24440 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24441   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24442
24443   std::string AsmStr = IA->getAsmString();
24444
24445   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24446   if (!Ty || Ty->getBitWidth() % 16 != 0)
24447     return false;
24448
24449   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24450   SmallVector<StringRef, 4> AsmPieces;
24451   SplitString(AsmStr, AsmPieces, ";\n");
24452
24453   switch (AsmPieces.size()) {
24454   default: return false;
24455   case 1:
24456     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24457     // we will turn this bswap into something that will be lowered to logical
24458     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24459     // lower so don't worry about this.
24460     // bswap $0
24461     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24462         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24463         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24464         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24465         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24466         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24467       // No need to check constraints, nothing other than the equivalent of
24468       // "=r,0" would be valid here.
24469       return IntrinsicLowering::LowerToByteSwap(CI);
24470     }
24471
24472     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24473     if (CI->getType()->isIntegerTy(16) &&
24474         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24475         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24476          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24477       AsmPieces.clear();
24478       const std::string &ConstraintsStr = IA->getConstraintString();
24479       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24480       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24481       if (clobbersFlagRegisters(AsmPieces))
24482         return IntrinsicLowering::LowerToByteSwap(CI);
24483     }
24484     break;
24485   case 3:
24486     if (CI->getType()->isIntegerTy(32) &&
24487         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24488         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24489         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24490         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24491       AsmPieces.clear();
24492       const std::string &ConstraintsStr = IA->getConstraintString();
24493       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24494       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24495       if (clobbersFlagRegisters(AsmPieces))
24496         return IntrinsicLowering::LowerToByteSwap(CI);
24497     }
24498
24499     if (CI->getType()->isIntegerTy(64)) {
24500       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24501       if (Constraints.size() >= 2 &&
24502           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24503           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24504         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24505         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24506             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24507             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24508           return IntrinsicLowering::LowerToByteSwap(CI);
24509       }
24510     }
24511     break;
24512   }
24513   return false;
24514 }
24515
24516 /// getConstraintType - Given a constraint letter, return the type of
24517 /// constraint it is for this target.
24518 X86TargetLowering::ConstraintType
24519 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24520   if (Constraint.size() == 1) {
24521     switch (Constraint[0]) {
24522     case 'R':
24523     case 'q':
24524     case 'Q':
24525     case 'f':
24526     case 't':
24527     case 'u':
24528     case 'y':
24529     case 'x':
24530     case 'Y':
24531     case 'l':
24532       return C_RegisterClass;
24533     case 'a':
24534     case 'b':
24535     case 'c':
24536     case 'd':
24537     case 'S':
24538     case 'D':
24539     case 'A':
24540       return C_Register;
24541     case 'I':
24542     case 'J':
24543     case 'K':
24544     case 'L':
24545     case 'M':
24546     case 'N':
24547     case 'G':
24548     case 'C':
24549     case 'e':
24550     case 'Z':
24551       return C_Other;
24552     default:
24553       break;
24554     }
24555   }
24556   return TargetLowering::getConstraintType(Constraint);
24557 }
24558
24559 /// Examine constraint type and operand type and determine a weight value.
24560 /// This object must already have been set up with the operand type
24561 /// and the current alternative constraint selected.
24562 TargetLowering::ConstraintWeight
24563   X86TargetLowering::getSingleConstraintMatchWeight(
24564     AsmOperandInfo &info, const char *constraint) const {
24565   ConstraintWeight weight = CW_Invalid;
24566   Value *CallOperandVal = info.CallOperandVal;
24567     // If we don't have a value, we can't do a match,
24568     // but allow it at the lowest weight.
24569   if (!CallOperandVal)
24570     return CW_Default;
24571   Type *type = CallOperandVal->getType();
24572   // Look at the constraint type.
24573   switch (*constraint) {
24574   default:
24575     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24576   case 'R':
24577   case 'q':
24578   case 'Q':
24579   case 'a':
24580   case 'b':
24581   case 'c':
24582   case 'd':
24583   case 'S':
24584   case 'D':
24585   case 'A':
24586     if (CallOperandVal->getType()->isIntegerTy())
24587       weight = CW_SpecificReg;
24588     break;
24589   case 'f':
24590   case 't':
24591   case 'u':
24592     if (type->isFloatingPointTy())
24593       weight = CW_SpecificReg;
24594     break;
24595   case 'y':
24596     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24597       weight = CW_SpecificReg;
24598     break;
24599   case 'x':
24600   case 'Y':
24601     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24602         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24603       weight = CW_Register;
24604     break;
24605   case 'I':
24606     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24607       if (C->getZExtValue() <= 31)
24608         weight = CW_Constant;
24609     }
24610     break;
24611   case 'J':
24612     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24613       if (C->getZExtValue() <= 63)
24614         weight = CW_Constant;
24615     }
24616     break;
24617   case 'K':
24618     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24619       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24620         weight = CW_Constant;
24621     }
24622     break;
24623   case 'L':
24624     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24625       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24626         weight = CW_Constant;
24627     }
24628     break;
24629   case 'M':
24630     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24631       if (C->getZExtValue() <= 3)
24632         weight = CW_Constant;
24633     }
24634     break;
24635   case 'N':
24636     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24637       if (C->getZExtValue() <= 0xff)
24638         weight = CW_Constant;
24639     }
24640     break;
24641   case 'G':
24642   case 'C':
24643     if (isa<ConstantFP>(CallOperandVal)) {
24644       weight = CW_Constant;
24645     }
24646     break;
24647   case 'e':
24648     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24649       if ((C->getSExtValue() >= -0x80000000LL) &&
24650           (C->getSExtValue() <= 0x7fffffffLL))
24651         weight = CW_Constant;
24652     }
24653     break;
24654   case 'Z':
24655     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24656       if (C->getZExtValue() <= 0xffffffff)
24657         weight = CW_Constant;
24658     }
24659     break;
24660   }
24661   return weight;
24662 }
24663
24664 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24665 /// with another that has more specific requirements based on the type of the
24666 /// corresponding operand.
24667 const char *X86TargetLowering::
24668 LowerXConstraint(EVT ConstraintVT) const {
24669   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24670   // 'f' like normal targets.
24671   if (ConstraintVT.isFloatingPoint()) {
24672     if (Subtarget->hasSSE2())
24673       return "Y";
24674     if (Subtarget->hasSSE1())
24675       return "x";
24676   }
24677
24678   return TargetLowering::LowerXConstraint(ConstraintVT);
24679 }
24680
24681 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24682 /// vector.  If it is invalid, don't add anything to Ops.
24683 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24684                                                      std::string &Constraint,
24685                                                      std::vector<SDValue>&Ops,
24686                                                      SelectionDAG &DAG) const {
24687   SDValue Result;
24688
24689   // Only support length 1 constraints for now.
24690   if (Constraint.length() > 1) return;
24691
24692   char ConstraintLetter = Constraint[0];
24693   switch (ConstraintLetter) {
24694   default: break;
24695   case 'I':
24696     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24697       if (C->getZExtValue() <= 31) {
24698         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24699                                        Op.getValueType());
24700         break;
24701       }
24702     }
24703     return;
24704   case 'J':
24705     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24706       if (C->getZExtValue() <= 63) {
24707         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24708                                        Op.getValueType());
24709         break;
24710       }
24711     }
24712     return;
24713   case 'K':
24714     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24715       if (isInt<8>(C->getSExtValue())) {
24716         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24717                                        Op.getValueType());
24718         break;
24719       }
24720     }
24721     return;
24722   case 'L':
24723     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24724       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24725           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24726         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24727                                        Op.getValueType());
24728         break;
24729       }
24730     }
24731     return;
24732   case 'M':
24733     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24734       if (C->getZExtValue() <= 3) {
24735         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24736                                        Op.getValueType());
24737         break;
24738       }
24739     }
24740     return;
24741   case 'N':
24742     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24743       if (C->getZExtValue() <= 255) {
24744         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24745                                        Op.getValueType());
24746         break;
24747       }
24748     }
24749     return;
24750   case 'O':
24751     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24752       if (C->getZExtValue() <= 127) {
24753         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24754                                        Op.getValueType());
24755         break;
24756       }
24757     }
24758     return;
24759   case 'e': {
24760     // 32-bit signed value
24761     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24762       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24763                                            C->getSExtValue())) {
24764         // Widen to 64 bits here to get it sign extended.
24765         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24766         break;
24767       }
24768     // FIXME gcc accepts some relocatable values here too, but only in certain
24769     // memory models; it's complicated.
24770     }
24771     return;
24772   }
24773   case 'Z': {
24774     // 32-bit unsigned value
24775     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24776       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24777                                            C->getZExtValue())) {
24778         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24779                                        Op.getValueType());
24780         break;
24781       }
24782     }
24783     // FIXME gcc accepts some relocatable values here too, but only in certain
24784     // memory models; it's complicated.
24785     return;
24786   }
24787   case 'i': {
24788     // Literal immediates are always ok.
24789     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24790       // Widen to 64 bits here to get it sign extended.
24791       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24792       break;
24793     }
24794
24795     // In any sort of PIC mode addresses need to be computed at runtime by
24796     // adding in a register or some sort of table lookup.  These can't
24797     // be used as immediates.
24798     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24799       return;
24800
24801     // If we are in non-pic codegen mode, we allow the address of a global (with
24802     // an optional displacement) to be used with 'i'.
24803     GlobalAddressSDNode *GA = nullptr;
24804     int64_t Offset = 0;
24805
24806     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24807     while (1) {
24808       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24809         Offset += GA->getOffset();
24810         break;
24811       } else if (Op.getOpcode() == ISD::ADD) {
24812         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24813           Offset += C->getZExtValue();
24814           Op = Op.getOperand(0);
24815           continue;
24816         }
24817       } else if (Op.getOpcode() == ISD::SUB) {
24818         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24819           Offset += -C->getZExtValue();
24820           Op = Op.getOperand(0);
24821           continue;
24822         }
24823       }
24824
24825       // Otherwise, this isn't something we can handle, reject it.
24826       return;
24827     }
24828
24829     const GlobalValue *GV = GA->getGlobal();
24830     // If we require an extra load to get this address, as in PIC mode, we
24831     // can't accept it.
24832     if (isGlobalStubReference(
24833             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24834       return;
24835
24836     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24837                                         GA->getValueType(0), Offset);
24838     break;
24839   }
24840   }
24841
24842   if (Result.getNode()) {
24843     Ops.push_back(Result);
24844     return;
24845   }
24846   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24847 }
24848
24849 std::pair<unsigned, const TargetRegisterClass *>
24850 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24851                                                 const std::string &Constraint,
24852                                                 MVT VT) const {
24853   // First, see if this is a constraint that directly corresponds to an LLVM
24854   // register class.
24855   if (Constraint.size() == 1) {
24856     // GCC Constraint Letters
24857     switch (Constraint[0]) {
24858     default: break;
24859       // TODO: Slight differences here in allocation order and leaving
24860       // RIP in the class. Do they matter any more here than they do
24861       // in the normal allocation?
24862     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24863       if (Subtarget->is64Bit()) {
24864         if (VT == MVT::i32 || VT == MVT::f32)
24865           return std::make_pair(0U, &X86::GR32RegClass);
24866         if (VT == MVT::i16)
24867           return std::make_pair(0U, &X86::GR16RegClass);
24868         if (VT == MVT::i8 || VT == MVT::i1)
24869           return std::make_pair(0U, &X86::GR8RegClass);
24870         if (VT == MVT::i64 || VT == MVT::f64)
24871           return std::make_pair(0U, &X86::GR64RegClass);
24872         break;
24873       }
24874       // 32-bit fallthrough
24875     case 'Q':   // Q_REGS
24876       if (VT == MVT::i32 || VT == MVT::f32)
24877         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24878       if (VT == MVT::i16)
24879         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24880       if (VT == MVT::i8 || VT == MVT::i1)
24881         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24882       if (VT == MVT::i64)
24883         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24884       break;
24885     case 'r':   // GENERAL_REGS
24886     case 'l':   // INDEX_REGS
24887       if (VT == MVT::i8 || VT == MVT::i1)
24888         return std::make_pair(0U, &X86::GR8RegClass);
24889       if (VT == MVT::i16)
24890         return std::make_pair(0U, &X86::GR16RegClass);
24891       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24892         return std::make_pair(0U, &X86::GR32RegClass);
24893       return std::make_pair(0U, &X86::GR64RegClass);
24894     case 'R':   // LEGACY_REGS
24895       if (VT == MVT::i8 || VT == MVT::i1)
24896         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24897       if (VT == MVT::i16)
24898         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24899       if (VT == MVT::i32 || !Subtarget->is64Bit())
24900         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24901       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24902     case 'f':  // FP Stack registers.
24903       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24904       // value to the correct fpstack register class.
24905       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24906         return std::make_pair(0U, &X86::RFP32RegClass);
24907       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24908         return std::make_pair(0U, &X86::RFP64RegClass);
24909       return std::make_pair(0U, &X86::RFP80RegClass);
24910     case 'y':   // MMX_REGS if MMX allowed.
24911       if (!Subtarget->hasMMX()) break;
24912       return std::make_pair(0U, &X86::VR64RegClass);
24913     case 'Y':   // SSE_REGS if SSE2 allowed
24914       if (!Subtarget->hasSSE2()) break;
24915       // FALL THROUGH.
24916     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24917       if (!Subtarget->hasSSE1()) break;
24918
24919       switch (VT.SimpleTy) {
24920       default: break;
24921       // Scalar SSE types.
24922       case MVT::f32:
24923       case MVT::i32:
24924         return std::make_pair(0U, &X86::FR32RegClass);
24925       case MVT::f64:
24926       case MVT::i64:
24927         return std::make_pair(0U, &X86::FR64RegClass);
24928       // Vector types.
24929       case MVT::v16i8:
24930       case MVT::v8i16:
24931       case MVT::v4i32:
24932       case MVT::v2i64:
24933       case MVT::v4f32:
24934       case MVT::v2f64:
24935         return std::make_pair(0U, &X86::VR128RegClass);
24936       // AVX types.
24937       case MVT::v32i8:
24938       case MVT::v16i16:
24939       case MVT::v8i32:
24940       case MVT::v4i64:
24941       case MVT::v8f32:
24942       case MVT::v4f64:
24943         return std::make_pair(0U, &X86::VR256RegClass);
24944       case MVT::v8f64:
24945       case MVT::v16f32:
24946       case MVT::v16i32:
24947       case MVT::v8i64:
24948         return std::make_pair(0U, &X86::VR512RegClass);
24949       }
24950       break;
24951     }
24952   }
24953
24954   // Use the default implementation in TargetLowering to convert the register
24955   // constraint into a member of a register class.
24956   std::pair<unsigned, const TargetRegisterClass*> Res;
24957   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24958
24959   // Not found as a standard register?
24960   if (!Res.second) {
24961     // Map st(0) -> st(7) -> ST0
24962     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24963         tolower(Constraint[1]) == 's' &&
24964         tolower(Constraint[2]) == 't' &&
24965         Constraint[3] == '(' &&
24966         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24967         Constraint[5] == ')' &&
24968         Constraint[6] == '}') {
24969
24970       Res.first = X86::FP0+Constraint[4]-'0';
24971       Res.second = &X86::RFP80RegClass;
24972       return Res;
24973     }
24974
24975     // GCC allows "st(0)" to be called just plain "st".
24976     if (StringRef("{st}").equals_lower(Constraint)) {
24977       Res.first = X86::FP0;
24978       Res.second = &X86::RFP80RegClass;
24979       return Res;
24980     }
24981
24982     // flags -> EFLAGS
24983     if (StringRef("{flags}").equals_lower(Constraint)) {
24984       Res.first = X86::EFLAGS;
24985       Res.second = &X86::CCRRegClass;
24986       return Res;
24987     }
24988
24989     // 'A' means EAX + EDX.
24990     if (Constraint == "A") {
24991       Res.first = X86::EAX;
24992       Res.second = &X86::GR32_ADRegClass;
24993       return Res;
24994     }
24995     return Res;
24996   }
24997
24998   // Otherwise, check to see if this is a register class of the wrong value
24999   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25000   // turn into {ax},{dx}.
25001   if (Res.second->hasType(VT))
25002     return Res;   // Correct type already, nothing to do.
25003
25004   // All of the single-register GCC register classes map their values onto
25005   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25006   // really want an 8-bit or 32-bit register, map to the appropriate register
25007   // class and return the appropriate register.
25008   if (Res.second == &X86::GR16RegClass) {
25009     if (VT == MVT::i8 || VT == MVT::i1) {
25010       unsigned DestReg = 0;
25011       switch (Res.first) {
25012       default: break;
25013       case X86::AX: DestReg = X86::AL; break;
25014       case X86::DX: DestReg = X86::DL; break;
25015       case X86::CX: DestReg = X86::CL; break;
25016       case X86::BX: DestReg = X86::BL; break;
25017       }
25018       if (DestReg) {
25019         Res.first = DestReg;
25020         Res.second = &X86::GR8RegClass;
25021       }
25022     } else if (VT == MVT::i32 || VT == MVT::f32) {
25023       unsigned DestReg = 0;
25024       switch (Res.first) {
25025       default: break;
25026       case X86::AX: DestReg = X86::EAX; break;
25027       case X86::DX: DestReg = X86::EDX; break;
25028       case X86::CX: DestReg = X86::ECX; break;
25029       case X86::BX: DestReg = X86::EBX; break;
25030       case X86::SI: DestReg = X86::ESI; break;
25031       case X86::DI: DestReg = X86::EDI; break;
25032       case X86::BP: DestReg = X86::EBP; break;
25033       case X86::SP: DestReg = X86::ESP; break;
25034       }
25035       if (DestReg) {
25036         Res.first = DestReg;
25037         Res.second = &X86::GR32RegClass;
25038       }
25039     } else if (VT == MVT::i64 || VT == MVT::f64) {
25040       unsigned DestReg = 0;
25041       switch (Res.first) {
25042       default: break;
25043       case X86::AX: DestReg = X86::RAX; break;
25044       case X86::DX: DestReg = X86::RDX; break;
25045       case X86::CX: DestReg = X86::RCX; break;
25046       case X86::BX: DestReg = X86::RBX; break;
25047       case X86::SI: DestReg = X86::RSI; break;
25048       case X86::DI: DestReg = X86::RDI; break;
25049       case X86::BP: DestReg = X86::RBP; break;
25050       case X86::SP: DestReg = X86::RSP; break;
25051       }
25052       if (DestReg) {
25053         Res.first = DestReg;
25054         Res.second = &X86::GR64RegClass;
25055       }
25056     }
25057   } else if (Res.second == &X86::FR32RegClass ||
25058              Res.second == &X86::FR64RegClass ||
25059              Res.second == &X86::VR128RegClass ||
25060              Res.second == &X86::VR256RegClass ||
25061              Res.second == &X86::FR32XRegClass ||
25062              Res.second == &X86::FR64XRegClass ||
25063              Res.second == &X86::VR128XRegClass ||
25064              Res.second == &X86::VR256XRegClass ||
25065              Res.second == &X86::VR512RegClass) {
25066     // Handle references to XMM physical registers that got mapped into the
25067     // wrong class.  This can happen with constraints like {xmm0} where the
25068     // target independent register mapper will just pick the first match it can
25069     // find, ignoring the required type.
25070
25071     if (VT == MVT::f32 || VT == MVT::i32)
25072       Res.second = &X86::FR32RegClass;
25073     else if (VT == MVT::f64 || VT == MVT::i64)
25074       Res.second = &X86::FR64RegClass;
25075     else if (X86::VR128RegClass.hasType(VT))
25076       Res.second = &X86::VR128RegClass;
25077     else if (X86::VR256RegClass.hasType(VT))
25078       Res.second = &X86::VR256RegClass;
25079     else if (X86::VR512RegClass.hasType(VT))
25080       Res.second = &X86::VR512RegClass;
25081   }
25082
25083   return Res;
25084 }
25085
25086 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25087                                             Type *Ty) const {
25088   // Scaling factors are not free at all.
25089   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25090   // will take 2 allocations in the out of order engine instead of 1
25091   // for plain addressing mode, i.e. inst (reg1).
25092   // E.g.,
25093   // vaddps (%rsi,%drx), %ymm0, %ymm1
25094   // Requires two allocations (one for the load, one for the computation)
25095   // whereas:
25096   // vaddps (%rsi), %ymm0, %ymm1
25097   // Requires just 1 allocation, i.e., freeing allocations for other operations
25098   // and having less micro operations to execute.
25099   //
25100   // For some X86 architectures, this is even worse because for instance for
25101   // stores, the complex addressing mode forces the instruction to use the
25102   // "load" ports instead of the dedicated "store" port.
25103   // E.g., on Haswell:
25104   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25105   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25106   if (isLegalAddressingMode(AM, Ty))
25107     // Scale represents reg2 * scale, thus account for 1
25108     // as soon as we use a second register.
25109     return AM.Scale != 0;
25110   return -1;
25111 }
25112
25113 bool X86TargetLowering::isTargetFTOL() const {
25114   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25115 }