Taints the non-acquire RMW's store address with the load part
[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 "X86ShuffleDecodeConstantPool.h"
22 #include "X86TargetMachine.h"
23 #include "X86TargetObjectFile.h"
24 #include "llvm/ADT/SmallBitVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/WinEHFuncInfo.h"
38 #include "llvm/IR/CallSite.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalAlias.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/MC/MCAsmInfo.h"
48 #include "llvm/MC/MCContext.h"
49 #include "llvm/MC/MCExpr.h"
50 #include "llvm/MC/MCSymbol.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Target/TargetOptions.h"
56 #include "X86IntrinsicsInfo.h"
57 #include <bitset>
58 #include <numeric>
59 #include <cctype>
60 using namespace llvm;
61
62 #define DEBUG_TYPE "x86-isel"
63
64 STATISTIC(NumTailCalls, "Number of tail calls");
65
66 static cl::opt<bool> ExperimentalVectorWideningLegalization(
67     "x86-experimental-vector-widening-legalization", cl::init(false),
68     cl::desc("Enable an experimental vector type legalization through widening "
69              "rather than promotion."),
70     cl::Hidden);
71
72 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
73                                      const X86Subtarget &STI)
74     : TargetLowering(TM), Subtarget(&STI) {
75   X86ScalarSSEf64 = Subtarget->hasSSE2();
76   X86ScalarSSEf32 = Subtarget->hasSSE1();
77   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
78
79   // Set up the TargetLowering object.
80
81   // X86 is weird. It always uses i8 for shift amounts and setcc results.
82   setBooleanContents(ZeroOrOneBooleanContent);
83   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
84   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
85
86   // For 64-bit, since we have so many registers, use the ILP scheduler.
87   // For 32-bit, use the register pressure specific scheduling.
88   // For Atom, always use ILP scheduling.
89   if (Subtarget->isAtom())
90     setSchedulingPreference(Sched::ILP);
91   else if (Subtarget->is64Bit())
92     setSchedulingPreference(Sched::ILP);
93   else
94     setSchedulingPreference(Sched::RegPressure);
95   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
96   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
97
98   // Bypass expensive divides on Atom when compiling with O2.
99   if (TM.getOptLevel() >= CodeGenOpt::Default) {
100     if (Subtarget->hasSlowDivide32())
101       addBypassSlowDiv(32, 8);
102     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
103       addBypassSlowDiv(64, 16);
104   }
105
106   if (Subtarget->isTargetKnownWindowsMSVC()) {
107     // Setup Windows compiler runtime calls.
108     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
109     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
110     setLibcallName(RTLIB::SREM_I64, "_allrem");
111     setLibcallName(RTLIB::UREM_I64, "_aullrem");
112     setLibcallName(RTLIB::MUL_I64, "_allmul");
113     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
117     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
118   }
119
120   if (Subtarget->isTargetDarwin()) {
121     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
122     setUseUnderscoreSetJmp(false);
123     setUseUnderscoreLongJmp(false);
124   } else if (Subtarget->isTargetWindowsGNU()) {
125     // MS runtime is weird: it exports _setjmp, but longjmp!
126     setUseUnderscoreSetJmp(true);
127     setUseUnderscoreLongJmp(false);
128   } else {
129     setUseUnderscoreSetJmp(true);
130     setUseUnderscoreLongJmp(true);
131   }
132
133   // Set up the register classes.
134   addRegisterClass(MVT::i8, &X86::GR8RegClass);
135   addRegisterClass(MVT::i16, &X86::GR16RegClass);
136   addRegisterClass(MVT::i32, &X86::GR32RegClass);
137   if (Subtarget->is64Bit())
138     addRegisterClass(MVT::i64, &X86::GR64RegClass);
139
140   for (MVT VT : MVT::integer_valuetypes())
141     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142
143   // We don't accept any truncstore of integer registers.
144   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
146   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
147   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
148   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
149   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
150
151   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
152
153   // SETOEQ and SETUNE require checking two conditions.
154   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
155   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
156   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
158   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
159   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
160
161   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
162   // operation.
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
164   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
165   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
166
167   if (Subtarget->is64Bit()) {
168     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
169       // f32/f64 are legal, f80 is custom.
170       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
171     else
172       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
173     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
174   } else if (!Subtarget->useSoftFloat()) {
175     // We have an algorithm for SSE2->double, and we turn this into a
176     // 64-bit FILD followed by conditional FADD for other targets.
177     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
178     // We have an algorithm for SSE2, and we turn this into a 64-bit
179     // FILD or VCVTUSI2SS/SD for other targets.
180     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
181   }
182
183   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
184   // this operation.
185   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
186   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
187
188   if (!Subtarget->useSoftFloat()) {
189     // SSE has no i16 to fp conversion, only i32
190     if (X86ScalarSSEf32) {
191       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
192       // f32 and f64 cases are Legal, f80 case is not
193       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
194     } else {
195       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
196       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
197     }
198   } else {
199     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
200     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
201   }
202
203   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
204   // this operation.
205   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
206   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
207
208   if (!Subtarget->useSoftFloat()) {
209     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
210     // are Legal, f80 is custom lowered.
211     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
212     setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
213
214     if (X86ScalarSSEf32) {
215       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
216       // f32 and f64 cases are Legal, f80 case is not
217       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
218     } else {
219       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
220       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
221     }
222   } else {
223     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Expand);
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Expand);
226   }
227
228   // Handle FP_TO_UINT by promoting the destination to a larger signed
229   // conversion.
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
232   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
233
234   if (Subtarget->is64Bit()) {
235     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
236       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
237       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
238       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
239     } else {
240       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
241       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
242     }
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 AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
252       // With SSE3 we can use fisttpll to convert to a signed i64; without
253       // SSE, we're stuck with a fistpll.
254       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
255
256     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
257   }
258
259   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
260   if (!X86ScalarSSEf64) {
261     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
262     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
263     if (Subtarget->is64Bit()) {
264       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
265       // Without SSE, i64->f64 goes through memory.
266       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
267     }
268   } else if (!Subtarget->is64Bit())
269     setOperationAction(ISD::BITCAST      , MVT::i64  , Custom);
270
271   // Scalar integer divide and remainder are lowered to use operations that
272   // produce two results, to match the available instructions. This exposes
273   // the two-result form to trivial CSE, which is able to combine x/y and x%y
274   // into a single instruction.
275   //
276   // Scalar integer multiply-high is also lowered to use two-result
277   // operations, to match the available instructions. However, plain multiply
278   // (low) operations are left as Legal, as there are single-result
279   // instructions for this in x86. Using the two-result multiply instructions
280   // when both high and low results are needed must be arranged by dagcombine.
281   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
282     setOperationAction(ISD::MULHS, VT, Expand);
283     setOperationAction(ISD::MULHU, VT, Expand);
284     setOperationAction(ISD::SDIV, VT, Expand);
285     setOperationAction(ISD::UDIV, VT, Expand);
286     setOperationAction(ISD::SREM, VT, Expand);
287     setOperationAction(ISD::UREM, VT, Expand);
288
289     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
290     setOperationAction(ISD::ADDC, VT, Custom);
291     setOperationAction(ISD::ADDE, VT, Custom);
292     setOperationAction(ISD::SUBC, VT, Custom);
293     setOperationAction(ISD::SUBE, VT, Custom);
294   }
295
296   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
297   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
298   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
299   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::f128,  Expand);
302   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
303   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
305   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::f128,  Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
313   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
314   if (Subtarget->is64Bit())
315     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
316   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
318   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
319   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
320
321   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
322     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
323     // is. We should promote the value to 64-bits to solve this.
324     // This is what the CRT headers do - `fmodf` is an inline header
325     // function casting to f64 and calling `fmod`.
326     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
327   } else {
328     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
329   }
330
331   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
332   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
333   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
334
335   // Promote the i8 variants and force them on up to i32 which has a shorter
336   // encoding.
337   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
338   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
339   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
340   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
341   if (Subtarget->hasBMI()) {
342     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
343     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
344     if (Subtarget->is64Bit())
345       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
346   } else {
347     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
348     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
349     if (Subtarget->is64Bit())
350       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
351   }
352
353   if (Subtarget->hasLZCNT()) {
354     // When promoting the i8 variants, force them to i32 for a shorter
355     // encoding.
356     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
357     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
358     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
359     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
361     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
362     if (Subtarget->is64Bit())
363       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
364   } else {
365     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
366     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
367     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
368     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
369     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
370     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
371     if (Subtarget->is64Bit()) {
372       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
373       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
374     }
375   }
376
377   // Special handling for half-precision floating point conversions.
378   // If we don't have F16C support, then lower half float conversions
379   // into library calls.
380   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
381     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
382     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
383   }
384
385   // There's never any support for operations beyond MVT::f32.
386   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
387   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
388   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
389   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
390
391   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
392   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
393   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
394   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
395   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
396   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
397
398   if (Subtarget->hasPOPCNT()) {
399     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
400   } else {
401     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
402     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
403     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
404     if (Subtarget->is64Bit())
405       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
406   }
407
408   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
409
410   if (!Subtarget->hasMOVBE())
411     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
412
413   // These should be promoted to a larger select which is supported.
414   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
415   // X86 wants to expand cmov itself.
416   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
417   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
418   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
419   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
420   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
421   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
422   setOperationAction(ISD::SELECT          , MVT::f128 , Custom);
423   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
424   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
425   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
427   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
428   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
429   setOperationAction(ISD::SETCC           , MVT::f128 , Custom);
430   setOperationAction(ISD::SETCCE          , MVT::i8   , Custom);
431   setOperationAction(ISD::SETCCE          , MVT::i16  , Custom);
432   setOperationAction(ISD::SETCCE          , MVT::i32  , Custom);
433   if (Subtarget->is64Bit()) {
434     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
435     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
436     setOperationAction(ISD::SETCCE        , MVT::i64  , Custom);
437   }
438   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
439   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
440   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
441   // support continuation, user-level threading, and etc.. As a result, no
442   // other SjLj exception interfaces are implemented and please don't build
443   // your own exception handling based on them.
444   // LLVM/Clang supports zero-cost DWARF exception handling.
445   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
446   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
447
448   // Darwin ABI issue.
449   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
450   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
451   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
452   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
453   if (Subtarget->is64Bit())
454     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
455   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
456   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
457   if (Subtarget->is64Bit()) {
458     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
459     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
460     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
461     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
462     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
463   }
464   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
465   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
466   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
467   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
468   if (Subtarget->is64Bit()) {
469     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
470     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
471     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
472   }
473
474   if (Subtarget->hasSSE1())
475     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
476
477   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
478
479   // Expand certain atomics
480   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
481     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
482     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
483     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
484   }
485
486   if (Subtarget->hasCmpxchg16b()) {
487     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
488   }
489
490   // FIXME - use subtarget debug flags
491   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
492       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
493     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
494   }
495
496   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
497   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
498
499   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
500   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
501
502   setOperationAction(ISD::TRAP, MVT::Other, Legal);
503   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
504
505   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
506   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
507   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
508   if (Subtarget->is64Bit()) {
509     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
510     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
511   } else {
512     // TargetInfo::CharPtrBuiltinVaList
513     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
514     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
515   }
516
517   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
518   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
519
520   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
521
522   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
523   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
524   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
525
526   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
527     // f32 and f64 use SSE.
528     // Set up the FP register classes.
529     addRegisterClass(MVT::f32, &X86::FR32RegClass);
530     addRegisterClass(MVT::f64, &X86::FR64RegClass);
531
532     // Use ANDPD to simulate FABS.
533     setOperationAction(ISD::FABS , MVT::f64, Custom);
534     setOperationAction(ISD::FABS , MVT::f32, Custom);
535
536     // Use XORP to simulate FNEG.
537     setOperationAction(ISD::FNEG , MVT::f64, Custom);
538     setOperationAction(ISD::FNEG , MVT::f32, Custom);
539
540     // Use ANDPD and ORPD to simulate FCOPYSIGN.
541     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
542     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
543
544     // Lower this to FGETSIGNx86 plus an AND.
545     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
546     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
547
548     // We don't support sin/cos/fmod
549     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
550     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
551     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
552     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
553     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
554     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
555
556     // Expand FP immediates into loads from the stack, except for the special
557     // cases we handle.
558     addLegalFPImmediate(APFloat(+0.0)); // xorpd
559     addLegalFPImmediate(APFloat(+0.0f)); // xorps
560   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
561     // Use SSE for f32, x87 for f64.
562     // Set up the FP register classes.
563     addRegisterClass(MVT::f32, &X86::FR32RegClass);
564     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
565
566     // Use ANDPS to simulate FABS.
567     setOperationAction(ISD::FABS , MVT::f32, Custom);
568
569     // Use XORP to simulate FNEG.
570     setOperationAction(ISD::FNEG , MVT::f32, Custom);
571
572     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
573
574     // Use ANDPS and ORPS to simulate FCOPYSIGN.
575     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
576     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
577
578     // We don't support sin/cos/fmod
579     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
580     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
581     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
582
583     // Special cases we handle for FP constants.
584     addLegalFPImmediate(APFloat(+0.0f)); // xorps
585     addLegalFPImmediate(APFloat(+0.0)); // FLD0
586     addLegalFPImmediate(APFloat(+1.0)); // FLD1
587     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
588     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
589
590     if (!TM.Options.UnsafeFPMath) {
591       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
592       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
593       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
594     }
595   } else if (!Subtarget->useSoftFloat()) {
596     // f32 and f64 in x87.
597     // Set up the FP register classes.
598     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
599     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
600
601     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
602     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
603     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
604     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
605
606     if (!TM.Options.UnsafeFPMath) {
607       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
608       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
609       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
610       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
611       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
612       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
613     }
614     addLegalFPImmediate(APFloat(+0.0)); // FLD0
615     addLegalFPImmediate(APFloat(+1.0)); // FLD1
616     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
617     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
618     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
619     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
620     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
621     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
622   }
623
624   // We don't support FMA.
625   setOperationAction(ISD::FMA, MVT::f64, Expand);
626   setOperationAction(ISD::FMA, MVT::f32, Expand);
627
628   // Long double always uses X87, except f128 in MMX.
629   if (!Subtarget->useSoftFloat()) {
630     if (Subtarget->is64Bit() && Subtarget->hasMMX()) {
631       addRegisterClass(MVT::f128, &X86::FR128RegClass);
632       ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
633       setOperationAction(ISD::FABS , MVT::f128, Custom);
634       setOperationAction(ISD::FNEG , MVT::f128, Custom);
635       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
636     }
637
638     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
639     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
640     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
641     {
642       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
643       addLegalFPImmediate(TmpFlt);  // FLD0
644       TmpFlt.changeSign();
645       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
646
647       bool ignored;
648       APFloat TmpFlt2(+1.0);
649       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
650                       &ignored);
651       addLegalFPImmediate(TmpFlt2);  // FLD1
652       TmpFlt2.changeSign();
653       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
654     }
655
656     if (!TM.Options.UnsafeFPMath) {
657       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
658       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
659       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
660     }
661
662     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
663     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
664     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
665     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
666     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
667     setOperationAction(ISD::FMA, MVT::f80, Expand);
668   }
669
670   // Always use a library call for pow.
671   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
672   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
673   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
674
675   setOperationAction(ISD::FLOG, MVT::f80, Expand);
676   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
677   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
678   setOperationAction(ISD::FEXP, MVT::f80, Expand);
679   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
680   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
681   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
682
683   // First set operation action for all vector types to either promote
684   // (for widening) or expand (for scalarization). Then we will selectively
685   // turn on ones that can be effectively codegen'd.
686   for (MVT VT : MVT::vector_valuetypes()) {
687     setOperationAction(ISD::ADD , VT, Expand);
688     setOperationAction(ISD::SUB , VT, Expand);
689     setOperationAction(ISD::FADD, VT, Expand);
690     setOperationAction(ISD::FNEG, VT, Expand);
691     setOperationAction(ISD::FSUB, VT, Expand);
692     setOperationAction(ISD::MUL , VT, Expand);
693     setOperationAction(ISD::FMUL, VT, Expand);
694     setOperationAction(ISD::SDIV, VT, Expand);
695     setOperationAction(ISD::UDIV, VT, Expand);
696     setOperationAction(ISD::FDIV, VT, Expand);
697     setOperationAction(ISD::SREM, VT, Expand);
698     setOperationAction(ISD::UREM, VT, Expand);
699     setOperationAction(ISD::LOAD, VT, Expand);
700     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
701     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
702     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
703     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
704     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
705     setOperationAction(ISD::FABS, VT, Expand);
706     setOperationAction(ISD::FSIN, VT, Expand);
707     setOperationAction(ISD::FSINCOS, VT, Expand);
708     setOperationAction(ISD::FCOS, VT, Expand);
709     setOperationAction(ISD::FSINCOS, VT, Expand);
710     setOperationAction(ISD::FREM, VT, Expand);
711     setOperationAction(ISD::FMA,  VT, Expand);
712     setOperationAction(ISD::FPOWI, VT, Expand);
713     setOperationAction(ISD::FSQRT, VT, Expand);
714     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
715     setOperationAction(ISD::FFLOOR, VT, Expand);
716     setOperationAction(ISD::FCEIL, VT, Expand);
717     setOperationAction(ISD::FTRUNC, VT, Expand);
718     setOperationAction(ISD::FRINT, VT, Expand);
719     setOperationAction(ISD::FNEARBYINT, VT, Expand);
720     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
721     setOperationAction(ISD::MULHS, VT, Expand);
722     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
723     setOperationAction(ISD::MULHU, VT, Expand);
724     setOperationAction(ISD::SDIVREM, VT, Expand);
725     setOperationAction(ISD::UDIVREM, VT, Expand);
726     setOperationAction(ISD::FPOW, VT, Expand);
727     setOperationAction(ISD::CTPOP, VT, Expand);
728     setOperationAction(ISD::CTTZ, VT, Expand);
729     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
730     setOperationAction(ISD::CTLZ, VT, Expand);
731     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
732     setOperationAction(ISD::SHL, VT, Expand);
733     setOperationAction(ISD::SRA, VT, Expand);
734     setOperationAction(ISD::SRL, VT, Expand);
735     setOperationAction(ISD::ROTL, VT, Expand);
736     setOperationAction(ISD::ROTR, VT, Expand);
737     setOperationAction(ISD::BSWAP, VT, Expand);
738     setOperationAction(ISD::SETCC, VT, Expand);
739     setOperationAction(ISD::FLOG, VT, Expand);
740     setOperationAction(ISD::FLOG2, VT, Expand);
741     setOperationAction(ISD::FLOG10, VT, Expand);
742     setOperationAction(ISD::FEXP, VT, Expand);
743     setOperationAction(ISD::FEXP2, VT, Expand);
744     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
745     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
746     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
747     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
748     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
749     setOperationAction(ISD::TRUNCATE, VT, Expand);
750     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
751     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
752     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
753     setOperationAction(ISD::VSELECT, VT, Expand);
754     setOperationAction(ISD::SELECT_CC, VT, Expand);
755     for (MVT InnerVT : MVT::vector_valuetypes()) {
756       setTruncStoreAction(InnerVT, VT, Expand);
757
758       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
759       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
760
761       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
762       // types, we have to deal with them whether we ask for Expansion or not.
763       // Setting Expand causes its own optimisation problems though, so leave
764       // them legal.
765       if (VT.getVectorElementType() == MVT::i1)
766         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
767
768       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
769       // split/scalarized right now.
770       if (VT.getVectorElementType() == MVT::f16)
771         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
772     }
773   }
774
775   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
776   // with -msoft-float, disable use of MMX as well.
777   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
778     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
779     // No operations on x86mmx supported, everything uses intrinsics.
780   }
781
782   // MMX-sized vectors (other than x86mmx) are expected to be expanded
783   // into smaller operations.
784   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
785     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
786     setOperationAction(ISD::AND,                MMXTy,      Expand);
787     setOperationAction(ISD::OR,                 MMXTy,      Expand);
788     setOperationAction(ISD::XOR,                MMXTy,      Expand);
789     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
790     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
791     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
792   }
793   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
794
795   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
796     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
797
798     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
801     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
802     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
803     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
804     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
805     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
806     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
807     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
808     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
809     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
810     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
811     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
812   }
813
814   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
815     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
816
817     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
818     // registers cannot be used even for integer operations.
819     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
820     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
821     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
822     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
823
824     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
825     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
826     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
827     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
828     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
829     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
830     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
831     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
832     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
833     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
834     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
835     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
836     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
837     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
838     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
839     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
840     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
841     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
842     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
843     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
844     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
845     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
846     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
847
848     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
849     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
850     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
851     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
852
853     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
854     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
855     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
856     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
857
858     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
859     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
860     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
861     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
862     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
863
864     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
865     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
866     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
867     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
868
869     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
870     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
871     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
872     // ISD::CTTZ v2i64 - scalarization is faster.
873     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
874     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
875     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
876     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
877
878     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
879     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
880       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
881       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
882       setOperationAction(ISD::VSELECT,            VT, Custom);
883       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
884     }
885
886     // We support custom legalizing of sext and anyext loads for specific
887     // memory vector types which we can load as a scalar (or sequence of
888     // scalars) and extend in-register to a legal 128-bit vector type. For sext
889     // loads these must work with a single scalar load.
890     for (MVT VT : MVT::integer_vector_valuetypes()) {
891       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
892       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
893       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
894       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
895       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
896       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
897       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
898       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
899       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
900     }
901
902     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
903     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
904     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
905     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
906     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
907     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
908     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
909     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
910
911     if (Subtarget->is64Bit()) {
912       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
913       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
914     }
915
916     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
917     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
918       setOperationAction(ISD::AND,    VT, Promote);
919       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
920       setOperationAction(ISD::OR,     VT, Promote);
921       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
922       setOperationAction(ISD::XOR,    VT, Promote);
923       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
924       setOperationAction(ISD::LOAD,   VT, Promote);
925       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
926       setOperationAction(ISD::SELECT, VT, Promote);
927       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
928     }
929
930     // Custom lower v2i64 and v2f64 selects.
931     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
932     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
933     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
934     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
935
936     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
937     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
938
939     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
940
941     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
942     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
943     // As there is no 64-bit GPR available, we need build a special custom
944     // sequence to convert from v2i32 to v2f32.
945     if (!Subtarget->is64Bit())
946       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
947
948     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
949     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
950
951     for (MVT VT : MVT::fp_vector_valuetypes())
952       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
953
954     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
955     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
956     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
957   }
958
959   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
960     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
961       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
962       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
963       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
964       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
965       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
966     }
967
968     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
969     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
970     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
971     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
972     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
973     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
974     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
975     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
976
977     // FIXME: Do we need to handle scalar-to-vector here?
978     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
979
980     // We directly match byte blends in the backend as they match the VSELECT
981     // condition form.
982     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
983
984     // SSE41 brings specific instructions for doing vector sign extend even in
985     // cases where we don't have SRA.
986     for (MVT VT : MVT::integer_vector_valuetypes()) {
987       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
988       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
989       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
990     }
991
992     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
993     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
994     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
995     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
996     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
997     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
998     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
999
1000     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1001     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1002     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1003     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1004     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1005     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1006
1007     // i8 and i16 vectors are custom because the source register and source
1008     // source memory operand types are not the same width.  f32 vectors are
1009     // custom since the immediate controlling the insert encodes additional
1010     // information.
1011     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1012     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1013     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1014     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1015
1016     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1017     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1018     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1019     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1020
1021     // FIXME: these should be Legal, but that's only for the case where
1022     // the index is constant.  For now custom expand to deal with that.
1023     if (Subtarget->is64Bit()) {
1024       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1025       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1026     }
1027   }
1028
1029   if (Subtarget->hasSSE2()) {
1030     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1031     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1032     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1033
1034     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1035     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1036
1037     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1038     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1039
1040     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1041     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1042
1043     // In the customized shift lowering, the legal cases in AVX2 will be
1044     // recognized.
1045     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1046     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1047
1048     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1049     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1050
1051     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1052     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1053   }
1054
1055   if (Subtarget->hasXOP()) {
1056     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1057     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1058     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1059     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1060     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1061     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1062     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1063     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1064   }
1065
1066   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1067     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1068     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1069     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1070     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1071     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1072     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1073
1074     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1075     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1076     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1077
1078     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1079     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1080     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1081     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1082     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1083     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1084     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1085     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1086     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1087     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1088     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1089     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1090
1091     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1092     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1093     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1094     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1095     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1096     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1097     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1098     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1099     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1100     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1101     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1102     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1103
1104     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1105     // even though v8i16 is a legal type.
1106     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1107     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1108     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1109
1110     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1111     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1112     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1113
1114     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1115     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1116
1117     for (MVT VT : MVT::fp_vector_valuetypes())
1118       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1119
1120     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1121     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1122
1123     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1124     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1125
1126     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1127     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1128
1129     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1130     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1131     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1132     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1133
1134     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1135     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1136     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1137
1138     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1139     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1140     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1141     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1142     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1143     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1144     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1145     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1146     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1147     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1148     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1149     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1150
1151     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1152     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1153     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1154     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1155
1156     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1157     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1158     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1159     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1160     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1161     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1162     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1163     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1164
1165     if (Subtarget->hasAnyFMA()) {
1166       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1167       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1168       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1169       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1170       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1171       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1172     }
1173
1174     if (Subtarget->hasInt256()) {
1175       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1176       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1177       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1178       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1179
1180       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1181       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1182       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1183       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1184
1185       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1186       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1187       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1188       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1189
1190       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1191       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1192       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1193       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1194
1195       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1196       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1197       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1198       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1199       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1200       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1201       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1202       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1203       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1204       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1205       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1206       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1207
1208       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1209       // when we have a 256bit-wide blend with immediate.
1210       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1211
1212       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1213       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1214       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1215       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1216       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1217       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1218       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1219
1220       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1221       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1222       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1223       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1224       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1225       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1226     } else {
1227       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1228       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1229       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1230       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1231
1232       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1233       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1234       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1235       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1236
1237       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1238       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1239       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1240       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1241
1242       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1243       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1244       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1245       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1246       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1247       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1248       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1249       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1250       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1251       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1252       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1253       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1254     }
1255
1256     // In the customized shift lowering, the legal cases in AVX2 will be
1257     // recognized.
1258     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1259     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1260
1261     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1262     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1263
1264     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1265     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1266
1267     // Custom lower several nodes for 256-bit types.
1268     for (MVT VT : MVT::vector_valuetypes()) {
1269       if (VT.getScalarSizeInBits() >= 32) {
1270         setOperationAction(ISD::MLOAD,  VT, Legal);
1271         setOperationAction(ISD::MSTORE, VT, Legal);
1272       }
1273       // Extract subvector is special because the value type
1274       // (result) is 128-bit but the source is 256-bit wide.
1275       if (VT.is128BitVector()) {
1276         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1277       }
1278       // Do not attempt to custom lower other non-256-bit vectors
1279       if (!VT.is256BitVector())
1280         continue;
1281
1282       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1283       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1284       setOperationAction(ISD::VSELECT,            VT, Custom);
1285       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1286       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1287       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1288       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1289       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1290     }
1291
1292     if (Subtarget->hasInt256())
1293       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1294
1295     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1296     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1297       setOperationAction(ISD::AND,    VT, Promote);
1298       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1299       setOperationAction(ISD::OR,     VT, Promote);
1300       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1301       setOperationAction(ISD::XOR,    VT, Promote);
1302       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1303       setOperationAction(ISD::LOAD,   VT, Promote);
1304       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1305       setOperationAction(ISD::SELECT, VT, Promote);
1306       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1307     }
1308   }
1309
1310   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1311     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1312     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1313     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1314     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1315
1316     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1317     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1318     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1319
1320     for (MVT VT : MVT::fp_vector_valuetypes())
1321       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1322
1323     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1324     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1325     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1326     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1327     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1328     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1329     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1330     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1331     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1332     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1333     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1334     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1335
1336     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1337     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1338     setOperationAction(ISD::SETCCE,             MVT::i1,    Custom);
1339     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1340     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1341     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1342     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1343     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1344     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1345     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1346     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1347     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1348     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1349     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1350     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1351
1352     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1353     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1354     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1355     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1356     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1357     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1358     setOperationAction(ISD::FABS,               MVT::v16f32, Custom);
1359
1360     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1361     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1362     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1363     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1364     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1365     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1366     setOperationAction(ISD::FABS,               MVT::v8f64, Custom);
1367     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1368     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1369
1370     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1371     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1372     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1373     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1374     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1375     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1376     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1377     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1378     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1379     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1380     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1381     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1382     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1383     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1384     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1385     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1386
1387     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1388     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1389     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1390     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1391     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1392     if (Subtarget->hasVLX()){
1393       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1394       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1395       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1396       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1397       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1398
1399       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1400       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1401       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1402       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1403       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1404     } else {
1405       setOperationAction(ISD::MLOAD,    MVT::v8i32, Custom);
1406       setOperationAction(ISD::MLOAD,    MVT::v8f32, Custom);
1407       setOperationAction(ISD::MSTORE,   MVT::v8i32, Custom);
1408       setOperationAction(ISD::MSTORE,   MVT::v8f32, Custom);
1409     }
1410     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1411     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1412     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1413     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1414     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1415     if (Subtarget->hasDQI()) {
1416       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1417       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1418
1419       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1420       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1421       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1422       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1423       if (Subtarget->hasVLX()) {
1424         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1425         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1426         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1427         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1428         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1429         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1430         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1431         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1432       }
1433     }
1434     if (Subtarget->hasVLX()) {
1435       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1436       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1437       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1438       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1439       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1440       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1441       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1442       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1443     }
1444     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1445     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1446     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1447     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1448     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1449     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1450     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1451     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1452     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1453     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1454     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1455     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1456     if (Subtarget->hasDQI()) {
1457       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1458       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1459     }
1460     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1461     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1462     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1463     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1464     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1465     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1466     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1467     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1468     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1469     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1470
1471     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1472     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1473     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1474     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1475     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1,   Custom);
1476
1477     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1478     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1479
1480     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1481
1482     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1483     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1484     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v16i1, Custom);
1485     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1486     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1487     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1488     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1489     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1490     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1491     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1492     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1493     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1494
1495     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1496     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1497     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1498     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1499     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1500     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1501     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1502     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1503
1504     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1505     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1506
1507     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1508     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1509
1510     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1511
1512     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1513     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1514
1515     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1516     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1517
1518     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1519     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1520
1521     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1522     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1523     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1524     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1525     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1526     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1527
1528     if (Subtarget->hasCDI()) {
1529       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1530       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1531       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Expand);
1532       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Expand);
1533
1534       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1535       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1536       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1537       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1538       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Expand);
1539       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Expand);
1540       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Expand);
1541       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Expand);
1542
1543       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1544       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1545
1546       if (Subtarget->hasVLX()) {
1547         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1548         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1549         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1550         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1551         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Expand);
1552         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Expand);
1553         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Expand);
1554         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Expand);
1555
1556         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1557         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1558         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1559         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1560       } else {
1561         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1562         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1563         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1564         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1565         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Expand);
1566         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Expand);
1567         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Expand);
1568         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Expand);
1569       }
1570     } // Subtarget->hasCDI()
1571
1572     if (Subtarget->hasDQI()) {
1573       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1574       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1575       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1576     }
1577     // Custom lower several nodes.
1578     for (MVT VT : MVT::vector_valuetypes()) {
1579       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1580       if (EltSize == 1) {
1581         setOperationAction(ISD::AND, VT, Legal);
1582         setOperationAction(ISD::OR,  VT, Legal);
1583         setOperationAction(ISD::XOR,  VT, Legal);
1584       }
1585       if ((VT.is128BitVector() || VT.is256BitVector()) && EltSize >= 32) {
1586         setOperationAction(ISD::MGATHER,  VT, Custom);
1587         setOperationAction(ISD::MSCATTER, VT, Custom);
1588       }
1589       // Extract subvector is special because the value type
1590       // (result) is 256/128-bit but the source is 512-bit wide.
1591       if (VT.is128BitVector() || VT.is256BitVector()) {
1592         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1593       }
1594       if (VT.getVectorElementType() == MVT::i1)
1595         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1596
1597       // Do not attempt to custom lower other non-512-bit vectors
1598       if (!VT.is512BitVector())
1599         continue;
1600
1601       if (EltSize >= 32) {
1602         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1603         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1604         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1605         setOperationAction(ISD::VSELECT,             VT, Legal);
1606         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1607         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1608         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1609         setOperationAction(ISD::MLOAD,               VT, Legal);
1610         setOperationAction(ISD::MSTORE,              VT, Legal);
1611         setOperationAction(ISD::MGATHER,  VT, Legal);
1612         setOperationAction(ISD::MSCATTER, VT, Custom);
1613       }
1614     }
1615     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1616       setOperationAction(ISD::SELECT, VT, Promote);
1617       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1618     }
1619   }// has  AVX-512
1620
1621   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1622     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1623     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1624
1625     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1626     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1627
1628     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1629     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1630     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1631     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1632     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1633     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1634     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1635     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1636     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1637     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1638     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1639     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1640     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1641     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1642     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1643     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1644     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1645     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1646     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1647     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1648     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1649     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1650     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1651     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1652     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1653     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1654     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1655     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1656     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1657     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1658     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1659     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1660     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1661     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1662     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1663     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1664     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1665     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1666     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1667     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1668     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1669     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1670
1671     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1672     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1673     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1674     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1675     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1676     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1677     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1678     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1679
1680     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1681     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1682     if (Subtarget->hasVLX())
1683       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1684
1685     if (Subtarget->hasCDI()) {
1686       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1687       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1688       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Expand);
1689       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Expand);
1690     }
1691
1692     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1693       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1694       setOperationAction(ISD::VSELECT,             VT, Legal);
1695       setOperationAction(ISD::SRL,                 VT, Custom);
1696       setOperationAction(ISD::SHL,                 VT, Custom);
1697       setOperationAction(ISD::SRA,                 VT, Custom);
1698
1699       setOperationAction(ISD::AND,    VT, Promote);
1700       AddPromotedToType (ISD::AND,    VT, MVT::v8i64);
1701       setOperationAction(ISD::OR,     VT, Promote);
1702       AddPromotedToType (ISD::OR,     VT, MVT::v8i64);
1703       setOperationAction(ISD::XOR,    VT, Promote);
1704       AddPromotedToType (ISD::XOR,    VT, MVT::v8i64);
1705     }
1706   }
1707
1708   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1709     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1710     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1711
1712     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1713     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1714     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1715     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1716     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1717     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1718     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1719     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1720     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1721     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1722     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1723     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1724
1725     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1726     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1727     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1728     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1729     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1730     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1731     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1732     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1733
1734     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1735     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1736     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1737     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1738     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1739     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1740     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1741     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1742   }
1743
1744   // We want to custom lower some of our intrinsics.
1745   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1746   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1747   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1748   if (!Subtarget->is64Bit()) {
1749     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1750     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1751   }
1752
1753   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1754   // handle type legalization for these operations here.
1755   //
1756   // FIXME: We really should do custom legalization for addition and
1757   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1758   // than generic legalization for 64-bit multiplication-with-overflow, though.
1759   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1760     if (VT == MVT::i64 && !Subtarget->is64Bit())
1761       continue;
1762     // Add/Sub/Mul with overflow operations are custom lowered.
1763     setOperationAction(ISD::SADDO, VT, Custom);
1764     setOperationAction(ISD::UADDO, VT, Custom);
1765     setOperationAction(ISD::SSUBO, VT, Custom);
1766     setOperationAction(ISD::USUBO, VT, Custom);
1767     setOperationAction(ISD::SMULO, VT, Custom);
1768     setOperationAction(ISD::UMULO, VT, Custom);
1769   }
1770
1771   if (!Subtarget->is64Bit()) {
1772     // These libcalls are not available in 32-bit.
1773     setLibcallName(RTLIB::SHL_I128, nullptr);
1774     setLibcallName(RTLIB::SRL_I128, nullptr);
1775     setLibcallName(RTLIB::SRA_I128, nullptr);
1776   }
1777
1778   // Combine sin / cos into one node or libcall if possible.
1779   if (Subtarget->hasSinCos()) {
1780     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1781     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1782     if (Subtarget->isTargetDarwin()) {
1783       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1784       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1785       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1786       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1787     }
1788   }
1789
1790   if (Subtarget->isTargetWin64()) {
1791     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1792     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1793     setOperationAction(ISD::SREM, MVT::i128, Custom);
1794     setOperationAction(ISD::UREM, MVT::i128, Custom);
1795     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1796     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1797   }
1798
1799   // We have target-specific dag combine patterns for the following nodes:
1800   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1801   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1802   setTargetDAGCombine(ISD::BITCAST);
1803   setTargetDAGCombine(ISD::VSELECT);
1804   setTargetDAGCombine(ISD::SELECT);
1805   setTargetDAGCombine(ISD::SHL);
1806   setTargetDAGCombine(ISD::SRA);
1807   setTargetDAGCombine(ISD::SRL);
1808   setTargetDAGCombine(ISD::OR);
1809   setTargetDAGCombine(ISD::AND);
1810   setTargetDAGCombine(ISD::ADD);
1811   setTargetDAGCombine(ISD::FADD);
1812   setTargetDAGCombine(ISD::FSUB);
1813   setTargetDAGCombine(ISD::FNEG);
1814   setTargetDAGCombine(ISD::FMA);
1815   setTargetDAGCombine(ISD::FMINNUM);
1816   setTargetDAGCombine(ISD::FMAXNUM);
1817   setTargetDAGCombine(ISD::SUB);
1818   setTargetDAGCombine(ISD::LOAD);
1819   setTargetDAGCombine(ISD::MLOAD);
1820   setTargetDAGCombine(ISD::STORE);
1821   setTargetDAGCombine(ISD::MSTORE);
1822   setTargetDAGCombine(ISD::TRUNCATE);
1823   setTargetDAGCombine(ISD::ZERO_EXTEND);
1824   setTargetDAGCombine(ISD::ANY_EXTEND);
1825   setTargetDAGCombine(ISD::SIGN_EXTEND);
1826   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1827   setTargetDAGCombine(ISD::SINT_TO_FP);
1828   setTargetDAGCombine(ISD::UINT_TO_FP);
1829   setTargetDAGCombine(ISD::SETCC);
1830   setTargetDAGCombine(ISD::BUILD_VECTOR);
1831   setTargetDAGCombine(ISD::MUL);
1832   setTargetDAGCombine(ISD::XOR);
1833   setTargetDAGCombine(ISD::MSCATTER);
1834   setTargetDAGCombine(ISD::MGATHER);
1835
1836   computeRegisterProperties(Subtarget->getRegisterInfo());
1837
1838   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1839   MaxStoresPerMemsetOptSize = 8;
1840   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1841   MaxStoresPerMemcpyOptSize = 4;
1842   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1843   MaxStoresPerMemmoveOptSize = 4;
1844   setPrefLoopAlignment(4); // 2^4 bytes.
1845
1846   // A predictable cmov does not hurt on an in-order CPU.
1847   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1848   PredictableSelectIsExpensive = !Subtarget->isAtom();
1849   EnableExtLdPromotion = true;
1850   setPrefFunctionAlignment(4); // 2^4 bytes.
1851
1852   verifyIntrinsicTables();
1853 }
1854
1855 // This has so far only been implemented for 64-bit MachO.
1856 bool X86TargetLowering::useLoadStackGuardNode() const {
1857   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1858 }
1859
1860 TargetLoweringBase::LegalizeTypeAction
1861 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1862   if (ExperimentalVectorWideningLegalization &&
1863       VT.getVectorNumElements() != 1 &&
1864       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1865     return TypeWidenVector;
1866
1867   return TargetLoweringBase::getPreferredVectorAction(VT);
1868 }
1869
1870 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1871                                           EVT VT) const {
1872   if (!VT.isVector())
1873     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1874
1875   if (VT.isSimple()) {
1876     MVT VVT = VT.getSimpleVT();
1877     const unsigned NumElts = VVT.getVectorNumElements();
1878     const MVT EltVT = VVT.getVectorElementType();
1879     if (VVT.is512BitVector()) {
1880       if (Subtarget->hasAVX512())
1881         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1882             EltVT == MVT::f32 || EltVT == MVT::f64)
1883           switch(NumElts) {
1884           case  8: return MVT::v8i1;
1885           case 16: return MVT::v16i1;
1886         }
1887       if (Subtarget->hasBWI())
1888         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1889           switch(NumElts) {
1890           case 32: return MVT::v32i1;
1891           case 64: return MVT::v64i1;
1892         }
1893     }
1894
1895     if (VVT.is256BitVector() || VVT.is128BitVector()) {
1896       if (Subtarget->hasVLX())
1897         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1898             EltVT == MVT::f32 || EltVT == MVT::f64)
1899           switch(NumElts) {
1900           case 2: return MVT::v2i1;
1901           case 4: return MVT::v4i1;
1902           case 8: return MVT::v8i1;
1903         }
1904       if (Subtarget->hasBWI() && Subtarget->hasVLX())
1905         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1906           switch(NumElts) {
1907           case  8: return MVT::v8i1;
1908           case 16: return MVT::v16i1;
1909           case 32: return MVT::v32i1;
1910         }
1911     }
1912   }
1913
1914   return VT.changeVectorElementTypeToInteger();
1915 }
1916
1917 /// Helper for getByValTypeAlignment to determine
1918 /// the desired ByVal argument alignment.
1919 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1920   if (MaxAlign == 16)
1921     return;
1922   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1923     if (VTy->getBitWidth() == 128)
1924       MaxAlign = 16;
1925   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1926     unsigned EltAlign = 0;
1927     getMaxByValAlign(ATy->getElementType(), EltAlign);
1928     if (EltAlign > MaxAlign)
1929       MaxAlign = EltAlign;
1930   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1931     for (auto *EltTy : STy->elements()) {
1932       unsigned EltAlign = 0;
1933       getMaxByValAlign(EltTy, EltAlign);
1934       if (EltAlign > MaxAlign)
1935         MaxAlign = EltAlign;
1936       if (MaxAlign == 16)
1937         break;
1938     }
1939   }
1940 }
1941
1942 /// Return the desired alignment for ByVal aggregate
1943 /// function arguments in the caller parameter area. For X86, aggregates
1944 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1945 /// are at 4-byte boundaries.
1946 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1947                                                   const DataLayout &DL) const {
1948   if (Subtarget->is64Bit()) {
1949     // Max of 8 and alignment of type.
1950     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1951     if (TyAlign > 8)
1952       return TyAlign;
1953     return 8;
1954   }
1955
1956   unsigned Align = 4;
1957   if (Subtarget->hasSSE1())
1958     getMaxByValAlign(Ty, Align);
1959   return Align;
1960 }
1961
1962 /// Returns the target specific optimal type for load
1963 /// and store operations as a result of memset, memcpy, and memmove
1964 /// lowering. If DstAlign is zero that means it's safe to destination
1965 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1966 /// means there isn't a need to check it against alignment requirement,
1967 /// probably because the source does not need to be loaded. If 'IsMemset' is
1968 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1969 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1970 /// source is constant so it does not need to be loaded.
1971 /// It returns EVT::Other if the type should be determined using generic
1972 /// target-independent logic.
1973 EVT
1974 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1975                                        unsigned DstAlign, unsigned SrcAlign,
1976                                        bool IsMemset, bool ZeroMemset,
1977                                        bool MemcpyStrSrc,
1978                                        MachineFunction &MF) const {
1979   const Function *F = MF.getFunction();
1980   if ((!IsMemset || ZeroMemset) &&
1981       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1982     if (Size >= 16 &&
1983         (!Subtarget->isUnalignedMem16Slow() ||
1984          ((DstAlign == 0 || DstAlign >= 16) &&
1985           (SrcAlign == 0 || SrcAlign >= 16)))) {
1986       if (Size >= 32) {
1987         // FIXME: Check if unaligned 32-byte accesses are slow.
1988         if (Subtarget->hasInt256())
1989           return MVT::v8i32;
1990         if (Subtarget->hasFp256())
1991           return MVT::v8f32;
1992       }
1993       if (Subtarget->hasSSE2())
1994         return MVT::v4i32;
1995       if (Subtarget->hasSSE1())
1996         return MVT::v4f32;
1997     } else if (!MemcpyStrSrc && Size >= 8 &&
1998                !Subtarget->is64Bit() &&
1999                Subtarget->hasSSE2()) {
2000       // Do not use f64 to lower memcpy if source is string constant. It's
2001       // better to use i32 to avoid the loads.
2002       return MVT::f64;
2003     }
2004   }
2005   // This is a compromise. If we reach here, unaligned accesses may be slow on
2006   // this target. However, creating smaller, aligned accesses could be even
2007   // slower and would certainly be a lot more code.
2008   if (Subtarget->is64Bit() && Size >= 8)
2009     return MVT::i64;
2010   return MVT::i32;
2011 }
2012
2013 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2014   if (VT == MVT::f32)
2015     return X86ScalarSSEf32;
2016   else if (VT == MVT::f64)
2017     return X86ScalarSSEf64;
2018   return true;
2019 }
2020
2021 bool
2022 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2023                                                   unsigned,
2024                                                   unsigned,
2025                                                   bool *Fast) const {
2026   if (Fast) {
2027     switch (VT.getSizeInBits()) {
2028     default:
2029       // 8-byte and under are always assumed to be fast.
2030       *Fast = true;
2031       break;
2032     case 128:
2033       *Fast = !Subtarget->isUnalignedMem16Slow();
2034       break;
2035     case 256:
2036       *Fast = !Subtarget->isUnalignedMem32Slow();
2037       break;
2038     // TODO: What about AVX-512 (512-bit) accesses?
2039     }
2040   }
2041   // Misaligned accesses of any size are always allowed.
2042   return true;
2043 }
2044
2045 /// Return the entry encoding for a jump table in the
2046 /// current function.  The returned value is a member of the
2047 /// MachineJumpTableInfo::JTEntryKind enum.
2048 unsigned X86TargetLowering::getJumpTableEncoding() const {
2049   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2050   // symbol.
2051   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2052       Subtarget->isPICStyleGOT())
2053     return MachineJumpTableInfo::EK_Custom32;
2054
2055   // Otherwise, use the normal jump table encoding heuristics.
2056   return TargetLowering::getJumpTableEncoding();
2057 }
2058
2059 bool X86TargetLowering::useSoftFloat() const {
2060   return Subtarget->useSoftFloat();
2061 }
2062
2063 const MCExpr *
2064 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2065                                              const MachineBasicBlock *MBB,
2066                                              unsigned uid,MCContext &Ctx) const{
2067   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2068          Subtarget->isPICStyleGOT());
2069   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2070   // entries.
2071   return MCSymbolRefExpr::create(MBB->getSymbol(),
2072                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2073 }
2074
2075 /// Returns relocation base for the given PIC jumptable.
2076 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2077                                                     SelectionDAG &DAG) const {
2078   if (!Subtarget->is64Bit())
2079     // This doesn't have SDLoc associated with it, but is not really the
2080     // same as a Register.
2081     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2082                        getPointerTy(DAG.getDataLayout()));
2083   return Table;
2084 }
2085
2086 /// This returns the relocation base for the given PIC jumptable,
2087 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2088 const MCExpr *X86TargetLowering::
2089 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2090                              MCContext &Ctx) const {
2091   // X86-64 uses RIP relative addressing based on the jump table label.
2092   if (Subtarget->isPICStyleRIPRel())
2093     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2094
2095   // Otherwise, the reference is relative to the PIC base.
2096   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2097 }
2098
2099 std::pair<const TargetRegisterClass *, uint8_t>
2100 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2101                                            MVT VT) const {
2102   const TargetRegisterClass *RRC = nullptr;
2103   uint8_t Cost = 1;
2104   switch (VT.SimpleTy) {
2105   default:
2106     return TargetLowering::findRepresentativeClass(TRI, VT);
2107   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2108     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2109     break;
2110   case MVT::x86mmx:
2111     RRC = &X86::VR64RegClass;
2112     break;
2113   case MVT::f32: case MVT::f64:
2114   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2115   case MVT::v4f32: case MVT::v2f64:
2116   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2117   case MVT::v4f64:
2118     RRC = &X86::VR128RegClass;
2119     break;
2120   }
2121   return std::make_pair(RRC, Cost);
2122 }
2123
2124 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2125                                                unsigned &Offset) const {
2126   if (!Subtarget->isTargetLinux())
2127     return false;
2128
2129   if (Subtarget->is64Bit()) {
2130     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2131     Offset = 0x28;
2132     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2133       AddressSpace = 256;
2134     else
2135       AddressSpace = 257;
2136   } else {
2137     // %gs:0x14 on i386
2138     Offset = 0x14;
2139     AddressSpace = 256;
2140   }
2141   return true;
2142 }
2143
2144 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2145   if (!Subtarget->isTargetAndroid())
2146     return TargetLowering::getSafeStackPointerLocation(IRB);
2147
2148   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2149   // definition of TLS_SLOT_SAFESTACK in
2150   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2151   unsigned AddressSpace, Offset;
2152   if (Subtarget->is64Bit()) {
2153     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2154     Offset = 0x48;
2155     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2156       AddressSpace = 256;
2157     else
2158       AddressSpace = 257;
2159   } else {
2160     // %gs:0x24 on i386
2161     Offset = 0x24;
2162     AddressSpace = 256;
2163   }
2164
2165   return ConstantExpr::getIntToPtr(
2166       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2167       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2168 }
2169
2170 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2171                                             unsigned DestAS) const {
2172   assert(SrcAS != DestAS && "Expected different address spaces!");
2173
2174   return SrcAS < 256 && DestAS < 256;
2175 }
2176
2177 //===----------------------------------------------------------------------===//
2178 //               Return Value Calling Convention Implementation
2179 //===----------------------------------------------------------------------===//
2180
2181 #include "X86GenCallingConv.inc"
2182
2183 bool X86TargetLowering::CanLowerReturn(
2184     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2185     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2186   SmallVector<CCValAssign, 16> RVLocs;
2187   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2188   return CCInfo.CheckReturn(Outs, RetCC_X86);
2189 }
2190
2191 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2192   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2193   return ScratchRegs;
2194 }
2195
2196 SDValue
2197 X86TargetLowering::LowerReturn(SDValue Chain,
2198                                CallingConv::ID CallConv, bool isVarArg,
2199                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2200                                const SmallVectorImpl<SDValue> &OutVals,
2201                                SDLoc dl, SelectionDAG &DAG) const {
2202   MachineFunction &MF = DAG.getMachineFunction();
2203   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2204
2205   if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2206     report_fatal_error("X86 interrupts may not return any value");
2207
2208   SmallVector<CCValAssign, 16> RVLocs;
2209   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2210   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2211
2212   SDValue Flag;
2213   SmallVector<SDValue, 6> RetOps;
2214   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2215   // Operand #1 = Bytes To Pop
2216   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2217                    MVT::i16));
2218
2219   // Copy the result values into the output registers.
2220   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2221     CCValAssign &VA = RVLocs[i];
2222     assert(VA.isRegLoc() && "Can only return in registers!");
2223     SDValue ValToCopy = OutVals[i];
2224     EVT ValVT = ValToCopy.getValueType();
2225
2226     // Promote values to the appropriate types.
2227     if (VA.getLocInfo() == CCValAssign::SExt)
2228       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2229     else if (VA.getLocInfo() == CCValAssign::ZExt)
2230       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2231     else if (VA.getLocInfo() == CCValAssign::AExt) {
2232       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2233         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2234       else
2235         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2236     }
2237     else if (VA.getLocInfo() == CCValAssign::BCvt)
2238       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2239
2240     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2241            "Unexpected FP-extend for return value.");
2242
2243     // If this is x86-64, and we disabled SSE, we can't return FP values,
2244     // or SSE or MMX vectors.
2245     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2246          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2247           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2248       report_fatal_error("SSE register return with SSE disabled");
2249     }
2250     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2251     // llvm-gcc has never done it right and no one has noticed, so this
2252     // should be OK for now.
2253     if (ValVT == MVT::f64 &&
2254         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2255       report_fatal_error("SSE2 register return with SSE2 disabled");
2256
2257     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2258     // the RET instruction and handled by the FP Stackifier.
2259     if (VA.getLocReg() == X86::FP0 ||
2260         VA.getLocReg() == X86::FP1) {
2261       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2262       // change the value to the FP stack register class.
2263       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2264         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2265       RetOps.push_back(ValToCopy);
2266       // Don't emit a copytoreg.
2267       continue;
2268     }
2269
2270     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2271     // which is returned in RAX / RDX.
2272     if (Subtarget->is64Bit()) {
2273       if (ValVT == MVT::x86mmx) {
2274         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2275           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2276           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2277                                   ValToCopy);
2278           // If we don't have SSE2 available, convert to v4f32 so the generated
2279           // register is legal.
2280           if (!Subtarget->hasSSE2())
2281             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2282         }
2283       }
2284     }
2285
2286     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2287     Flag = Chain.getValue(1);
2288     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2289   }
2290
2291   // All x86 ABIs require that for returning structs by value we copy
2292   // the sret argument into %rax/%eax (depending on ABI) for the return.
2293   // We saved the argument into a virtual register in the entry block,
2294   // so now we copy the value out and into %rax/%eax.
2295   //
2296   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2297   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2298   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2299   // either case FuncInfo->setSRetReturnReg() will have been called.
2300   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2301     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2302                                      getPointerTy(MF.getDataLayout()));
2303
2304     unsigned RetValReg
2305         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2306           X86::RAX : X86::EAX;
2307     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2308     Flag = Chain.getValue(1);
2309
2310     // RAX/EAX now acts like a return value.
2311     RetOps.push_back(
2312         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2313   }
2314
2315   const X86RegisterInfo *TRI = Subtarget->getRegisterInfo();
2316   const MCPhysReg *I =
2317       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2318   if (I) {
2319     for (; *I; ++I) {
2320       if (X86::GR64RegClass.contains(*I))
2321         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2322       else
2323         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2324     }
2325   }
2326
2327   RetOps[0] = Chain;  // Update chain.
2328
2329   // Add the flag if we have it.
2330   if (Flag.getNode())
2331     RetOps.push_back(Flag);
2332
2333   X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2334   if (CallConv == CallingConv::X86_INTR)
2335     opcode = X86ISD::IRET;
2336   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2337 }
2338
2339 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2340   if (N->getNumValues() != 1)
2341     return false;
2342   if (!N->hasNUsesOfValue(1, 0))
2343     return false;
2344
2345   SDValue TCChain = Chain;
2346   SDNode *Copy = *N->use_begin();
2347   if (Copy->getOpcode() == ISD::CopyToReg) {
2348     // If the copy has a glue operand, we conservatively assume it isn't safe to
2349     // perform a tail call.
2350     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2351       return false;
2352     TCChain = Copy->getOperand(0);
2353   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2354     return false;
2355
2356   bool HasRet = false;
2357   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2358        UI != UE; ++UI) {
2359     if (UI->getOpcode() != X86ISD::RET_FLAG)
2360       return false;
2361     // If we are returning more than one value, we can definitely
2362     // not make a tail call see PR19530
2363     if (UI->getNumOperands() > 4)
2364       return false;
2365     if (UI->getNumOperands() == 4 &&
2366         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2367       return false;
2368     HasRet = true;
2369   }
2370
2371   if (!HasRet)
2372     return false;
2373
2374   Chain = TCChain;
2375   return true;
2376 }
2377
2378 EVT
2379 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2380                                             ISD::NodeType ExtendKind) const {
2381   MVT ReturnMVT;
2382   // TODO: Is this also valid on 32-bit?
2383   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2384     ReturnMVT = MVT::i8;
2385   else
2386     ReturnMVT = MVT::i32;
2387
2388   EVT MinVT = getRegisterType(Context, ReturnMVT);
2389   return VT.bitsLT(MinVT) ? MinVT : VT;
2390 }
2391
2392 /// Lower the result values of a call into the
2393 /// appropriate copies out of appropriate physical registers.
2394 ///
2395 SDValue
2396 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2397                                    CallingConv::ID CallConv, bool isVarArg,
2398                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2399                                    SDLoc dl, SelectionDAG &DAG,
2400                                    SmallVectorImpl<SDValue> &InVals) const {
2401
2402   // Assign locations to each value returned by this call.
2403   SmallVector<CCValAssign, 16> RVLocs;
2404   bool Is64Bit = Subtarget->is64Bit();
2405   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2406                  *DAG.getContext());
2407   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2408
2409   // Copy all of the result registers out of their specified physreg.
2410   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2411     CCValAssign &VA = RVLocs[i];
2412     EVT CopyVT = VA.getLocVT();
2413
2414     // If this is x86-64, and we disabled SSE, we can't return FP values
2415     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2416         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2417       report_fatal_error("SSE register return with SSE disabled");
2418     }
2419
2420     // If we prefer to use the value in xmm registers, copy it out as f80 and
2421     // use a truncate to move it from fp stack reg to xmm reg.
2422     bool RoundAfterCopy = false;
2423     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2424         isScalarFPTypeInSSEReg(VA.getValVT())) {
2425       CopyVT = MVT::f80;
2426       RoundAfterCopy = (CopyVT != VA.getLocVT());
2427     }
2428
2429     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2430                                CopyVT, InFlag).getValue(1);
2431     SDValue Val = Chain.getValue(0);
2432
2433     if (RoundAfterCopy)
2434       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2435                         // This truncation won't change the value.
2436                         DAG.getIntPtrConstant(1, dl));
2437
2438     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2439       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2440
2441     InFlag = Chain.getValue(2);
2442     InVals.push_back(Val);
2443   }
2444
2445   return Chain;
2446 }
2447
2448 //===----------------------------------------------------------------------===//
2449 //                C & StdCall & Fast Calling Convention implementation
2450 //===----------------------------------------------------------------------===//
2451 //  StdCall calling convention seems to be standard for many Windows' API
2452 //  routines and around. It differs from C calling convention just a little:
2453 //  callee should clean up the stack, not caller. Symbols should be also
2454 //  decorated in some fancy way :) It doesn't support any vector arguments.
2455 //  For info on fast calling convention see Fast Calling Convention (tail call)
2456 //  implementation LowerX86_32FastCCCallTo.
2457
2458 /// CallIsStructReturn - Determines whether a call uses struct return
2459 /// semantics.
2460 enum StructReturnType {
2461   NotStructReturn,
2462   RegStructReturn,
2463   StackStructReturn
2464 };
2465 static StructReturnType
2466 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsMCU) {
2467   if (Outs.empty())
2468     return NotStructReturn;
2469
2470   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2471   if (!Flags.isSRet())
2472     return NotStructReturn;
2473   if (Flags.isInReg() || IsMCU)
2474     return RegStructReturn;
2475   return StackStructReturn;
2476 }
2477
2478 /// Determines whether a function uses struct return semantics.
2479 static StructReturnType
2480 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsMCU) {
2481   if (Ins.empty())
2482     return NotStructReturn;
2483
2484   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2485   if (!Flags.isSRet())
2486     return NotStructReturn;
2487   if (Flags.isInReg() || IsMCU)
2488     return RegStructReturn;
2489   return StackStructReturn;
2490 }
2491
2492 /// Make a copy of an aggregate at address specified by "Src" to address
2493 /// "Dst" with size and alignment information specified by the specific
2494 /// parameter attribute. The copy will be passed as a byval function parameter.
2495 static SDValue
2496 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2497                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2498                           SDLoc dl) {
2499   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2500
2501   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2502                        /*isVolatile*/false, /*AlwaysInline=*/true,
2503                        /*isTailCall*/false,
2504                        MachinePointerInfo(), MachinePointerInfo());
2505 }
2506
2507 /// Return true if the calling convention is one that we can guarantee TCO for.
2508 static bool canGuaranteeTCO(CallingConv::ID CC) {
2509   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2510           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2511 }
2512
2513 /// Return true if we might ever do TCO for calls with this calling convention.
2514 static bool mayTailCallThisCC(CallingConv::ID CC) {
2515   switch (CC) {
2516   // C calling conventions:
2517   case CallingConv::C:
2518   case CallingConv::X86_64_Win64:
2519   case CallingConv::X86_64_SysV:
2520   // Callee pop conventions:
2521   case CallingConv::X86_ThisCall:
2522   case CallingConv::X86_StdCall:
2523   case CallingConv::X86_VectorCall:
2524   case CallingConv::X86_FastCall:
2525     return true;
2526   default:
2527     return canGuaranteeTCO(CC);
2528   }
2529 }
2530
2531 /// Return true if the function is being made into a tailcall target by
2532 /// changing its ABI.
2533 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2534   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2535 }
2536
2537 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2538   auto Attr =
2539       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2540   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2541     return false;
2542
2543   CallSite CS(CI);
2544   CallingConv::ID CalleeCC = CS.getCallingConv();
2545   if (!mayTailCallThisCC(CalleeCC))
2546     return false;
2547
2548   return true;
2549 }
2550
2551 SDValue
2552 X86TargetLowering::LowerMemArgument(SDValue Chain,
2553                                     CallingConv::ID CallConv,
2554                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2555                                     SDLoc dl, SelectionDAG &DAG,
2556                                     const CCValAssign &VA,
2557                                     MachineFrameInfo *MFI,
2558                                     unsigned i) const {
2559   // Create the nodes corresponding to a load from this parameter slot.
2560   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2561   bool AlwaysUseMutable = shouldGuaranteeTCO(
2562       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2563   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2564   EVT ValVT;
2565
2566   // If value is passed by pointer we have address passed instead of the value
2567   // itself.
2568   bool ExtendedInMem = VA.isExtInLoc() &&
2569     VA.getValVT().getScalarType() == MVT::i1;
2570
2571   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2572     ValVT = VA.getLocVT();
2573   else
2574     ValVT = VA.getValVT();
2575
2576   // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2577   // taken by a return address.
2578   int Offset = 0;
2579   if (CallConv == CallingConv::X86_INTR) {
2580     const X86Subtarget& Subtarget =
2581         static_cast<const X86Subtarget&>(DAG.getSubtarget());
2582     // X86 interrupts may take one or two arguments.
2583     // On the stack there will be no return address as in regular call.
2584     // Offset of last argument need to be set to -4/-8 bytes.
2585     // Where offset of the first argument out of two, should be set to 0 bytes.
2586     Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2587   }
2588
2589   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2590   // changed with more analysis.
2591   // In case of tail call optimization mark all arguments mutable. Since they
2592   // could be overwritten by lowering of arguments in case of a tail call.
2593   if (Flags.isByVal()) {
2594     unsigned Bytes = Flags.getByValSize();
2595     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2596     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2597     // Adjust SP offset of interrupt parameter.
2598     if (CallConv == CallingConv::X86_INTR) {
2599       MFI->setObjectOffset(FI, Offset);
2600     }
2601     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2602   } else {
2603     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2604                                     VA.getLocMemOffset(), isImmutable);
2605     // Adjust SP offset of interrupt parameter.
2606     if (CallConv == CallingConv::X86_INTR) {
2607       MFI->setObjectOffset(FI, Offset);
2608     }
2609
2610     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2611     SDValue Val = DAG.getLoad(
2612         ValVT, dl, Chain, FIN,
2613         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2614         false, false, 0);
2615     return ExtendedInMem ?
2616       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2617   }
2618 }
2619
2620 // FIXME: Get this from tablegen.
2621 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2622                                                 const X86Subtarget *Subtarget) {
2623   assert(Subtarget->is64Bit());
2624
2625   if (Subtarget->isCallingConvWin64(CallConv)) {
2626     static const MCPhysReg GPR64ArgRegsWin64[] = {
2627       X86::RCX, X86::RDX, X86::R8,  X86::R9
2628     };
2629     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2630   }
2631
2632   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2633     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2634   };
2635   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2636 }
2637
2638 // FIXME: Get this from tablegen.
2639 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2640                                                 CallingConv::ID CallConv,
2641                                                 const X86Subtarget *Subtarget) {
2642   assert(Subtarget->is64Bit());
2643   if (Subtarget->isCallingConvWin64(CallConv)) {
2644     // The XMM registers which might contain var arg parameters are shadowed
2645     // in their paired GPR.  So we only need to save the GPR to their home
2646     // slots.
2647     // TODO: __vectorcall will change this.
2648     return None;
2649   }
2650
2651   const Function *Fn = MF.getFunction();
2652   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2653   bool isSoftFloat = Subtarget->useSoftFloat();
2654   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2655          "SSE register cannot be used when SSE is disabled!");
2656   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2657     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2658     // registers.
2659     return None;
2660
2661   static const MCPhysReg XMMArgRegs64Bit[] = {
2662     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2663     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2664   };
2665   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2666 }
2667
2668 SDValue X86TargetLowering::LowerFormalArguments(
2669     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2670     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2671     SmallVectorImpl<SDValue> &InVals) const {
2672   MachineFunction &MF = DAG.getMachineFunction();
2673   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2674   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2675
2676   const Function* Fn = MF.getFunction();
2677   if (Fn->hasExternalLinkage() &&
2678       Subtarget->isTargetCygMing() &&
2679       Fn->getName() == "main")
2680     FuncInfo->setForceFramePointer(true);
2681
2682   MachineFrameInfo *MFI = MF.getFrameInfo();
2683   bool Is64Bit = Subtarget->is64Bit();
2684   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2685
2686   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2687          "Var args not supported with calling convention fastcc, ghc or hipe");
2688
2689   if (CallConv == CallingConv::X86_INTR) {
2690     bool isLegal = Ins.size() == 1 ||
2691                    (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2692                                         (!Is64Bit && Ins[1].VT == MVT::i32)));
2693     if (!isLegal)
2694       report_fatal_error("X86 interrupts may take one or two arguments");
2695   }
2696
2697   // Assign locations to all of the incoming arguments.
2698   SmallVector<CCValAssign, 16> ArgLocs;
2699   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2700
2701   // Allocate shadow area for Win64
2702   if (IsWin64)
2703     CCInfo.AllocateStack(32, 8);
2704
2705   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2706
2707   unsigned LastVal = ~0U;
2708   SDValue ArgValue;
2709   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2710     CCValAssign &VA = ArgLocs[i];
2711     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2712     // places.
2713     assert(VA.getValNo() != LastVal &&
2714            "Don't support value assigned to multiple locs yet");
2715     (void)LastVal;
2716     LastVal = VA.getValNo();
2717
2718     if (VA.isRegLoc()) {
2719       EVT RegVT = VA.getLocVT();
2720       const TargetRegisterClass *RC;
2721       if (RegVT == MVT::i32)
2722         RC = &X86::GR32RegClass;
2723       else if (Is64Bit && RegVT == MVT::i64)
2724         RC = &X86::GR64RegClass;
2725       else if (RegVT == MVT::f32)
2726         RC = &X86::FR32RegClass;
2727       else if (RegVT == MVT::f64)
2728         RC = &X86::FR64RegClass;
2729       else if (RegVT == MVT::f128)
2730         RC = &X86::FR128RegClass;
2731       else if (RegVT.is512BitVector())
2732         RC = &X86::VR512RegClass;
2733       else if (RegVT.is256BitVector())
2734         RC = &X86::VR256RegClass;
2735       else if (RegVT.is128BitVector())
2736         RC = &X86::VR128RegClass;
2737       else if (RegVT == MVT::x86mmx)
2738         RC = &X86::VR64RegClass;
2739       else if (RegVT == MVT::i1)
2740         RC = &X86::VK1RegClass;
2741       else if (RegVT == MVT::v8i1)
2742         RC = &X86::VK8RegClass;
2743       else if (RegVT == MVT::v16i1)
2744         RC = &X86::VK16RegClass;
2745       else if (RegVT == MVT::v32i1)
2746         RC = &X86::VK32RegClass;
2747       else if (RegVT == MVT::v64i1)
2748         RC = &X86::VK64RegClass;
2749       else
2750         llvm_unreachable("Unknown argument type!");
2751
2752       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2753       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2754
2755       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2756       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2757       // right size.
2758       if (VA.getLocInfo() == CCValAssign::SExt)
2759         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2760                                DAG.getValueType(VA.getValVT()));
2761       else if (VA.getLocInfo() == CCValAssign::ZExt)
2762         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2763                                DAG.getValueType(VA.getValVT()));
2764       else if (VA.getLocInfo() == CCValAssign::BCvt)
2765         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2766
2767       if (VA.isExtInLoc()) {
2768         // Handle MMX values passed in XMM regs.
2769         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2770           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2771         else
2772           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2773       }
2774     } else {
2775       assert(VA.isMemLoc());
2776       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2777     }
2778
2779     // If value is passed via pointer - do a load.
2780     if (VA.getLocInfo() == CCValAssign::Indirect)
2781       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2782                              MachinePointerInfo(), false, false, false, 0);
2783
2784     InVals.push_back(ArgValue);
2785   }
2786
2787   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2788     // All x86 ABIs require that for returning structs by value we copy the
2789     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2790     // the argument into a virtual register so that we can access it from the
2791     // return points.
2792     if (Ins[i].Flags.isSRet()) {
2793       unsigned Reg = FuncInfo->getSRetReturnReg();
2794       if (!Reg) {
2795         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2796         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2797         FuncInfo->setSRetReturnReg(Reg);
2798       }
2799       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2800       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2801       break;
2802     }
2803   }
2804
2805   unsigned StackSize = CCInfo.getNextStackOffset();
2806   // Align stack specially for tail calls.
2807   if (shouldGuaranteeTCO(CallConv,
2808                          MF.getTarget().Options.GuaranteedTailCallOpt))
2809     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2810
2811   // If the function takes variable number of arguments, make a frame index for
2812   // the start of the first vararg value... for expansion of llvm.va_start. We
2813   // can skip this if there are no va_start calls.
2814   if (MFI->hasVAStart() &&
2815       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2816                    CallConv != CallingConv::X86_ThisCall))) {
2817     FuncInfo->setVarArgsFrameIndex(
2818         MFI->CreateFixedObject(1, StackSize, true));
2819   }
2820
2821   // Figure out if XMM registers are in use.
2822   assert(!(Subtarget->useSoftFloat() &&
2823            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2824          "SSE register cannot be used when SSE is disabled!");
2825
2826   // 64-bit calling conventions support varargs and register parameters, so we
2827   // have to do extra work to spill them in the prologue.
2828   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2829     // Find the first unallocated argument registers.
2830     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2831     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2832     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2833     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2834     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2835            "SSE register cannot be used when SSE is disabled!");
2836
2837     // Gather all the live in physical registers.
2838     SmallVector<SDValue, 6> LiveGPRs;
2839     SmallVector<SDValue, 8> LiveXMMRegs;
2840     SDValue ALVal;
2841     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2842       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2843       LiveGPRs.push_back(
2844           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2845     }
2846     if (!ArgXMMs.empty()) {
2847       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2848       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2849       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2850         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2851         LiveXMMRegs.push_back(
2852             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2853       }
2854     }
2855
2856     if (IsWin64) {
2857       // Get to the caller-allocated home save location.  Add 8 to account
2858       // for the return address.
2859       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2860       FuncInfo->setRegSaveFrameIndex(
2861           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2862       // Fixup to set vararg frame on shadow area (4 x i64).
2863       if (NumIntRegs < 4)
2864         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2865     } else {
2866       // For X86-64, if there are vararg parameters that are passed via
2867       // registers, then we must store them to their spots on the stack so
2868       // they may be loaded by deferencing the result of va_next.
2869       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2870       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2871       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2872           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2873     }
2874
2875     // Store the integer parameter registers.
2876     SmallVector<SDValue, 8> MemOps;
2877     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2878                                       getPointerTy(DAG.getDataLayout()));
2879     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2880     for (SDValue Val : LiveGPRs) {
2881       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2882                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2883       SDValue Store =
2884           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2885                        MachinePointerInfo::getFixedStack(
2886                            DAG.getMachineFunction(),
2887                            FuncInfo->getRegSaveFrameIndex(), Offset),
2888                        false, false, 0);
2889       MemOps.push_back(Store);
2890       Offset += 8;
2891     }
2892
2893     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2894       // Now store the XMM (fp + vector) parameter registers.
2895       SmallVector<SDValue, 12> SaveXMMOps;
2896       SaveXMMOps.push_back(Chain);
2897       SaveXMMOps.push_back(ALVal);
2898       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2899                              FuncInfo->getRegSaveFrameIndex(), dl));
2900       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2901                              FuncInfo->getVarArgsFPOffset(), dl));
2902       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2903                         LiveXMMRegs.end());
2904       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2905                                    MVT::Other, SaveXMMOps));
2906     }
2907
2908     if (!MemOps.empty())
2909       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2910   }
2911
2912   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2913     // Find the largest legal vector type.
2914     MVT VecVT = MVT::Other;
2915     // FIXME: Only some x86_32 calling conventions support AVX512.
2916     if (Subtarget->hasAVX512() &&
2917         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2918                      CallConv == CallingConv::Intel_OCL_BI)))
2919       VecVT = MVT::v16f32;
2920     else if (Subtarget->hasAVX())
2921       VecVT = MVT::v8f32;
2922     else if (Subtarget->hasSSE2())
2923       VecVT = MVT::v4f32;
2924
2925     // We forward some GPRs and some vector types.
2926     SmallVector<MVT, 2> RegParmTypes;
2927     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2928     RegParmTypes.push_back(IntVT);
2929     if (VecVT != MVT::Other)
2930       RegParmTypes.push_back(VecVT);
2931
2932     // Compute the set of forwarded registers. The rest are scratch.
2933     SmallVectorImpl<ForwardedRegister> &Forwards =
2934         FuncInfo->getForwardedMustTailRegParms();
2935     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2936
2937     // Conservatively forward AL on x86_64, since it might be used for varargs.
2938     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2939       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2940       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2941     }
2942
2943     // Copy all forwards from physical to virtual registers.
2944     for (ForwardedRegister &F : Forwards) {
2945       // FIXME: Can we use a less constrained schedule?
2946       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2947       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2948       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2949     }
2950   }
2951
2952   // Some CCs need callee pop.
2953   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2954                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2955     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2956   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
2957     // X86 interrupts must pop the error code if present
2958     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 8 : 4);
2959   } else {
2960     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2961     // If this is an sret function, the return should pop the hidden pointer.
2962     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2963         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2964         argsAreStructReturn(Ins, Subtarget->isTargetMCU()) == StackStructReturn)
2965       FuncInfo->setBytesToPopOnReturn(4);
2966   }
2967
2968   if (!Is64Bit) {
2969     // RegSaveFrameIndex is X86-64 only.
2970     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2971     if (CallConv == CallingConv::X86_FastCall ||
2972         CallConv == CallingConv::X86_ThisCall)
2973       // fastcc functions can't have varargs.
2974       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2975   }
2976
2977   FuncInfo->setArgumentStackSize(StackSize);
2978
2979   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2980     EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2981     if (Personality == EHPersonality::CoreCLR) {
2982       assert(Is64Bit);
2983       // TODO: Add a mechanism to frame lowering that will allow us to indicate
2984       // that we'd prefer this slot be allocated towards the bottom of the frame
2985       // (i.e. near the stack pointer after allocating the frame).  Every
2986       // funclet needs a copy of this slot in its (mostly empty) frame, and the
2987       // offset from the bottom of this and each funclet's frame must be the
2988       // same, so the size of funclets' (mostly empty) frames is dictated by
2989       // how far this slot is from the bottom (since they allocate just enough
2990       // space to accomodate holding this slot at the correct offset).
2991       int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2992       EHInfo->PSPSymFrameIdx = PSPSymFI;
2993     }
2994   }
2995
2996   return Chain;
2997 }
2998
2999 SDValue
3000 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
3001                                     SDValue StackPtr, SDValue Arg,
3002                                     SDLoc dl, SelectionDAG &DAG,
3003                                     const CCValAssign &VA,
3004                                     ISD::ArgFlagsTy Flags) const {
3005   unsigned LocMemOffset = VA.getLocMemOffset();
3006   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3007   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3008                        StackPtr, PtrOff);
3009   if (Flags.isByVal())
3010     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3011
3012   return DAG.getStore(
3013       Chain, dl, Arg, PtrOff,
3014       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
3015       false, false, 0);
3016 }
3017
3018 /// Emit a load of return address if tail call
3019 /// optimization is performed and it is required.
3020 SDValue
3021 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
3022                                            SDValue &OutRetAddr, SDValue Chain,
3023                                            bool IsTailCall, bool Is64Bit,
3024                                            int FPDiff, SDLoc dl) const {
3025   // Adjust the Return address stack slot.
3026   EVT VT = getPointerTy(DAG.getDataLayout());
3027   OutRetAddr = getReturnAddressFrameIndex(DAG);
3028
3029   // Load the "old" Return address.
3030   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
3031                            false, false, false, 0);
3032   return SDValue(OutRetAddr.getNode(), 1);
3033 }
3034
3035 /// Emit a store of the return address if tail call
3036 /// optimization is performed and it is required (FPDiff!=0).
3037 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3038                                         SDValue Chain, SDValue RetAddrFrIdx,
3039                                         EVT PtrVT, unsigned SlotSize,
3040                                         int FPDiff, SDLoc dl) {
3041   // Store the return address to the appropriate stack slot.
3042   if (!FPDiff) return Chain;
3043   // Calculate the new stack slot for the return address.
3044   int NewReturnAddrFI =
3045     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3046                                          false);
3047   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3048   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3049                        MachinePointerInfo::getFixedStack(
3050                            DAG.getMachineFunction(), NewReturnAddrFI),
3051                        false, false, 0);
3052   return Chain;
3053 }
3054
3055 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3056 /// operation of specified width.
3057 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
3058                        SDValue V2) {
3059   unsigned NumElems = VT.getVectorNumElements();
3060   SmallVector<int, 8> Mask;
3061   Mask.push_back(NumElems);
3062   for (unsigned i = 1; i != NumElems; ++i)
3063     Mask.push_back(i);
3064   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3065 }
3066
3067 SDValue
3068 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3069                              SmallVectorImpl<SDValue> &InVals) const {
3070   SelectionDAG &DAG                     = CLI.DAG;
3071   SDLoc &dl                             = CLI.DL;
3072   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3073   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3074   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3075   SDValue Chain                         = CLI.Chain;
3076   SDValue Callee                        = CLI.Callee;
3077   CallingConv::ID CallConv              = CLI.CallConv;
3078   bool &isTailCall                      = CLI.IsTailCall;
3079   bool isVarArg                         = CLI.IsVarArg;
3080
3081   MachineFunction &MF = DAG.getMachineFunction();
3082   bool Is64Bit        = Subtarget->is64Bit();
3083   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
3084   StructReturnType SR = callIsStructReturn(Outs, Subtarget->isTargetMCU());
3085   bool IsSibcall      = false;
3086   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3087   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3088
3089   if (CallConv == CallingConv::X86_INTR)
3090     report_fatal_error("X86 interrupts may not be called directly");
3091
3092   if (Attr.getValueAsString() == "true")
3093     isTailCall = false;
3094
3095   if (Subtarget->isPICStyleGOT() &&
3096       !MF.getTarget().Options.GuaranteedTailCallOpt) {
3097     // If we are using a GOT, disable tail calls to external symbols with
3098     // default visibility. Tail calling such a symbol requires using a GOT
3099     // relocation, which forces early binding of the symbol. This breaks code
3100     // that require lazy function symbol resolution. Using musttail or
3101     // GuaranteedTailCallOpt will override this.
3102     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3103     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3104                G->getGlobal()->hasDefaultVisibility()))
3105       isTailCall = false;
3106   }
3107
3108   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3109   if (IsMustTail) {
3110     // Force this to be a tail call.  The verifier rules are enough to ensure
3111     // that we can lower this successfully without moving the return address
3112     // around.
3113     isTailCall = true;
3114   } else if (isTailCall) {
3115     // Check if it's really possible to do a tail call.
3116     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3117                     isVarArg, SR != NotStructReturn,
3118                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3119                     Outs, OutVals, Ins, DAG);
3120
3121     // Sibcalls are automatically detected tailcalls which do not require
3122     // ABI changes.
3123     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3124       IsSibcall = true;
3125
3126     if (isTailCall)
3127       ++NumTailCalls;
3128   }
3129
3130   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3131          "Var args not supported with calling convention fastcc, ghc or hipe");
3132
3133   // Analyze operands of the call, assigning locations to each operand.
3134   SmallVector<CCValAssign, 16> ArgLocs;
3135   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3136
3137   // Allocate shadow area for Win64
3138   if (IsWin64)
3139     CCInfo.AllocateStack(32, 8);
3140
3141   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3142
3143   // Get a count of how many bytes are to be pushed on the stack.
3144   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3145   if (IsSibcall)
3146     // This is a sibcall. The memory operands are available in caller's
3147     // own caller's stack.
3148     NumBytes = 0;
3149   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3150            canGuaranteeTCO(CallConv))
3151     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3152
3153   int FPDiff = 0;
3154   if (isTailCall && !IsSibcall && !IsMustTail) {
3155     // Lower arguments at fp - stackoffset + fpdiff.
3156     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3157
3158     FPDiff = NumBytesCallerPushed - NumBytes;
3159
3160     // Set the delta of movement of the returnaddr stackslot.
3161     // But only set if delta is greater than previous delta.
3162     if (FPDiff < X86Info->getTCReturnAddrDelta())
3163       X86Info->setTCReturnAddrDelta(FPDiff);
3164   }
3165
3166   unsigned NumBytesToPush = NumBytes;
3167   unsigned NumBytesToPop = NumBytes;
3168
3169   // If we have an inalloca argument, all stack space has already been allocated
3170   // for us and be right at the top of the stack.  We don't support multiple
3171   // arguments passed in memory when using inalloca.
3172   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3173     NumBytesToPush = 0;
3174     if (!ArgLocs.back().isMemLoc())
3175       report_fatal_error("cannot use inalloca attribute on a register "
3176                          "parameter");
3177     if (ArgLocs.back().getLocMemOffset() != 0)
3178       report_fatal_error("any parameter with the inalloca attribute must be "
3179                          "the only memory argument");
3180   }
3181
3182   if (!IsSibcall)
3183     Chain = DAG.getCALLSEQ_START(
3184         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3185
3186   SDValue RetAddrFrIdx;
3187   // Load return address for tail calls.
3188   if (isTailCall && FPDiff)
3189     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3190                                     Is64Bit, FPDiff, dl);
3191
3192   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3193   SmallVector<SDValue, 8> MemOpChains;
3194   SDValue StackPtr;
3195
3196   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3197   // of tail call optimization arguments are handle later.
3198   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3199   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3200     // Skip inalloca arguments, they have already been written.
3201     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3202     if (Flags.isInAlloca())
3203       continue;
3204
3205     CCValAssign &VA = ArgLocs[i];
3206     EVT RegVT = VA.getLocVT();
3207     SDValue Arg = OutVals[i];
3208     bool isByVal = Flags.isByVal();
3209
3210     // Promote the value if needed.
3211     switch (VA.getLocInfo()) {
3212     default: llvm_unreachable("Unknown loc info!");
3213     case CCValAssign::Full: break;
3214     case CCValAssign::SExt:
3215       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3216       break;
3217     case CCValAssign::ZExt:
3218       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3219       break;
3220     case CCValAssign::AExt:
3221       if (Arg.getValueType().isVector() &&
3222           Arg.getValueType().getVectorElementType() == MVT::i1)
3223         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3224       else if (RegVT.is128BitVector()) {
3225         // Special case: passing MMX values in XMM registers.
3226         Arg = DAG.getBitcast(MVT::i64, Arg);
3227         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3228         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3229       } else
3230         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3231       break;
3232     case CCValAssign::BCvt:
3233       Arg = DAG.getBitcast(RegVT, Arg);
3234       break;
3235     case CCValAssign::Indirect: {
3236       // Store the argument.
3237       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3238       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3239       Chain = DAG.getStore(
3240           Chain, dl, Arg, SpillSlot,
3241           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3242           false, false, 0);
3243       Arg = SpillSlot;
3244       break;
3245     }
3246     }
3247
3248     if (VA.isRegLoc()) {
3249       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3250       if (isVarArg && IsWin64) {
3251         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3252         // shadow reg if callee is a varargs function.
3253         unsigned ShadowReg = 0;
3254         switch (VA.getLocReg()) {
3255         case X86::XMM0: ShadowReg = X86::RCX; break;
3256         case X86::XMM1: ShadowReg = X86::RDX; break;
3257         case X86::XMM2: ShadowReg = X86::R8; break;
3258         case X86::XMM3: ShadowReg = X86::R9; break;
3259         }
3260         if (ShadowReg)
3261           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3262       }
3263     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3264       assert(VA.isMemLoc());
3265       if (!StackPtr.getNode())
3266         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3267                                       getPointerTy(DAG.getDataLayout()));
3268       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3269                                              dl, DAG, VA, Flags));
3270     }
3271   }
3272
3273   if (!MemOpChains.empty())
3274     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3275
3276   if (Subtarget->isPICStyleGOT()) {
3277     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3278     // GOT pointer.
3279     if (!isTailCall) {
3280       RegsToPass.push_back(std::make_pair(
3281           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3282                                           getPointerTy(DAG.getDataLayout()))));
3283     } else {
3284       // If we are tail calling and generating PIC/GOT style code load the
3285       // address of the callee into ECX. The value in ecx is used as target of
3286       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3287       // for tail calls on PIC/GOT architectures. Normally we would just put the
3288       // address of GOT into ebx and then call target@PLT. But for tail calls
3289       // ebx would be restored (since ebx is callee saved) before jumping to the
3290       // target@PLT.
3291
3292       // Note: The actual moving to ECX is done further down.
3293       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3294       if (G && !G->getGlobal()->hasLocalLinkage() &&
3295           G->getGlobal()->hasDefaultVisibility())
3296         Callee = LowerGlobalAddress(Callee, DAG);
3297       else if (isa<ExternalSymbolSDNode>(Callee))
3298         Callee = LowerExternalSymbol(Callee, DAG);
3299     }
3300   }
3301
3302   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3303     // From AMD64 ABI document:
3304     // For calls that may call functions that use varargs or stdargs
3305     // (prototype-less calls or calls to functions containing ellipsis (...) in
3306     // the declaration) %al is used as hidden argument to specify the number
3307     // of SSE registers used. The contents of %al do not need to match exactly
3308     // the number of registers, but must be an ubound on the number of SSE
3309     // registers used and is in the range 0 - 8 inclusive.
3310
3311     // Count the number of XMM registers allocated.
3312     static const MCPhysReg XMMArgRegs[] = {
3313       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3314       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3315     };
3316     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3317     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3318            && "SSE registers cannot be used when SSE is disabled");
3319
3320     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3321                                         DAG.getConstant(NumXMMRegs, dl,
3322                                                         MVT::i8)));
3323   }
3324
3325   if (isVarArg && IsMustTail) {
3326     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3327     for (const auto &F : Forwards) {
3328       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3329       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3330     }
3331   }
3332
3333   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3334   // don't need this because the eligibility check rejects calls that require
3335   // shuffling arguments passed in memory.
3336   if (!IsSibcall && isTailCall) {
3337     // Force all the incoming stack arguments to be loaded from the stack
3338     // before any new outgoing arguments are stored to the stack, because the
3339     // outgoing stack slots may alias the incoming argument stack slots, and
3340     // the alias isn't otherwise explicit. This is slightly more conservative
3341     // than necessary, because it means that each store effectively depends
3342     // on every argument instead of just those arguments it would clobber.
3343     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3344
3345     SmallVector<SDValue, 8> MemOpChains2;
3346     SDValue FIN;
3347     int FI = 0;
3348     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3349       CCValAssign &VA = ArgLocs[i];
3350       if (VA.isRegLoc())
3351         continue;
3352       assert(VA.isMemLoc());
3353       SDValue Arg = OutVals[i];
3354       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3355       // Skip inalloca arguments.  They don't require any work.
3356       if (Flags.isInAlloca())
3357         continue;
3358       // Create frame index.
3359       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3360       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3361       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3362       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3363
3364       if (Flags.isByVal()) {
3365         // Copy relative to framepointer.
3366         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3367         if (!StackPtr.getNode())
3368           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3369                                         getPointerTy(DAG.getDataLayout()));
3370         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3371                              StackPtr, Source);
3372
3373         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3374                                                          ArgChain,
3375                                                          Flags, DAG, dl));
3376       } else {
3377         // Store relative to framepointer.
3378         MemOpChains2.push_back(DAG.getStore(
3379             ArgChain, dl, Arg, FIN,
3380             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3381             false, false, 0));
3382       }
3383     }
3384
3385     if (!MemOpChains2.empty())
3386       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3387
3388     // Store the return address to the appropriate stack slot.
3389     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3390                                      getPointerTy(DAG.getDataLayout()),
3391                                      RegInfo->getSlotSize(), FPDiff, dl);
3392   }
3393
3394   // Build a sequence of copy-to-reg nodes chained together with token chain
3395   // and flag operands which copy the outgoing args into registers.
3396   SDValue InFlag;
3397   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3398     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3399                              RegsToPass[i].second, InFlag);
3400     InFlag = Chain.getValue(1);
3401   }
3402
3403   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3404     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3405     // In the 64-bit large code model, we have to make all calls
3406     // through a register, since the call instruction's 32-bit
3407     // pc-relative offset may not be large enough to hold the whole
3408     // address.
3409   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3410     // If the callee is a GlobalAddress node (quite common, every direct call
3411     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3412     // it.
3413     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3414
3415     // We should use extra load for direct calls to dllimported functions in
3416     // non-JIT mode.
3417     const GlobalValue *GV = G->getGlobal();
3418     if (!GV->hasDLLImportStorageClass()) {
3419       unsigned char OpFlags = 0;
3420       bool ExtraLoad = false;
3421       unsigned WrapperKind = ISD::DELETED_NODE;
3422
3423       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3424       // external symbols most go through the PLT in PIC mode.  If the symbol
3425       // has hidden or protected visibility, or if it is static or local, then
3426       // we don't need to use the PLT - we can directly call it.
3427       if (Subtarget->isTargetELF() &&
3428           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3429           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3430         OpFlags = X86II::MO_PLT;
3431       } else if (Subtarget->isPICStyleStubAny() &&
3432                  !GV->isStrongDefinitionForLinker() &&
3433                  (!Subtarget->getTargetTriple().isMacOSX() ||
3434                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3435         // PC-relative references to external symbols should go through $stub,
3436         // unless we're building with the leopard linker or later, which
3437         // automatically synthesizes these stubs.
3438         OpFlags = X86II::MO_DARWIN_STUB;
3439       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3440                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3441         // If the function is marked as non-lazy, generate an indirect call
3442         // which loads from the GOT directly. This avoids runtime overhead
3443         // at the cost of eager binding (and one extra byte of encoding).
3444         OpFlags = X86II::MO_GOTPCREL;
3445         WrapperKind = X86ISD::WrapperRIP;
3446         ExtraLoad = true;
3447       }
3448
3449       Callee = DAG.getTargetGlobalAddress(
3450           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3451
3452       // Add a wrapper if needed.
3453       if (WrapperKind != ISD::DELETED_NODE)
3454         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3455                              getPointerTy(DAG.getDataLayout()), Callee);
3456       // Add extra indirection if needed.
3457       if (ExtraLoad)
3458         Callee = DAG.getLoad(
3459             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3460             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3461             false, 0);
3462     }
3463   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3464     unsigned char OpFlags = 0;
3465
3466     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3467     // external symbols should go through the PLT.
3468     if (Subtarget->isTargetELF() &&
3469         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3470       OpFlags = X86II::MO_PLT;
3471     } else if (Subtarget->isPICStyleStubAny() &&
3472                (!Subtarget->getTargetTriple().isMacOSX() ||
3473                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3474       // PC-relative references to external symbols should go through $stub,
3475       // unless we're building with the leopard linker or later, which
3476       // automatically synthesizes these stubs.
3477       OpFlags = X86II::MO_DARWIN_STUB;
3478     }
3479
3480     Callee = DAG.getTargetExternalSymbol(
3481         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3482   } else if (Subtarget->isTarget64BitILP32() &&
3483              Callee->getValueType(0) == MVT::i32) {
3484     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3485     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3486   }
3487
3488   // Returns a chain & a flag for retval copy to use.
3489   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3490   SmallVector<SDValue, 8> Ops;
3491
3492   if (!IsSibcall && isTailCall) {
3493     Chain = DAG.getCALLSEQ_END(Chain,
3494                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3495                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3496     InFlag = Chain.getValue(1);
3497   }
3498
3499   Ops.push_back(Chain);
3500   Ops.push_back(Callee);
3501
3502   if (isTailCall)
3503     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3504
3505   // Add argument registers to the end of the list so that they are known live
3506   // into the call.
3507   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3508     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3509                                   RegsToPass[i].second.getValueType()));
3510
3511   // Add a register mask operand representing the call-preserved registers.
3512   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3513   assert(Mask && "Missing call preserved mask for calling convention");
3514
3515   // If this is an invoke in a 32-bit function using a funclet-based
3516   // personality, assume the function clobbers all registers. If an exception
3517   // is thrown, the runtime will not restore CSRs.
3518   // FIXME: Model this more precisely so that we can register allocate across
3519   // the normal edge and spill and fill across the exceptional edge.
3520   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3521     const Function *CallerFn = MF.getFunction();
3522     EHPersonality Pers =
3523         CallerFn->hasPersonalityFn()
3524             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3525             : EHPersonality::Unknown;
3526     if (isFuncletEHPersonality(Pers))
3527       Mask = RegInfo->getNoPreservedMask();
3528   }
3529
3530   Ops.push_back(DAG.getRegisterMask(Mask));
3531
3532   if (InFlag.getNode())
3533     Ops.push_back(InFlag);
3534
3535   if (isTailCall) {
3536     // We used to do:
3537     //// If this is the first return lowered for this function, add the regs
3538     //// to the liveout set for the function.
3539     // This isn't right, although it's probably harmless on x86; liveouts
3540     // should be computed from returns not tail calls.  Consider a void
3541     // function making a tail call to a function returning int.
3542     MF.getFrameInfo()->setHasTailCall();
3543     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3544   }
3545
3546   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3547   InFlag = Chain.getValue(1);
3548
3549   // Create the CALLSEQ_END node.
3550   unsigned NumBytesForCalleeToPop;
3551   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3552                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3553     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3554   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3555            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3556            SR == StackStructReturn)
3557     // If this is a call to a struct-return function, the callee
3558     // pops the hidden struct pointer, so we have to push it back.
3559     // This is common for Darwin/X86, Linux & Mingw32 targets.
3560     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3561     NumBytesForCalleeToPop = 4;
3562   else
3563     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3564
3565   // Returns a flag for retval copy to use.
3566   if (!IsSibcall) {
3567     Chain = DAG.getCALLSEQ_END(Chain,
3568                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3569                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3570                                                      true),
3571                                InFlag, dl);
3572     InFlag = Chain.getValue(1);
3573   }
3574
3575   // Handle result values, copying them out of physregs into vregs that we
3576   // return.
3577   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3578                          Ins, dl, DAG, InVals);
3579 }
3580
3581 //===----------------------------------------------------------------------===//
3582 //                Fast Calling Convention (tail call) implementation
3583 //===----------------------------------------------------------------------===//
3584
3585 //  Like std call, callee cleans arguments, convention except that ECX is
3586 //  reserved for storing the tail called function address. Only 2 registers are
3587 //  free for argument passing (inreg). Tail call optimization is performed
3588 //  provided:
3589 //                * tailcallopt is enabled
3590 //                * caller/callee are fastcc
3591 //  On X86_64 architecture with GOT-style position independent code only local
3592 //  (within module) calls are supported at the moment.
3593 //  To keep the stack aligned according to platform abi the function
3594 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3595 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3596 //  If a tail called function callee has more arguments than the caller the
3597 //  caller needs to make sure that there is room to move the RETADDR to. This is
3598 //  achieved by reserving an area the size of the argument delta right after the
3599 //  original RETADDR, but before the saved framepointer or the spilled registers
3600 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3601 //  stack layout:
3602 //    arg1
3603 //    arg2
3604 //    RETADDR
3605 //    [ new RETADDR
3606 //      move area ]
3607 //    (possible EBP)
3608 //    ESI
3609 //    EDI
3610 //    local1 ..
3611
3612 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3613 /// requirement.
3614 unsigned
3615 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3616                                                SelectionDAG& DAG) const {
3617   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3618   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3619   unsigned StackAlignment = TFI.getStackAlignment();
3620   uint64_t AlignMask = StackAlignment - 1;
3621   int64_t Offset = StackSize;
3622   unsigned SlotSize = RegInfo->getSlotSize();
3623   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3624     // Number smaller than 12 so just add the difference.
3625     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3626   } else {
3627     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3628     Offset = ((~AlignMask) & Offset) + StackAlignment +
3629       (StackAlignment-SlotSize);
3630   }
3631   return Offset;
3632 }
3633
3634 /// Return true if the given stack call argument is already available in the
3635 /// same position (relatively) of the caller's incoming argument stack.
3636 static
3637 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3638                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3639                          const X86InstrInfo *TII) {
3640   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3641   int FI = INT_MAX;
3642   if (Arg.getOpcode() == ISD::CopyFromReg) {
3643     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3644     if (!TargetRegisterInfo::isVirtualRegister(VR))
3645       return false;
3646     MachineInstr *Def = MRI->getVRegDef(VR);
3647     if (!Def)
3648       return false;
3649     if (!Flags.isByVal()) {
3650       if (!TII->isLoadFromStackSlot(Def, FI))
3651         return false;
3652     } else {
3653       unsigned Opcode = Def->getOpcode();
3654       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3655            Opcode == X86::LEA64_32r) &&
3656           Def->getOperand(1).isFI()) {
3657         FI = Def->getOperand(1).getIndex();
3658         Bytes = Flags.getByValSize();
3659       } else
3660         return false;
3661     }
3662   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3663     if (Flags.isByVal())
3664       // ByVal argument is passed in as a pointer but it's now being
3665       // dereferenced. e.g.
3666       // define @foo(%struct.X* %A) {
3667       //   tail call @bar(%struct.X* byval %A)
3668       // }
3669       return false;
3670     SDValue Ptr = Ld->getBasePtr();
3671     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3672     if (!FINode)
3673       return false;
3674     FI = FINode->getIndex();
3675   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3676     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3677     FI = FINode->getIndex();
3678     Bytes = Flags.getByValSize();
3679   } else
3680     return false;
3681
3682   assert(FI != INT_MAX);
3683   if (!MFI->isFixedObjectIndex(FI))
3684     return false;
3685   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3686 }
3687
3688 /// Check whether the call is eligible for tail call optimization. Targets
3689 /// that want to do tail call optimization should implement this function.
3690 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3691     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3692     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3693     const SmallVectorImpl<ISD::OutputArg> &Outs,
3694     const SmallVectorImpl<SDValue> &OutVals,
3695     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3696   if (!mayTailCallThisCC(CalleeCC))
3697     return false;
3698
3699   // If -tailcallopt is specified, make fastcc functions tail-callable.
3700   MachineFunction &MF = DAG.getMachineFunction();
3701   const Function *CallerF = MF.getFunction();
3702
3703   // If the function return type is x86_fp80 and the callee return type is not,
3704   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3705   // perform a tailcall optimization here.
3706   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3707     return false;
3708
3709   CallingConv::ID CallerCC = CallerF->getCallingConv();
3710   bool CCMatch = CallerCC == CalleeCC;
3711   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3712   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3713
3714   // Win64 functions have extra shadow space for argument homing. Don't do the
3715   // sibcall if the caller and callee have mismatched expectations for this
3716   // space.
3717   if (IsCalleeWin64 != IsCallerWin64)
3718     return false;
3719
3720   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3721     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3722       return true;
3723     return false;
3724   }
3725
3726   // Look for obvious safe cases to perform tail call optimization that do not
3727   // require ABI changes. This is what gcc calls sibcall.
3728
3729   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3730   // emit a special epilogue.
3731   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3732   if (RegInfo->needsStackRealignment(MF))
3733     return false;
3734
3735   // Also avoid sibcall optimization if either caller or callee uses struct
3736   // return semantics.
3737   if (isCalleeStructRet || isCallerStructRet)
3738     return false;
3739
3740   // Do not sibcall optimize vararg calls unless all arguments are passed via
3741   // registers.
3742   if (isVarArg && !Outs.empty()) {
3743     // Optimizing for varargs on Win64 is unlikely to be safe without
3744     // additional testing.
3745     if (IsCalleeWin64 || IsCallerWin64)
3746       return false;
3747
3748     SmallVector<CCValAssign, 16> ArgLocs;
3749     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3750                    *DAG.getContext());
3751
3752     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3753     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3754       if (!ArgLocs[i].isRegLoc())
3755         return false;
3756   }
3757
3758   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3759   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3760   // this into a sibcall.
3761   bool Unused = false;
3762   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3763     if (!Ins[i].Used) {
3764       Unused = true;
3765       break;
3766     }
3767   }
3768   if (Unused) {
3769     SmallVector<CCValAssign, 16> RVLocs;
3770     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3771                    *DAG.getContext());
3772     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3773     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3774       CCValAssign &VA = RVLocs[i];
3775       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3776         return false;
3777     }
3778   }
3779
3780   // If the calling conventions do not match, then we'd better make sure the
3781   // results are returned in the same way as what the caller expects.
3782   if (!CCMatch) {
3783     SmallVector<CCValAssign, 16> RVLocs1;
3784     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3785                     *DAG.getContext());
3786     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3787
3788     SmallVector<CCValAssign, 16> RVLocs2;
3789     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3790                     *DAG.getContext());
3791     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3792
3793     if (RVLocs1.size() != RVLocs2.size())
3794       return false;
3795     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3796       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3797         return false;
3798       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3799         return false;
3800       if (RVLocs1[i].isRegLoc()) {
3801         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3802           return false;
3803       } else {
3804         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3805           return false;
3806       }
3807     }
3808   }
3809
3810   unsigned StackArgsSize = 0;
3811
3812   // If the callee takes no arguments then go on to check the results of the
3813   // call.
3814   if (!Outs.empty()) {
3815     // Check if stack adjustment is needed. For now, do not do this if any
3816     // argument is passed on the stack.
3817     SmallVector<CCValAssign, 16> ArgLocs;
3818     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3819                    *DAG.getContext());
3820
3821     // Allocate shadow area for Win64
3822     if (IsCalleeWin64)
3823       CCInfo.AllocateStack(32, 8);
3824
3825     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3826     StackArgsSize = CCInfo.getNextStackOffset();
3827
3828     if (CCInfo.getNextStackOffset()) {
3829       // Check if the arguments are already laid out in the right way as
3830       // the caller's fixed stack objects.
3831       MachineFrameInfo *MFI = MF.getFrameInfo();
3832       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3833       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3834       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3835         CCValAssign &VA = ArgLocs[i];
3836         SDValue Arg = OutVals[i];
3837         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3838         if (VA.getLocInfo() == CCValAssign::Indirect)
3839           return false;
3840         if (!VA.isRegLoc()) {
3841           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3842                                    MFI, MRI, TII))
3843             return false;
3844         }
3845       }
3846     }
3847
3848     // If the tailcall address may be in a register, then make sure it's
3849     // possible to register allocate for it. In 32-bit, the call address can
3850     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3851     // callee-saved registers are restored. These happen to be the same
3852     // registers used to pass 'inreg' arguments so watch out for those.
3853     if (!Subtarget->is64Bit() &&
3854         ((!isa<GlobalAddressSDNode>(Callee) &&
3855           !isa<ExternalSymbolSDNode>(Callee)) ||
3856          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3857       unsigned NumInRegs = 0;
3858       // In PIC we need an extra register to formulate the address computation
3859       // for the callee.
3860       unsigned MaxInRegs =
3861         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3862
3863       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3864         CCValAssign &VA = ArgLocs[i];
3865         if (!VA.isRegLoc())
3866           continue;
3867         unsigned Reg = VA.getLocReg();
3868         switch (Reg) {
3869         default: break;
3870         case X86::EAX: case X86::EDX: case X86::ECX:
3871           if (++NumInRegs == MaxInRegs)
3872             return false;
3873           break;
3874         }
3875       }
3876     }
3877   }
3878
3879   bool CalleeWillPop =
3880       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3881                        MF.getTarget().Options.GuaranteedTailCallOpt);
3882
3883   if (unsigned BytesToPop =
3884           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3885     // If we have bytes to pop, the callee must pop them.
3886     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3887     if (!CalleePopMatches)
3888       return false;
3889   } else if (CalleeWillPop && StackArgsSize > 0) {
3890     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3891     return false;
3892   }
3893
3894   return true;
3895 }
3896
3897 FastISel *
3898 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3899                                   const TargetLibraryInfo *libInfo) const {
3900   return X86::createFastISel(funcInfo, libInfo);
3901 }
3902
3903 //===----------------------------------------------------------------------===//
3904 //                           Other Lowering Hooks
3905 //===----------------------------------------------------------------------===//
3906
3907 static bool MayFoldLoad(SDValue Op) {
3908   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3909 }
3910
3911 static bool MayFoldIntoStore(SDValue Op) {
3912   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3913 }
3914
3915 static bool isTargetShuffle(unsigned Opcode) {
3916   switch(Opcode) {
3917   default: return false;
3918   case X86ISD::BLENDI:
3919   case X86ISD::PSHUFB:
3920   case X86ISD::PSHUFD:
3921   case X86ISD::PSHUFHW:
3922   case X86ISD::PSHUFLW:
3923   case X86ISD::SHUFP:
3924   case X86ISD::INSERTPS:
3925   case X86ISD::PALIGNR:
3926   case X86ISD::MOVLHPS:
3927   case X86ISD::MOVLHPD:
3928   case X86ISD::MOVHLPS:
3929   case X86ISD::MOVLPS:
3930   case X86ISD::MOVLPD:
3931   case X86ISD::MOVSHDUP:
3932   case X86ISD::MOVSLDUP:
3933   case X86ISD::MOVDDUP:
3934   case X86ISD::MOVSS:
3935   case X86ISD::MOVSD:
3936   case X86ISD::UNPCKL:
3937   case X86ISD::UNPCKH:
3938   case X86ISD::VPERMILPI:
3939   case X86ISD::VPERM2X128:
3940   case X86ISD::VPERMI:
3941   case X86ISD::VPERMV:
3942   case X86ISD::VPERMV3:
3943     return true;
3944   }
3945 }
3946
3947 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3948                                     SDValue V1, unsigned TargetMask,
3949                                     SelectionDAG &DAG) {
3950   switch(Opc) {
3951   default: llvm_unreachable("Unknown x86 shuffle node");
3952   case X86ISD::PSHUFD:
3953   case X86ISD::PSHUFHW:
3954   case X86ISD::PSHUFLW:
3955   case X86ISD::VPERMILPI:
3956   case X86ISD::VPERMI:
3957     return DAG.getNode(Opc, dl, VT, V1,
3958                        DAG.getConstant(TargetMask, dl, MVT::i8));
3959   }
3960 }
3961
3962 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3963                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3964   switch(Opc) {
3965   default: llvm_unreachable("Unknown x86 shuffle node");
3966   case X86ISD::MOVLHPS:
3967   case X86ISD::MOVLHPD:
3968   case X86ISD::MOVHLPS:
3969   case X86ISD::MOVLPS:
3970   case X86ISD::MOVLPD:
3971   case X86ISD::MOVSS:
3972   case X86ISD::MOVSD:
3973   case X86ISD::UNPCKL:
3974   case X86ISD::UNPCKH:
3975     return DAG.getNode(Opc, dl, VT, V1, V2);
3976   }
3977 }
3978
3979 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3980   MachineFunction &MF = DAG.getMachineFunction();
3981   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3982   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3983   int ReturnAddrIndex = FuncInfo->getRAIndex();
3984
3985   if (ReturnAddrIndex == 0) {
3986     // Set up a frame object for the return address.
3987     unsigned SlotSize = RegInfo->getSlotSize();
3988     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3989                                                            -(int64_t)SlotSize,
3990                                                            false);
3991     FuncInfo->setRAIndex(ReturnAddrIndex);
3992   }
3993
3994   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3995 }
3996
3997 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3998                                        bool hasSymbolicDisplacement) {
3999   // Offset should fit into 32 bit immediate field.
4000   if (!isInt<32>(Offset))
4001     return false;
4002
4003   // If we don't have a symbolic displacement - we don't have any extra
4004   // restrictions.
4005   if (!hasSymbolicDisplacement)
4006     return true;
4007
4008   // FIXME: Some tweaks might be needed for medium code model.
4009   if (M != CodeModel::Small && M != CodeModel::Kernel)
4010     return false;
4011
4012   // For small code model we assume that latest object is 16MB before end of 31
4013   // bits boundary. We may also accept pretty large negative constants knowing
4014   // that all objects are in the positive half of address space.
4015   if (M == CodeModel::Small && Offset < 16*1024*1024)
4016     return true;
4017
4018   // For kernel code model we know that all object resist in the negative half
4019   // of 32bits address space. We may not accept negative offsets, since they may
4020   // be just off and we may accept pretty large positive ones.
4021   if (M == CodeModel::Kernel && Offset >= 0)
4022     return true;
4023
4024   return false;
4025 }
4026
4027 /// Determines whether the callee is required to pop its own arguments.
4028 /// Callee pop is necessary to support tail calls.
4029 bool X86::isCalleePop(CallingConv::ID CallingConv,
4030                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4031   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4032   // can guarantee TCO.
4033   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4034     return true;
4035
4036   switch (CallingConv) {
4037   default:
4038     return false;
4039   case CallingConv::X86_StdCall:
4040   case CallingConv::X86_FastCall:
4041   case CallingConv::X86_ThisCall:
4042   case CallingConv::X86_VectorCall:
4043     return !is64Bit;
4044   }
4045 }
4046
4047 /// \brief Return true if the condition is an unsigned comparison operation.
4048 static bool isX86CCUnsigned(unsigned X86CC) {
4049   switch (X86CC) {
4050   default: llvm_unreachable("Invalid integer condition!");
4051   case X86::COND_E:     return true;
4052   case X86::COND_G:     return false;
4053   case X86::COND_GE:    return false;
4054   case X86::COND_L:     return false;
4055   case X86::COND_LE:    return false;
4056   case X86::COND_NE:    return true;
4057   case X86::COND_B:     return true;
4058   case X86::COND_A:     return true;
4059   case X86::COND_BE:    return true;
4060   case X86::COND_AE:    return true;
4061   }
4062 }
4063
4064 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4065   switch (SetCCOpcode) {
4066   default: llvm_unreachable("Invalid integer condition!");
4067   case ISD::SETEQ:  return X86::COND_E;
4068   case ISD::SETGT:  return X86::COND_G;
4069   case ISD::SETGE:  return X86::COND_GE;
4070   case ISD::SETLT:  return X86::COND_L;
4071   case ISD::SETLE:  return X86::COND_LE;
4072   case ISD::SETNE:  return X86::COND_NE;
4073   case ISD::SETULT: return X86::COND_B;
4074   case ISD::SETUGT: return X86::COND_A;
4075   case ISD::SETULE: return X86::COND_BE;
4076   case ISD::SETUGE: return X86::COND_AE;
4077   }
4078 }
4079
4080 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4081 /// condition code, returning the condition code and the LHS/RHS of the
4082 /// comparison to make.
4083 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4084                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4085   if (!isFP) {
4086     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4087       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4088         // X > -1   -> X == 0, jump !sign.
4089         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4090         return X86::COND_NS;
4091       }
4092       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4093         // X < 0   -> X == 0, jump on sign.
4094         return X86::COND_S;
4095       }
4096       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4097         // X < 1   -> X <= 0
4098         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4099         return X86::COND_LE;
4100       }
4101     }
4102
4103     return TranslateIntegerX86CC(SetCCOpcode);
4104   }
4105
4106   // First determine if it is required or is profitable to flip the operands.
4107
4108   // If LHS is a foldable load, but RHS is not, flip the condition.
4109   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4110       !ISD::isNON_EXTLoad(RHS.getNode())) {
4111     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4112     std::swap(LHS, RHS);
4113   }
4114
4115   switch (SetCCOpcode) {
4116   default: break;
4117   case ISD::SETOLT:
4118   case ISD::SETOLE:
4119   case ISD::SETUGT:
4120   case ISD::SETUGE:
4121     std::swap(LHS, RHS);
4122     break;
4123   }
4124
4125   // On a floating point condition, the flags are set as follows:
4126   // ZF  PF  CF   op
4127   //  0 | 0 | 0 | X > Y
4128   //  0 | 0 | 1 | X < Y
4129   //  1 | 0 | 0 | X == Y
4130   //  1 | 1 | 1 | unordered
4131   switch (SetCCOpcode) {
4132   default: llvm_unreachable("Condcode should be pre-legalized away");
4133   case ISD::SETUEQ:
4134   case ISD::SETEQ:   return X86::COND_E;
4135   case ISD::SETOLT:              // flipped
4136   case ISD::SETOGT:
4137   case ISD::SETGT:   return X86::COND_A;
4138   case ISD::SETOLE:              // flipped
4139   case ISD::SETOGE:
4140   case ISD::SETGE:   return X86::COND_AE;
4141   case ISD::SETUGT:              // flipped
4142   case ISD::SETULT:
4143   case ISD::SETLT:   return X86::COND_B;
4144   case ISD::SETUGE:              // flipped
4145   case ISD::SETULE:
4146   case ISD::SETLE:   return X86::COND_BE;
4147   case ISD::SETONE:
4148   case ISD::SETNE:   return X86::COND_NE;
4149   case ISD::SETUO:   return X86::COND_P;
4150   case ISD::SETO:    return X86::COND_NP;
4151   case ISD::SETOEQ:
4152   case ISD::SETUNE:  return X86::COND_INVALID;
4153   }
4154 }
4155
4156 /// Is there a floating point cmov for the specific X86 condition code?
4157 /// Current x86 isa includes the following FP cmov instructions:
4158 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4159 static bool hasFPCMov(unsigned X86CC) {
4160   switch (X86CC) {
4161   default:
4162     return false;
4163   case X86::COND_B:
4164   case X86::COND_BE:
4165   case X86::COND_E:
4166   case X86::COND_P:
4167   case X86::COND_A:
4168   case X86::COND_AE:
4169   case X86::COND_NE:
4170   case X86::COND_NP:
4171     return true;
4172   }
4173 }
4174
4175
4176 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
4177                                            const CallInst &I,
4178                                            unsigned Intrinsic) const {
4179
4180   const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
4181   if (!IntrData)
4182     return false;
4183
4184   switch (IntrData->Type) {
4185   case LOADA:
4186   case LOADU: {
4187     Info.opc = ISD::INTRINSIC_W_CHAIN;
4188     Info.memVT = MVT::getVT(I.getType());
4189     Info.ptrVal = I.getArgOperand(0);
4190     Info.offset = 0;
4191     Info.align = (IntrData->Type == LOADA ? Info.memVT.getSizeInBits()/8 : 1);
4192     Info.vol = false;
4193     Info.readMem = true;
4194     Info.writeMem = false;
4195     return true;
4196   }
4197   default:
4198     break;
4199   }
4200
4201   return false;
4202 }
4203
4204 /// Returns true if the target can instruction select the
4205 /// specified FP immediate natively. If false, the legalizer will
4206 /// materialize the FP immediate as a load from a constant pool.
4207 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4208   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4209     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4210       return true;
4211   }
4212   return false;
4213 }
4214
4215 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4216                                               ISD::LoadExtType ExtTy,
4217                                               EVT NewVT) const {
4218   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4219   // relocation target a movq or addq instruction: don't let the load shrink.
4220   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4221   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4222     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4223       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4224   return true;
4225 }
4226
4227 /// \brief Returns true if it is beneficial to convert a load of a constant
4228 /// to just the constant itself.
4229 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4230                                                           Type *Ty) const {
4231   assert(Ty->isIntegerTy());
4232
4233   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4234   if (BitSize == 0 || BitSize > 64)
4235     return false;
4236   return true;
4237 }
4238
4239 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4240                                                 unsigned Index) const {
4241   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4242     return false;
4243
4244   return (Index == 0 || Index == ResVT.getVectorNumElements());
4245 }
4246
4247 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4248   // Speculate cttz only if we can directly use TZCNT.
4249   return Subtarget->hasBMI();
4250 }
4251
4252 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4253   // Speculate ctlz only if we can directly use LZCNT.
4254   return Subtarget->hasLZCNT();
4255 }
4256
4257 /// Return true if every element in Mask, beginning
4258 /// from position Pos and ending in Pos+Size is undef.
4259 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4260   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4261     if (0 <= Mask[i])
4262       return false;
4263   return true;
4264 }
4265
4266 /// Return true if Val is undef or if its value falls within the
4267 /// specified range (L, H].
4268 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4269   return (Val < 0) || (Val >= Low && Val < Hi);
4270 }
4271
4272 /// Val is either less than zero (undef) or equal to the specified value.
4273 static bool isUndefOrEqual(int Val, int CmpVal) {
4274   return (Val < 0 || Val == CmpVal);
4275 }
4276
4277 /// Return true if every element in Mask, beginning
4278 /// from position Pos and ending in Pos+Size, falls within the specified
4279 /// sequential range (Low, Low+Size]. or is undef.
4280 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4281                                        unsigned Pos, unsigned Size, int Low) {
4282   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4283     if (!isUndefOrEqual(Mask[i], Low))
4284       return false;
4285   return true;
4286 }
4287
4288 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4289 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4290 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4291   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4292   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4293     return false;
4294
4295   // The index should be aligned on a vecWidth-bit boundary.
4296   uint64_t Index =
4297     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4298
4299   MVT VT = N->getSimpleValueType(0);
4300   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4301   bool Result = (Index * ElSize) % vecWidth == 0;
4302
4303   return Result;
4304 }
4305
4306 /// Return true if the specified INSERT_SUBVECTOR
4307 /// operand specifies a subvector insert that is suitable for input to
4308 /// insertion of 128 or 256-bit subvectors
4309 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4310   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4311   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4312     return false;
4313   // The index should be aligned on a vecWidth-bit boundary.
4314   uint64_t Index =
4315     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4316
4317   MVT VT = N->getSimpleValueType(0);
4318   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4319   bool Result = (Index * ElSize) % vecWidth == 0;
4320
4321   return Result;
4322 }
4323
4324 bool X86::isVINSERT128Index(SDNode *N) {
4325   return isVINSERTIndex(N, 128);
4326 }
4327
4328 bool X86::isVINSERT256Index(SDNode *N) {
4329   return isVINSERTIndex(N, 256);
4330 }
4331
4332 bool X86::isVEXTRACT128Index(SDNode *N) {
4333   return isVEXTRACTIndex(N, 128);
4334 }
4335
4336 bool X86::isVEXTRACT256Index(SDNode *N) {
4337   return isVEXTRACTIndex(N, 256);
4338 }
4339
4340 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4341   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4342   assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4343          "Illegal extract subvector for VEXTRACT");
4344
4345   uint64_t Index =
4346     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4347
4348   MVT VecVT = N->getOperand(0).getSimpleValueType();
4349   MVT ElVT = VecVT.getVectorElementType();
4350
4351   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4352   return Index / NumElemsPerChunk;
4353 }
4354
4355 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4356   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4357   assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4358          "Illegal insert subvector for VINSERT");
4359
4360   uint64_t Index =
4361     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4362
4363   MVT VecVT = N->getSimpleValueType(0);
4364   MVT ElVT = VecVT.getVectorElementType();
4365
4366   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4367   return Index / NumElemsPerChunk;
4368 }
4369
4370 /// Return the appropriate immediate to extract the specified
4371 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4372 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4373   return getExtractVEXTRACTImmediate(N, 128);
4374 }
4375
4376 /// Return the appropriate immediate to extract the specified
4377 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4378 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4379   return getExtractVEXTRACTImmediate(N, 256);
4380 }
4381
4382 /// Return the appropriate immediate to insert at the specified
4383 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4384 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4385   return getInsertVINSERTImmediate(N, 128);
4386 }
4387
4388 /// Return the appropriate immediate to insert at the specified
4389 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4390 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4391   return getInsertVINSERTImmediate(N, 256);
4392 }
4393
4394 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4395 bool X86::isZeroNode(SDValue Elt) {
4396   return isNullConstant(Elt) || isNullFPConstant(Elt);
4397 }
4398
4399 // Build a vector of constants
4400 // Use an UNDEF node if MaskElt == -1.
4401 // Spilt 64-bit constants in the 32-bit mode.
4402 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4403                               SelectionDAG &DAG,
4404                               SDLoc dl, bool IsMask = false) {
4405
4406   SmallVector<SDValue, 32>  Ops;
4407   bool Split = false;
4408
4409   MVT ConstVecVT = VT;
4410   unsigned NumElts = VT.getVectorNumElements();
4411   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4412   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4413     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4414     Split = true;
4415   }
4416
4417   MVT EltVT = ConstVecVT.getVectorElementType();
4418   for (unsigned i = 0; i < NumElts; ++i) {
4419     bool IsUndef = Values[i] < 0 && IsMask;
4420     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4421       DAG.getConstant(Values[i], dl, EltVT);
4422     Ops.push_back(OpNode);
4423     if (Split)
4424       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4425                     DAG.getConstant(0, dl, EltVT));
4426   }
4427   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4428   if (Split)
4429     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4430   return ConstsNode;
4431 }
4432
4433 /// Returns a vector of specified type with all zero elements.
4434 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4435                              SelectionDAG &DAG, SDLoc dl) {
4436   assert(VT.isVector() && "Expected a vector type");
4437
4438   // Always build SSE zero vectors as <4 x i32> bitcasted
4439   // to their dest type. This ensures they get CSE'd.
4440   SDValue Vec;
4441   if (VT.is128BitVector()) {  // SSE
4442     if (Subtarget->hasSSE2()) {  // SSE2
4443       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4444       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4445     } else { // SSE1
4446       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4447       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4448     }
4449   } else if (VT.is256BitVector()) { // AVX
4450     if (Subtarget->hasInt256()) { // AVX2
4451       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4452       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4453       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4454     } else {
4455       // 256-bit logic and arithmetic instructions in AVX are all
4456       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4457       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4458       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4459       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4460     }
4461   } else if (VT.is512BitVector()) { // AVX-512
4462       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4463       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4464                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4465       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4466   } else if (VT.getVectorElementType() == MVT::i1) {
4467
4468     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4469             && "Unexpected vector type");
4470     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4471             && "Unexpected vector type");
4472     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4473     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4474     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4475   } else
4476     llvm_unreachable("Unexpected vector type");
4477
4478   return DAG.getBitcast(VT, Vec);
4479 }
4480
4481 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4482                                 SelectionDAG &DAG, SDLoc dl,
4483                                 unsigned vectorWidth) {
4484   assert((vectorWidth == 128 || vectorWidth == 256) &&
4485          "Unsupported vector width");
4486   EVT VT = Vec.getValueType();
4487   EVT ElVT = VT.getVectorElementType();
4488   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4489   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4490                                   VT.getVectorNumElements()/Factor);
4491
4492   // Extract from UNDEF is UNDEF.
4493   if (Vec.getOpcode() == ISD::UNDEF)
4494     return DAG.getUNDEF(ResultVT);
4495
4496   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4497   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4498   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4499
4500   // This is the index of the first element of the vectorWidth-bit chunk
4501   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4502   IdxVal &= ~(ElemsPerChunk - 1);
4503
4504   // If the input is a buildvector just emit a smaller one.
4505   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4506     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4507                        makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4508
4509   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4510   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4511 }
4512
4513 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4514 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4515 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4516 /// instructions or a simple subregister reference. Idx is an index in the
4517 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4518 /// lowering EXTRACT_VECTOR_ELT operations easier.
4519 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4520                                    SelectionDAG &DAG, SDLoc dl) {
4521   assert((Vec.getValueType().is256BitVector() ||
4522           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4523   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4524 }
4525
4526 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4527 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4528                                    SelectionDAG &DAG, SDLoc dl) {
4529   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4530   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4531 }
4532
4533 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4534                                unsigned IdxVal, SelectionDAG &DAG,
4535                                SDLoc dl, unsigned vectorWidth) {
4536   assert((vectorWidth == 128 || vectorWidth == 256) &&
4537          "Unsupported vector width");
4538   // Inserting UNDEF is Result
4539   if (Vec.getOpcode() == ISD::UNDEF)
4540     return Result;
4541   EVT VT = Vec.getValueType();
4542   EVT ElVT = VT.getVectorElementType();
4543   EVT ResultVT = Result.getValueType();
4544
4545   // Insert the relevant vectorWidth bits.
4546   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4547   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4548
4549   // This is the index of the first element of the vectorWidth-bit chunk
4550   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4551   IdxVal &= ~(ElemsPerChunk - 1);
4552
4553   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4554   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4555 }
4556
4557 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4558 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4559 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4560 /// simple superregister reference.  Idx is an index in the 128 bits
4561 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4562 /// lowering INSERT_VECTOR_ELT operations easier.
4563 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4564                                   SelectionDAG &DAG, SDLoc dl) {
4565   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4566
4567   // For insertion into the zero index (low half) of a 256-bit vector, it is
4568   // more efficient to generate a blend with immediate instead of an insert*128.
4569   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4570   // extend the subvector to the size of the result vector. Make sure that
4571   // we are not recursing on that node by checking for undef here.
4572   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4573       Result.getOpcode() != ISD::UNDEF) {
4574     EVT ResultVT = Result.getValueType();
4575     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4576     SDValue Undef = DAG.getUNDEF(ResultVT);
4577     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4578                                  Vec, ZeroIndex);
4579
4580     // The blend instruction, and therefore its mask, depend on the data type.
4581     MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4582     if (ScalarType.isFloatingPoint()) {
4583       // Choose either vblendps (float) or vblendpd (double).
4584       unsigned ScalarSize = ScalarType.getSizeInBits();
4585       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4586       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4587       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4588       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4589     }
4590
4591     const X86Subtarget &Subtarget =
4592     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4593
4594     // AVX2 is needed for 256-bit integer blend support.
4595     // Integers must be cast to 32-bit because there is only vpblendd;
4596     // vpblendw can't be used for this because it has a handicapped mask.
4597
4598     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4599     // is still more efficient than using the wrong domain vinsertf128 that
4600     // will be created by InsertSubVector().
4601     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4602
4603     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4604     Result = DAG.getBitcast(CastVT, Result);
4605     Vec256 = DAG.getBitcast(CastVT, Vec256);
4606     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4607     return DAG.getBitcast(ResultVT, Vec256);
4608   }
4609
4610   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4611 }
4612
4613 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4614                                   SelectionDAG &DAG, SDLoc dl) {
4615   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4616   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4617 }
4618
4619 /// Insert i1-subvector to i1-vector.
4620 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4621
4622   SDLoc dl(Op);
4623   SDValue Vec = Op.getOperand(0);
4624   SDValue SubVec = Op.getOperand(1);
4625   SDValue Idx = Op.getOperand(2);
4626
4627   if (!isa<ConstantSDNode>(Idx))
4628     return SDValue();
4629
4630   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4631   if (IdxVal == 0  && Vec.isUndef()) // the operation is legal
4632     return Op;
4633
4634   MVT OpVT = Op.getSimpleValueType();
4635   MVT SubVecVT = SubVec.getSimpleValueType();
4636   unsigned NumElems = OpVT.getVectorNumElements();
4637   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4638
4639   assert(IdxVal + SubVecNumElems <= NumElems &&
4640          IdxVal % SubVecVT.getSizeInBits() == 0 &&
4641          "Unexpected index value in INSERT_SUBVECTOR");
4642
4643   // There are 3 possible cases:
4644   // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4645   // 2. Subvector should be inserted in the upper part
4646   //    (IdxVal + SubVecNumElems == NumElems)
4647   // 3. Subvector should be inserted in the middle (for example v2i1
4648   //    to v16i1, index 2)
4649
4650   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4651   SDValue Undef = DAG.getUNDEF(OpVT);
4652   SDValue WideSubVec =
4653     DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4654   if (Vec.isUndef())
4655     return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4656       DAG.getConstant(IdxVal, dl, MVT::i8));
4657
4658   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4659     unsigned ShiftLeft = NumElems - SubVecNumElems;
4660     unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4661     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4662       DAG.getConstant(ShiftLeft, dl, MVT::i8));
4663     return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4664       DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4665   }
4666
4667   if (IdxVal == 0) {
4668     // Zero lower bits of the Vec
4669     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4670     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4671     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4672     // Merge them together
4673     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4674   }
4675
4676   // Simple case when we put subvector in the upper part
4677   if (IdxVal + SubVecNumElems == NumElems) {
4678     // Zero upper bits of the Vec
4679     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4680                         DAG.getConstant(IdxVal, dl, MVT::i8));
4681     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4682     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4683     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4684     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4685   }
4686   // Subvector should be inserted in the middle - use shuffle
4687   SmallVector<int, 64> Mask;
4688   for (unsigned i = 0; i < NumElems; ++i)
4689     Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4690                     i : i + NumElems);
4691   return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4692 }
4693
4694 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4695 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4696 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4697 /// large BUILD_VECTORS.
4698 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4699                                    unsigned NumElems, SelectionDAG &DAG,
4700                                    SDLoc dl) {
4701   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4702   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4703 }
4704
4705 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4706                                    unsigned NumElems, SelectionDAG &DAG,
4707                                    SDLoc dl) {
4708   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4709   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4710 }
4711
4712 /// Returns a vector of specified type with all bits set.
4713 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4714 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4715 /// Then bitcast to their original type, ensuring they get CSE'd.
4716 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4717                              SelectionDAG &DAG, SDLoc dl) {
4718   assert(VT.isVector() && "Expected a vector type");
4719
4720   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4721   SDValue Vec;
4722   if (VT.is512BitVector()) {
4723     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4724                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4725     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4726   } else if (VT.is256BitVector()) {
4727     if (Subtarget->hasInt256()) { // AVX2
4728       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4729       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4730     } else { // AVX
4731       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4732       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4733     }
4734   } else if (VT.is128BitVector()) {
4735     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4736   } else
4737     llvm_unreachable("Unexpected vector type");
4738
4739   return DAG.getBitcast(VT, Vec);
4740 }
4741
4742 /// Returns a vector_shuffle node for an unpackl operation.
4743 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4744                           SDValue V2) {
4745   unsigned NumElems = VT.getVectorNumElements();
4746   SmallVector<int, 8> Mask;
4747   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4748     Mask.push_back(i);
4749     Mask.push_back(i + NumElems);
4750   }
4751   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4752 }
4753
4754 /// Returns a vector_shuffle node for an unpackh operation.
4755 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4756                           SDValue V2) {
4757   unsigned NumElems = VT.getVectorNumElements();
4758   SmallVector<int, 8> Mask;
4759   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4760     Mask.push_back(i + Half);
4761     Mask.push_back(i + NumElems + Half);
4762   }
4763   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4764 }
4765
4766 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4767 /// This produces a shuffle where the low element of V2 is swizzled into the
4768 /// zero/undef vector, landing at element Idx.
4769 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4770 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4771                                            bool IsZero,
4772                                            const X86Subtarget *Subtarget,
4773                                            SelectionDAG &DAG) {
4774   MVT VT = V2.getSimpleValueType();
4775   SDValue V1 = IsZero
4776     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4777   unsigned NumElems = VT.getVectorNumElements();
4778   SmallVector<int, 16> MaskVec;
4779   for (unsigned i = 0; i != NumElems; ++i)
4780     // If this is the insertion idx, put the low elt of V2 here.
4781     MaskVec.push_back(i == Idx ? NumElems : i);
4782   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4783 }
4784
4785 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4786 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4787 /// uses one source. Note that this will set IsUnary for shuffles which use a
4788 /// single input multiple times, and in those cases it will
4789 /// adjust the mask to only have indices within that single input.
4790 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
4791                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4792   unsigned NumElems = VT.getVectorNumElements();
4793   SDValue ImmN;
4794
4795   IsUnary = false;
4796   bool IsFakeUnary = false;
4797   switch(N->getOpcode()) {
4798   case X86ISD::BLENDI:
4799     ImmN = N->getOperand(N->getNumOperands()-1);
4800     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4801     break;
4802   case X86ISD::SHUFP:
4803     ImmN = N->getOperand(N->getNumOperands()-1);
4804     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4805     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4806     break;
4807   case X86ISD::INSERTPS:
4808     ImmN = N->getOperand(N->getNumOperands()-1);
4809     DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4810     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4811     break;
4812   case X86ISD::UNPCKH:
4813     DecodeUNPCKHMask(VT, Mask);
4814     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4815     break;
4816   case X86ISD::UNPCKL:
4817     DecodeUNPCKLMask(VT, Mask);
4818     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4819     break;
4820   case X86ISD::MOVHLPS:
4821     DecodeMOVHLPSMask(NumElems, Mask);
4822     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4823     break;
4824   case X86ISD::MOVLHPS:
4825     DecodeMOVLHPSMask(NumElems, Mask);
4826     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4827     break;
4828   case X86ISD::PALIGNR:
4829     ImmN = N->getOperand(N->getNumOperands()-1);
4830     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4831     break;
4832   case X86ISD::PSHUFD:
4833   case X86ISD::VPERMILPI:
4834     ImmN = N->getOperand(N->getNumOperands()-1);
4835     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4836     IsUnary = true;
4837     break;
4838   case X86ISD::PSHUFHW:
4839     ImmN = N->getOperand(N->getNumOperands()-1);
4840     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4841     IsUnary = true;
4842     break;
4843   case X86ISD::PSHUFLW:
4844     ImmN = N->getOperand(N->getNumOperands()-1);
4845     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4846     IsUnary = true;
4847     break;
4848   case X86ISD::PSHUFB: {
4849     IsUnary = true;
4850     SDValue MaskNode = N->getOperand(1);
4851     while (MaskNode->getOpcode() == ISD::BITCAST)
4852       MaskNode = MaskNode->getOperand(0);
4853
4854     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4855       // If we have a build-vector, then things are easy.
4856       MVT VT = MaskNode.getSimpleValueType();
4857       assert(VT.isVector() &&
4858              "Can't produce a non-vector with a build_vector!");
4859       if (!VT.isInteger())
4860         return false;
4861
4862       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4863
4864       SmallVector<uint64_t, 32> RawMask;
4865       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4866         SDValue Op = MaskNode->getOperand(i);
4867         if (Op->getOpcode() == ISD::UNDEF) {
4868           RawMask.push_back((uint64_t)SM_SentinelUndef);
4869           continue;
4870         }
4871         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4872         if (!CN)
4873           return false;
4874         APInt MaskElement = CN->getAPIntValue();
4875
4876         // We now have to decode the element which could be any integer size and
4877         // extract each byte of it.
4878         for (int j = 0; j < NumBytesPerElement; ++j) {
4879           // Note that this is x86 and so always little endian: the low byte is
4880           // the first byte of the mask.
4881           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4882           MaskElement = MaskElement.lshr(8);
4883         }
4884       }
4885       DecodePSHUFBMask(RawMask, Mask);
4886       break;
4887     }
4888
4889     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4890     if (!MaskLoad)
4891       return false;
4892
4893     SDValue Ptr = MaskLoad->getBasePtr();
4894     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4895         Ptr->getOpcode() == X86ISD::WrapperRIP)
4896       Ptr = Ptr->getOperand(0);
4897
4898     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4899     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4900       return false;
4901
4902     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4903       DecodePSHUFBMask(C, Mask);
4904       break;
4905     }
4906
4907     return false;
4908   }
4909   case X86ISD::VPERMI:
4910     ImmN = N->getOperand(N->getNumOperands()-1);
4911     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4912     IsUnary = true;
4913     break;
4914   case X86ISD::MOVSS:
4915   case X86ISD::MOVSD:
4916     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4917     break;
4918   case X86ISD::VPERM2X128:
4919     ImmN = N->getOperand(N->getNumOperands()-1);
4920     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4921     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4922     break;
4923   case X86ISD::MOVSLDUP:
4924     DecodeMOVSLDUPMask(VT, Mask);
4925     IsUnary = true;
4926     break;
4927   case X86ISD::MOVSHDUP:
4928     DecodeMOVSHDUPMask(VT, Mask);
4929     IsUnary = true;
4930     break;
4931   case X86ISD::MOVDDUP:
4932     DecodeMOVDDUPMask(VT, Mask);
4933     IsUnary = true;
4934     break;
4935   case X86ISD::MOVLHPD:
4936   case X86ISD::MOVLPD:
4937   case X86ISD::MOVLPS:
4938     // Not yet implemented
4939     return false;
4940   case X86ISD::VPERMV: {
4941     IsUnary = true;
4942     SDValue MaskNode = N->getOperand(0);
4943     while (MaskNode->getOpcode() == ISD::BITCAST)
4944       MaskNode = MaskNode->getOperand(0);
4945
4946     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4947     SmallVector<uint64_t, 32> RawMask;
4948     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4949       // If we have a build-vector, then things are easy.
4950       assert(MaskNode.getSimpleValueType().isInteger() &&
4951              MaskNode.getSimpleValueType().getVectorNumElements() ==
4952              VT.getVectorNumElements());
4953
4954       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4955         SDValue Op = MaskNode->getOperand(i);
4956         if (Op->getOpcode() == ISD::UNDEF)
4957           RawMask.push_back((uint64_t)SM_SentinelUndef);
4958         else if (isa<ConstantSDNode>(Op)) {
4959           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4960           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4961         } else
4962           return false;
4963       }
4964       DecodeVPERMVMask(RawMask, Mask);
4965       break;
4966     }
4967     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4968       unsigned NumEltsInMask = MaskNode->getNumOperands();
4969       MaskNode = MaskNode->getOperand(0);
4970       if (auto *CN = dyn_cast<ConstantSDNode>(MaskNode)) {
4971         APInt MaskEltValue = CN->getAPIntValue();
4972         for (unsigned i = 0; i < NumEltsInMask; ++i)
4973           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4974         DecodeVPERMVMask(RawMask, Mask);
4975         break;
4976       }
4977       // It may be a scalar load
4978     }
4979
4980     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4981     if (!MaskLoad)
4982       return false;
4983
4984     SDValue Ptr = MaskLoad->getBasePtr();
4985     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4986         Ptr->getOpcode() == X86ISD::WrapperRIP)
4987       Ptr = Ptr->getOperand(0);
4988
4989     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4990     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4991       return false;
4992
4993     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4994       DecodeVPERMVMask(C, VT, Mask);
4995       break;
4996     }
4997     return false;
4998   }
4999   case X86ISD::VPERMV3: {
5000     IsUnary = false;
5001     SDValue MaskNode = N->getOperand(1);
5002     while (MaskNode->getOpcode() == ISD::BITCAST)
5003       MaskNode = MaskNode->getOperand(1);
5004
5005     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5006       // If we have a build-vector, then things are easy.
5007       assert(MaskNode.getSimpleValueType().isInteger() &&
5008              MaskNode.getSimpleValueType().getVectorNumElements() ==
5009              VT.getVectorNumElements());
5010
5011       SmallVector<uint64_t, 32> RawMask;
5012       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
5013
5014       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
5015         SDValue Op = MaskNode->getOperand(i);
5016         if (Op->getOpcode() == ISD::UNDEF)
5017           RawMask.push_back((uint64_t)SM_SentinelUndef);
5018         else {
5019           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5020           if (!CN)
5021             return false;
5022           APInt MaskElement = CN->getAPIntValue();
5023           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
5024         }
5025       }
5026       DecodeVPERMV3Mask(RawMask, Mask);
5027       break;
5028     }
5029
5030     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5031     if (!MaskLoad)
5032       return false;
5033
5034     SDValue Ptr = MaskLoad->getBasePtr();
5035     if (Ptr->getOpcode() == X86ISD::Wrapper ||
5036         Ptr->getOpcode() == X86ISD::WrapperRIP)
5037       Ptr = Ptr->getOperand(0);
5038
5039     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5040     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5041       return false;
5042
5043     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5044       DecodeVPERMV3Mask(C, VT, Mask);
5045       break;
5046     }
5047     return false;
5048   }
5049   default: llvm_unreachable("unknown target shuffle node");
5050   }
5051
5052   // Empty mask indicates the decode failed.
5053   if (Mask.empty())
5054     return false;
5055
5056   // Check if we're getting a shuffle mask with zero'd elements.
5057   if (!AllowSentinelZero)
5058     if (std::any_of(Mask.begin(), Mask.end(),
5059                     [](int M){ return M == SM_SentinelZero; }))
5060       return false;
5061
5062   // If we have a fake unary shuffle, the shuffle mask is spread across two
5063   // inputs that are actually the same node. Re-map the mask to always point
5064   // into the first input.
5065   if (IsFakeUnary)
5066     for (int &M : Mask)
5067       if (M >= (int)Mask.size())
5068         M -= Mask.size();
5069
5070   return true;
5071 }
5072
5073 /// Returns the scalar element that will make up the ith
5074 /// element of the result of the vector shuffle.
5075 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5076                                    unsigned Depth) {
5077   if (Depth == 6)
5078     return SDValue();  // Limit search depth.
5079
5080   SDValue V = SDValue(N, 0);
5081   EVT VT = V.getValueType();
5082   unsigned Opcode = V.getOpcode();
5083
5084   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5085   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5086     int Elt = SV->getMaskElt(Index);
5087
5088     if (Elt < 0)
5089       return DAG.getUNDEF(VT.getVectorElementType());
5090
5091     unsigned NumElems = VT.getVectorNumElements();
5092     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5093                                          : SV->getOperand(1);
5094     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5095   }
5096
5097   // Recurse into target specific vector shuffles to find scalars.
5098   if (isTargetShuffle(Opcode)) {
5099     MVT ShufVT = V.getSimpleValueType();
5100     int NumElems = (int)ShufVT.getVectorNumElements();
5101     SmallVector<int, 16> ShuffleMask;
5102     bool IsUnary;
5103
5104     if (!getTargetShuffleMask(N, ShufVT, false, ShuffleMask, IsUnary))
5105       return SDValue();
5106
5107     int Elt = ShuffleMask[Index];
5108     if (Elt == SM_SentinelUndef)
5109       return DAG.getUNDEF(ShufVT.getVectorElementType());
5110
5111     assert(0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range");
5112     SDValue NewV = (Elt < NumElems) ? N->getOperand(0) : N->getOperand(1);
5113     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5114                                Depth+1);
5115   }
5116
5117   // Actual nodes that may contain scalar elements
5118   if (Opcode == ISD::BITCAST) {
5119     V = V.getOperand(0);
5120     EVT SrcVT = V.getValueType();
5121     unsigned NumElems = VT.getVectorNumElements();
5122
5123     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5124       return SDValue();
5125   }
5126
5127   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5128     return (Index == 0) ? V.getOperand(0)
5129                         : DAG.getUNDEF(VT.getVectorElementType());
5130
5131   if (V.getOpcode() == ISD::BUILD_VECTOR)
5132     return V.getOperand(Index);
5133
5134   return SDValue();
5135 }
5136
5137 /// Custom lower build_vector of v16i8.
5138 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5139                                        unsigned NumNonZero, unsigned NumZero,
5140                                        SelectionDAG &DAG,
5141                                        const X86Subtarget* Subtarget,
5142                                        const TargetLowering &TLI) {
5143   if (NumNonZero > 8)
5144     return SDValue();
5145
5146   SDLoc dl(Op);
5147   SDValue V;
5148   bool First = true;
5149
5150   // SSE4.1 - use PINSRB to insert each byte directly.
5151   if (Subtarget->hasSSE41()) {
5152     for (unsigned i = 0; i < 16; ++i) {
5153       bool isNonZero = (NonZeros & (1 << i)) != 0;
5154       if (isNonZero) {
5155         if (First) {
5156           if (NumZero)
5157             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5158           else
5159             V = DAG.getUNDEF(MVT::v16i8);
5160           First = false;
5161         }
5162         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5163                         MVT::v16i8, V, Op.getOperand(i),
5164                         DAG.getIntPtrConstant(i, dl));
5165       }
5166     }
5167
5168     return V;
5169   }
5170
5171   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5172   for (unsigned i = 0; i < 16; ++i) {
5173     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5174     if (ThisIsNonZero && First) {
5175       if (NumZero)
5176         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5177       else
5178         V = DAG.getUNDEF(MVT::v8i16);
5179       First = false;
5180     }
5181
5182     if ((i & 1) != 0) {
5183       SDValue ThisElt, LastElt;
5184       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5185       if (LastIsNonZero) {
5186         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5187                               MVT::i16, Op.getOperand(i-1));
5188       }
5189       if (ThisIsNonZero) {
5190         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5191         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5192                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
5193         if (LastIsNonZero)
5194           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5195       } else
5196         ThisElt = LastElt;
5197
5198       if (ThisElt.getNode())
5199         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5200                         DAG.getIntPtrConstant(i/2, dl));
5201     }
5202   }
5203
5204   return DAG.getBitcast(MVT::v16i8, V);
5205 }
5206
5207 /// Custom lower build_vector of v8i16.
5208 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5209                                      unsigned NumNonZero, unsigned NumZero,
5210                                      SelectionDAG &DAG,
5211                                      const X86Subtarget* Subtarget,
5212                                      const TargetLowering &TLI) {
5213   if (NumNonZero > 4)
5214     return SDValue();
5215
5216   SDLoc dl(Op);
5217   SDValue V;
5218   bool First = true;
5219   for (unsigned i = 0; i < 8; ++i) {
5220     bool isNonZero = (NonZeros & (1 << i)) != 0;
5221     if (isNonZero) {
5222       if (First) {
5223         if (NumZero)
5224           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5225         else
5226           V = DAG.getUNDEF(MVT::v8i16);
5227         First = false;
5228       }
5229       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5230                       MVT::v8i16, V, Op.getOperand(i),
5231                       DAG.getIntPtrConstant(i, dl));
5232     }
5233   }
5234
5235   return V;
5236 }
5237
5238 /// Custom lower build_vector of v4i32 or v4f32.
5239 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5240                                      const X86Subtarget *Subtarget,
5241                                      const TargetLowering &TLI) {
5242   // Find all zeroable elements.
5243   std::bitset<4> Zeroable;
5244   for (int i=0; i < 4; ++i) {
5245     SDValue Elt = Op->getOperand(i);
5246     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5247   }
5248   assert(Zeroable.size() - Zeroable.count() > 1 &&
5249          "We expect at least two non-zero elements!");
5250
5251   // We only know how to deal with build_vector nodes where elements are either
5252   // zeroable or extract_vector_elt with constant index.
5253   SDValue FirstNonZero;
5254   unsigned FirstNonZeroIdx;
5255   for (unsigned i=0; i < 4; ++i) {
5256     if (Zeroable[i])
5257       continue;
5258     SDValue Elt = Op->getOperand(i);
5259     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5260         !isa<ConstantSDNode>(Elt.getOperand(1)))
5261       return SDValue();
5262     // Make sure that this node is extracting from a 128-bit vector.
5263     MVT VT = Elt.getOperand(0).getSimpleValueType();
5264     if (!VT.is128BitVector())
5265       return SDValue();
5266     if (!FirstNonZero.getNode()) {
5267       FirstNonZero = Elt;
5268       FirstNonZeroIdx = i;
5269     }
5270   }
5271
5272   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5273   SDValue V1 = FirstNonZero.getOperand(0);
5274   MVT VT = V1.getSimpleValueType();
5275
5276   // See if this build_vector can be lowered as a blend with zero.
5277   SDValue Elt;
5278   unsigned EltMaskIdx, EltIdx;
5279   int Mask[4];
5280   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5281     if (Zeroable[EltIdx]) {
5282       // The zero vector will be on the right hand side.
5283       Mask[EltIdx] = EltIdx+4;
5284       continue;
5285     }
5286
5287     Elt = Op->getOperand(EltIdx);
5288     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5289     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5290     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5291       break;
5292     Mask[EltIdx] = EltIdx;
5293   }
5294
5295   if (EltIdx == 4) {
5296     // Let the shuffle legalizer deal with blend operations.
5297     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5298     if (V1.getSimpleValueType() != VT)
5299       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5300     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5301   }
5302
5303   // See if we can lower this build_vector to a INSERTPS.
5304   if (!Subtarget->hasSSE41())
5305     return SDValue();
5306
5307   SDValue V2 = Elt.getOperand(0);
5308   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5309     V1 = SDValue();
5310
5311   bool CanFold = true;
5312   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5313     if (Zeroable[i])
5314       continue;
5315
5316     SDValue Current = Op->getOperand(i);
5317     SDValue SrcVector = Current->getOperand(0);
5318     if (!V1.getNode())
5319       V1 = SrcVector;
5320     CanFold = SrcVector == V1 &&
5321       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5322   }
5323
5324   if (!CanFold)
5325     return SDValue();
5326
5327   assert(V1.getNode() && "Expected at least two non-zero elements!");
5328   if (V1.getSimpleValueType() != MVT::v4f32)
5329     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5330   if (V2.getSimpleValueType() != MVT::v4f32)
5331     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5332
5333   // Ok, we can emit an INSERTPS instruction.
5334   unsigned ZMask = Zeroable.to_ulong();
5335
5336   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5337   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5338   SDLoc DL(Op);
5339   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5340                                DAG.getIntPtrConstant(InsertPSMask, DL));
5341   return DAG.getBitcast(VT, Result);
5342 }
5343
5344 /// Return a vector logical shift node.
5345 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5346                          unsigned NumBits, SelectionDAG &DAG,
5347                          const TargetLowering &TLI, SDLoc dl) {
5348   assert(VT.is128BitVector() && "Unknown type for VShift");
5349   MVT ShVT = MVT::v2i64;
5350   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5351   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5352   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5353   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5354   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5355   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5356 }
5357
5358 static SDValue
5359 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5360
5361   // Check if the scalar load can be widened into a vector load. And if
5362   // the address is "base + cst" see if the cst can be "absorbed" into
5363   // the shuffle mask.
5364   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5365     SDValue Ptr = LD->getBasePtr();
5366     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5367       return SDValue();
5368     EVT PVT = LD->getValueType(0);
5369     if (PVT != MVT::i32 && PVT != MVT::f32)
5370       return SDValue();
5371
5372     int FI = -1;
5373     int64_t Offset = 0;
5374     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5375       FI = FINode->getIndex();
5376       Offset = 0;
5377     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5378                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5379       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5380       Offset = Ptr.getConstantOperandVal(1);
5381       Ptr = Ptr.getOperand(0);
5382     } else {
5383       return SDValue();
5384     }
5385
5386     // FIXME: 256-bit vector instructions don't require a strict alignment,
5387     // improve this code to support it better.
5388     unsigned RequiredAlign = VT.getSizeInBits()/8;
5389     SDValue Chain = LD->getChain();
5390     // Make sure the stack object alignment is at least 16 or 32.
5391     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5392     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5393       if (MFI->isFixedObjectIndex(FI)) {
5394         // Can't change the alignment. FIXME: It's possible to compute
5395         // the exact stack offset and reference FI + adjust offset instead.
5396         // If someone *really* cares about this. That's the way to implement it.
5397         return SDValue();
5398       } else {
5399         MFI->setObjectAlignment(FI, RequiredAlign);
5400       }
5401     }
5402
5403     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5404     // Ptr + (Offset & ~15).
5405     if (Offset < 0)
5406       return SDValue();
5407     if ((Offset % RequiredAlign) & 3)
5408       return SDValue();
5409     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5410     if (StartOffset) {
5411       SDLoc DL(Ptr);
5412       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5413                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5414     }
5415
5416     int EltNo = (Offset - StartOffset) >> 2;
5417     unsigned NumElems = VT.getVectorNumElements();
5418
5419     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5420     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5421                              LD->getPointerInfo().getWithOffset(StartOffset),
5422                              false, false, false, 0);
5423
5424     SmallVector<int, 8> Mask(NumElems, EltNo);
5425
5426     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5427   }
5428
5429   return SDValue();
5430 }
5431
5432 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5433 /// elements can be replaced by a single large load which has the same value as
5434 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5435 ///
5436 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5437 ///
5438 /// FIXME: we'd also like to handle the case where the last elements are zero
5439 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5440 /// There's even a handy isZeroNode for that purpose.
5441 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5442                                         SDLoc &DL, SelectionDAG &DAG,
5443                                         bool isAfterLegalize) {
5444   unsigned NumElems = Elts.size();
5445
5446   LoadSDNode *LDBase = nullptr;
5447   unsigned LastLoadedElt = -1U;
5448
5449   // For each element in the initializer, see if we've found a load or an undef.
5450   // If we don't find an initial load element, or later load elements are
5451   // non-consecutive, bail out.
5452   for (unsigned i = 0; i < NumElems; ++i) {
5453     SDValue Elt = Elts[i];
5454     // Look through a bitcast.
5455     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5456       Elt = Elt.getOperand(0);
5457     if (!Elt.getNode() ||
5458         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5459       return SDValue();
5460     if (!LDBase) {
5461       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5462         return SDValue();
5463       LDBase = cast<LoadSDNode>(Elt.getNode());
5464       LastLoadedElt = i;
5465       continue;
5466     }
5467     if (Elt.getOpcode() == ISD::UNDEF)
5468       continue;
5469
5470     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5471     EVT LdVT = Elt.getValueType();
5472     // Each loaded element must be the correct fractional portion of the
5473     // requested vector load.
5474     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5475       return SDValue();
5476     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5477       return SDValue();
5478     LastLoadedElt = i;
5479   }
5480
5481   // If we have found an entire vector of loads and undefs, then return a large
5482   // load of the entire vector width starting at the base pointer.  If we found
5483   // consecutive loads for the low half, generate a vzext_load node.
5484   if (LastLoadedElt == NumElems - 1) {
5485     assert(LDBase && "Did not find base load for merging consecutive loads");
5486     EVT EltVT = LDBase->getValueType(0);
5487     // Ensure that the input vector size for the merged loads matches the
5488     // cumulative size of the input elements.
5489     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5490       return SDValue();
5491
5492     if (isAfterLegalize &&
5493         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5494       return SDValue();
5495
5496     SDValue NewLd = SDValue();
5497
5498     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5499                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5500                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5501                         LDBase->getAlignment());
5502
5503     if (LDBase->hasAnyUseOfValue(1)) {
5504       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5505                                      SDValue(LDBase, 1),
5506                                      SDValue(NewLd.getNode(), 1));
5507       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5508       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5509                              SDValue(NewLd.getNode(), 1));
5510     }
5511
5512     return NewLd;
5513   }
5514
5515   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5516   //of a v4i32 / v4f32. It's probably worth generalizing.
5517   EVT EltVT = VT.getVectorElementType();
5518   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5519       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5520     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5521     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5522     SDValue ResNode =
5523         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5524                                 LDBase->getPointerInfo(),
5525                                 LDBase->getAlignment(),
5526                                 false/*isVolatile*/, true/*ReadMem*/,
5527                                 false/*WriteMem*/);
5528
5529     // Make sure the newly-created LOAD is in the same position as LDBase in
5530     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5531     // update uses of LDBase's output chain to use the TokenFactor.
5532     if (LDBase->hasAnyUseOfValue(1)) {
5533       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5534                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5535       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5536       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5537                              SDValue(ResNode.getNode(), 1));
5538     }
5539
5540     return DAG.getBitcast(VT, ResNode);
5541   }
5542   return SDValue();
5543 }
5544
5545 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5546 /// to generate a splat value for the following cases:
5547 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5548 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5549 /// a scalar load, or a constant.
5550 /// The VBROADCAST node is returned when a pattern is found,
5551 /// or SDValue() otherwise.
5552 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5553                                     SelectionDAG &DAG) {
5554   // VBROADCAST requires AVX.
5555   // TODO: Splats could be generated for non-AVX CPUs using SSE
5556   // instructions, but there's less potential gain for only 128-bit vectors.
5557   if (!Subtarget->hasAVX())
5558     return SDValue();
5559
5560   MVT VT = Op.getSimpleValueType();
5561   SDLoc dl(Op);
5562
5563   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5564          "Unsupported vector type for broadcast.");
5565
5566   SDValue Ld;
5567   bool ConstSplatVal;
5568
5569   switch (Op.getOpcode()) {
5570     default:
5571       // Unknown pattern found.
5572       return SDValue();
5573
5574     case ISD::BUILD_VECTOR: {
5575       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5576       BitVector UndefElements;
5577       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5578
5579       // We need a splat of a single value to use broadcast, and it doesn't
5580       // make any sense if the value is only in one element of the vector.
5581       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5582         return SDValue();
5583
5584       Ld = Splat;
5585       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5586                        Ld.getOpcode() == ISD::ConstantFP);
5587
5588       // Make sure that all of the users of a non-constant load are from the
5589       // BUILD_VECTOR node.
5590       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5591         return SDValue();
5592       break;
5593     }
5594
5595     case ISD::VECTOR_SHUFFLE: {
5596       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5597
5598       // Shuffles must have a splat mask where the first element is
5599       // broadcasted.
5600       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5601         return SDValue();
5602
5603       SDValue Sc = Op.getOperand(0);
5604       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5605           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5606
5607         if (!Subtarget->hasInt256())
5608           return SDValue();
5609
5610         // Use the register form of the broadcast instruction available on AVX2.
5611         if (VT.getSizeInBits() >= 256)
5612           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5613         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5614       }
5615
5616       Ld = Sc.getOperand(0);
5617       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5618                        Ld.getOpcode() == ISD::ConstantFP);
5619
5620       // The scalar_to_vector node and the suspected
5621       // load node must have exactly one user.
5622       // Constants may have multiple users.
5623
5624       // AVX-512 has register version of the broadcast
5625       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5626         Ld.getValueType().getSizeInBits() >= 32;
5627       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5628           !hasRegVer))
5629         return SDValue();
5630       break;
5631     }
5632   }
5633
5634   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5635   bool IsGE256 = (VT.getSizeInBits() >= 256);
5636
5637   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5638   // instruction to save 8 or more bytes of constant pool data.
5639   // TODO: If multiple splats are generated to load the same constant,
5640   // it may be detrimental to overall size. There needs to be a way to detect
5641   // that condition to know if this is truly a size win.
5642   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5643
5644   // Handle broadcasting a single constant scalar from the constant pool
5645   // into a vector.
5646   // On Sandybridge (no AVX2), it is still better to load a constant vector
5647   // from the constant pool and not to broadcast it from a scalar.
5648   // But override that restriction when optimizing for size.
5649   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5650   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5651     EVT CVT = Ld.getValueType();
5652     assert(!CVT.isVector() && "Must not broadcast a vector type");
5653
5654     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5655     // For size optimization, also splat v2f64 and v2i64, and for size opt
5656     // with AVX2, also splat i8 and i16.
5657     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5658     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5659         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5660       const Constant *C = nullptr;
5661       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5662         C = CI->getConstantIntValue();
5663       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5664         C = CF->getConstantFPValue();
5665
5666       assert(C && "Invalid constant type");
5667
5668       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5669       SDValue CP =
5670           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5671       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5672       Ld = DAG.getLoad(
5673           CVT, dl, DAG.getEntryNode(), CP,
5674           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5675           false, false, Alignment);
5676
5677       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5678     }
5679   }
5680
5681   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5682
5683   // Handle AVX2 in-register broadcasts.
5684   if (!IsLoad && Subtarget->hasInt256() &&
5685       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5686     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5687
5688   // The scalar source must be a normal load.
5689   if (!IsLoad)
5690     return SDValue();
5691
5692   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5693       (Subtarget->hasVLX() && ScalarSize == 64))
5694     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5695
5696   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5697   // double since there is no vbroadcastsd xmm
5698   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5699     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5700       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5701   }
5702
5703   // Unsupported broadcast.
5704   return SDValue();
5705 }
5706
5707 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5708 /// underlying vector and index.
5709 ///
5710 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5711 /// index.
5712 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5713                                          SDValue ExtIdx) {
5714   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5715   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5716     return Idx;
5717
5718   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5719   // lowered this:
5720   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5721   // to:
5722   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5723   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5724   //                           undef)
5725   //                       Constant<0>)
5726   // In this case the vector is the extract_subvector expression and the index
5727   // is 2, as specified by the shuffle.
5728   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5729   SDValue ShuffleVec = SVOp->getOperand(0);
5730   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5731   assert(ShuffleVecVT.getVectorElementType() ==
5732          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5733
5734   int ShuffleIdx = SVOp->getMaskElt(Idx);
5735   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5736     ExtractedFromVec = ShuffleVec;
5737     return ShuffleIdx;
5738   }
5739   return Idx;
5740 }
5741
5742 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5743   MVT VT = Op.getSimpleValueType();
5744
5745   // Skip if insert_vec_elt is not supported.
5746   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5747   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5748     return SDValue();
5749
5750   SDLoc DL(Op);
5751   unsigned NumElems = Op.getNumOperands();
5752
5753   SDValue VecIn1;
5754   SDValue VecIn2;
5755   SmallVector<unsigned, 4> InsertIndices;
5756   SmallVector<int, 8> Mask(NumElems, -1);
5757
5758   for (unsigned i = 0; i != NumElems; ++i) {
5759     unsigned Opc = Op.getOperand(i).getOpcode();
5760
5761     if (Opc == ISD::UNDEF)
5762       continue;
5763
5764     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5765       // Quit if more than 1 elements need inserting.
5766       if (InsertIndices.size() > 1)
5767         return SDValue();
5768
5769       InsertIndices.push_back(i);
5770       continue;
5771     }
5772
5773     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5774     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5775     // Quit if non-constant index.
5776     if (!isa<ConstantSDNode>(ExtIdx))
5777       return SDValue();
5778     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5779
5780     // Quit if extracted from vector of different type.
5781     if (ExtractedFromVec.getValueType() != VT)
5782       return SDValue();
5783
5784     if (!VecIn1.getNode())
5785       VecIn1 = ExtractedFromVec;
5786     else if (VecIn1 != ExtractedFromVec) {
5787       if (!VecIn2.getNode())
5788         VecIn2 = ExtractedFromVec;
5789       else if (VecIn2 != ExtractedFromVec)
5790         // Quit if more than 2 vectors to shuffle
5791         return SDValue();
5792     }
5793
5794     if (ExtractedFromVec == VecIn1)
5795       Mask[i] = Idx;
5796     else if (ExtractedFromVec == VecIn2)
5797       Mask[i] = Idx + NumElems;
5798   }
5799
5800   if (!VecIn1.getNode())
5801     return SDValue();
5802
5803   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5804   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5805   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5806     unsigned Idx = InsertIndices[i];
5807     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5808                      DAG.getIntPtrConstant(Idx, DL));
5809   }
5810
5811   return NV;
5812 }
5813
5814 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5815   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5816          Op.getScalarValueSizeInBits() == 1 &&
5817          "Can not convert non-constant vector");
5818   uint64_t Immediate = 0;
5819   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5820     SDValue In = Op.getOperand(idx);
5821     if (In.getOpcode() != ISD::UNDEF)
5822       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5823   }
5824   SDLoc dl(Op);
5825   MVT VT =
5826    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5827   return DAG.getConstant(Immediate, dl, VT);
5828 }
5829 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5830 SDValue
5831 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5832
5833   MVT VT = Op.getSimpleValueType();
5834   assert((VT.getVectorElementType() == MVT::i1) &&
5835          "Unexpected type in LowerBUILD_VECTORvXi1!");
5836
5837   SDLoc dl(Op);
5838   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5839     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5840     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5841     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5842   }
5843
5844   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5845     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5846     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5847     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5848   }
5849
5850   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5851     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5852     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5853       return DAG.getBitcast(VT, Imm);
5854     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5855     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5856                         DAG.getIntPtrConstant(0, dl));
5857   }
5858
5859   // Vector has one or more non-const elements
5860   uint64_t Immediate = 0;
5861   SmallVector<unsigned, 16> NonConstIdx;
5862   bool IsSplat = true;
5863   bool HasConstElts = false;
5864   int SplatIdx = -1;
5865   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5866     SDValue In = Op.getOperand(idx);
5867     if (In.getOpcode() == ISD::UNDEF)
5868       continue;
5869     if (!isa<ConstantSDNode>(In))
5870       NonConstIdx.push_back(idx);
5871     else {
5872       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5873       HasConstElts = true;
5874     }
5875     if (SplatIdx == -1)
5876       SplatIdx = idx;
5877     else if (In != Op.getOperand(SplatIdx))
5878       IsSplat = false;
5879   }
5880
5881   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5882   if (IsSplat)
5883     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5884                        DAG.getConstant(1, dl, VT),
5885                        DAG.getConstant(0, dl, VT));
5886
5887   // insert elements one by one
5888   SDValue DstVec;
5889   SDValue Imm;
5890   if (Immediate) {
5891     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5892     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5893   }
5894   else if (HasConstElts)
5895     Imm = DAG.getConstant(0, dl, VT);
5896   else
5897     Imm = DAG.getUNDEF(VT);
5898   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5899     DstVec = DAG.getBitcast(VT, Imm);
5900   else {
5901     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5902     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5903                          DAG.getIntPtrConstant(0, dl));
5904   }
5905
5906   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5907     unsigned InsertIdx = NonConstIdx[i];
5908     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5909                          Op.getOperand(InsertIdx),
5910                          DAG.getIntPtrConstant(InsertIdx, dl));
5911   }
5912   return DstVec;
5913 }
5914
5915 /// \brief Return true if \p N implements a horizontal binop and return the
5916 /// operands for the horizontal binop into V0 and V1.
5917 ///
5918 /// This is a helper function of LowerToHorizontalOp().
5919 /// This function checks that the build_vector \p N in input implements a
5920 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5921 /// operation to match.
5922 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5923 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5924 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5925 /// arithmetic sub.
5926 ///
5927 /// This function only analyzes elements of \p N whose indices are
5928 /// in range [BaseIdx, LastIdx).
5929 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5930                               SelectionDAG &DAG,
5931                               unsigned BaseIdx, unsigned LastIdx,
5932                               SDValue &V0, SDValue &V1) {
5933   EVT VT = N->getValueType(0);
5934
5935   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5936   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5937          "Invalid Vector in input!");
5938
5939   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5940   bool CanFold = true;
5941   unsigned ExpectedVExtractIdx = BaseIdx;
5942   unsigned NumElts = LastIdx - BaseIdx;
5943   V0 = DAG.getUNDEF(VT);
5944   V1 = DAG.getUNDEF(VT);
5945
5946   // Check if N implements a horizontal binop.
5947   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5948     SDValue Op = N->getOperand(i + BaseIdx);
5949
5950     // Skip UNDEFs.
5951     if (Op->getOpcode() == ISD::UNDEF) {
5952       // Update the expected vector extract index.
5953       if (i * 2 == NumElts)
5954         ExpectedVExtractIdx = BaseIdx;
5955       ExpectedVExtractIdx += 2;
5956       continue;
5957     }
5958
5959     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5960
5961     if (!CanFold)
5962       break;
5963
5964     SDValue Op0 = Op.getOperand(0);
5965     SDValue Op1 = Op.getOperand(1);
5966
5967     // Try to match the following pattern:
5968     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5969     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5970         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5971         Op0.getOperand(0) == Op1.getOperand(0) &&
5972         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5973         isa<ConstantSDNode>(Op1.getOperand(1)));
5974     if (!CanFold)
5975       break;
5976
5977     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5978     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5979
5980     if (i * 2 < NumElts) {
5981       if (V0.getOpcode() == ISD::UNDEF) {
5982         V0 = Op0.getOperand(0);
5983         if (V0.getValueType() != VT)
5984           return false;
5985       }
5986     } else {
5987       if (V1.getOpcode() == ISD::UNDEF) {
5988         V1 = Op0.getOperand(0);
5989         if (V1.getValueType() != VT)
5990           return false;
5991       }
5992       if (i * 2 == NumElts)
5993         ExpectedVExtractIdx = BaseIdx;
5994     }
5995
5996     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5997     if (I0 == ExpectedVExtractIdx)
5998       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5999     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6000       // Try to match the following dag sequence:
6001       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6002       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6003     } else
6004       CanFold = false;
6005
6006     ExpectedVExtractIdx += 2;
6007   }
6008
6009   return CanFold;
6010 }
6011
6012 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6013 /// a concat_vector.
6014 ///
6015 /// This is a helper function of LowerToHorizontalOp().
6016 /// This function expects two 256-bit vectors called V0 and V1.
6017 /// At first, each vector is split into two separate 128-bit vectors.
6018 /// Then, the resulting 128-bit vectors are used to implement two
6019 /// horizontal binary operations.
6020 ///
6021 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6022 ///
6023 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6024 /// the two new horizontal binop.
6025 /// When Mode is set, the first horizontal binop dag node would take as input
6026 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6027 /// horizontal binop dag node would take as input the lower 128-bit of V1
6028 /// and the upper 128-bit of V1.
6029 ///   Example:
6030 ///     HADD V0_LO, V0_HI
6031 ///     HADD V1_LO, V1_HI
6032 ///
6033 /// Otherwise, the first horizontal binop dag node takes as input the lower
6034 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6035 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
6036 ///   Example:
6037 ///     HADD V0_LO, V1_LO
6038 ///     HADD V0_HI, V1_HI
6039 ///
6040 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6041 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6042 /// the upper 128-bits of the result.
6043 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6044                                      SDLoc DL, SelectionDAG &DAG,
6045                                      unsigned X86Opcode, bool Mode,
6046                                      bool isUndefLO, bool isUndefHI) {
6047   EVT VT = V0.getValueType();
6048   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6049          "Invalid nodes in input!");
6050
6051   unsigned NumElts = VT.getVectorNumElements();
6052   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6053   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6054   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6055   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6056   EVT NewVT = V0_LO.getValueType();
6057
6058   SDValue LO = DAG.getUNDEF(NewVT);
6059   SDValue HI = DAG.getUNDEF(NewVT);
6060
6061   if (Mode) {
6062     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6063     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6064       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6065     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6066       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6067   } else {
6068     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6069     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6070                        V1_LO->getOpcode() != ISD::UNDEF))
6071       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6072
6073     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6074                        V1_HI->getOpcode() != ISD::UNDEF))
6075       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6076   }
6077
6078   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6079 }
6080
6081 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6082 /// node.
6083 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6084                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6085   MVT VT = BV->getSimpleValueType(0);
6086   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6087       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6088     return SDValue();
6089
6090   SDLoc DL(BV);
6091   unsigned NumElts = VT.getVectorNumElements();
6092   SDValue InVec0 = DAG.getUNDEF(VT);
6093   SDValue InVec1 = DAG.getUNDEF(VT);
6094
6095   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6096           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6097
6098   // Odd-numbered elements in the input build vector are obtained from
6099   // adding two integer/float elements.
6100   // Even-numbered elements in the input build vector are obtained from
6101   // subtracting two integer/float elements.
6102   unsigned ExpectedOpcode = ISD::FSUB;
6103   unsigned NextExpectedOpcode = ISD::FADD;
6104   bool AddFound = false;
6105   bool SubFound = false;
6106
6107   for (unsigned i = 0, e = NumElts; i != e; ++i) {
6108     SDValue Op = BV->getOperand(i);
6109
6110     // Skip 'undef' values.
6111     unsigned Opcode = Op.getOpcode();
6112     if (Opcode == ISD::UNDEF) {
6113       std::swap(ExpectedOpcode, NextExpectedOpcode);
6114       continue;
6115     }
6116
6117     // Early exit if we found an unexpected opcode.
6118     if (Opcode != ExpectedOpcode)
6119       return SDValue();
6120
6121     SDValue Op0 = Op.getOperand(0);
6122     SDValue Op1 = Op.getOperand(1);
6123
6124     // Try to match the following pattern:
6125     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6126     // Early exit if we cannot match that sequence.
6127     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6128         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6129         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6130         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6131         Op0.getOperand(1) != Op1.getOperand(1))
6132       return SDValue();
6133
6134     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6135     if (I0 != i)
6136       return SDValue();
6137
6138     // We found a valid add/sub node. Update the information accordingly.
6139     if (i & 1)
6140       AddFound = true;
6141     else
6142       SubFound = true;
6143
6144     // Update InVec0 and InVec1.
6145     if (InVec0.getOpcode() == ISD::UNDEF) {
6146       InVec0 = Op0.getOperand(0);
6147       if (InVec0.getSimpleValueType() != VT)
6148         return SDValue();
6149     }
6150     if (InVec1.getOpcode() == ISD::UNDEF) {
6151       InVec1 = Op1.getOperand(0);
6152       if (InVec1.getSimpleValueType() != VT)
6153         return SDValue();
6154     }
6155
6156     // Make sure that operands in input to each add/sub node always
6157     // come from a same pair of vectors.
6158     if (InVec0 != Op0.getOperand(0)) {
6159       if (ExpectedOpcode == ISD::FSUB)
6160         return SDValue();
6161
6162       // FADD is commutable. Try to commute the operands
6163       // and then test again.
6164       std::swap(Op0, Op1);
6165       if (InVec0 != Op0.getOperand(0))
6166         return SDValue();
6167     }
6168
6169     if (InVec1 != Op1.getOperand(0))
6170       return SDValue();
6171
6172     // Update the pair of expected opcodes.
6173     std::swap(ExpectedOpcode, NextExpectedOpcode);
6174   }
6175
6176   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6177   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6178       InVec1.getOpcode() != ISD::UNDEF)
6179     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6180
6181   return SDValue();
6182 }
6183
6184 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6185 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6186                                    const X86Subtarget *Subtarget,
6187                                    SelectionDAG &DAG) {
6188   MVT VT = BV->getSimpleValueType(0);
6189   unsigned NumElts = VT.getVectorNumElements();
6190   unsigned NumUndefsLO = 0;
6191   unsigned NumUndefsHI = 0;
6192   unsigned Half = NumElts/2;
6193
6194   // Count the number of UNDEF operands in the build_vector in input.
6195   for (unsigned i = 0, e = Half; i != e; ++i)
6196     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6197       NumUndefsLO++;
6198
6199   for (unsigned i = Half, e = NumElts; i != e; ++i)
6200     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6201       NumUndefsHI++;
6202
6203   // Early exit if this is either a build_vector of all UNDEFs or all the
6204   // operands but one are UNDEF.
6205   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6206     return SDValue();
6207
6208   SDLoc DL(BV);
6209   SDValue InVec0, InVec1;
6210   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6211     // Try to match an SSE3 float HADD/HSUB.
6212     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6213       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6214
6215     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6216       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6217   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6218     // Try to match an SSSE3 integer HADD/HSUB.
6219     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6220       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6221
6222     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6223       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6224   }
6225
6226   if (!Subtarget->hasAVX())
6227     return SDValue();
6228
6229   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6230     // Try to match an AVX horizontal add/sub of packed single/double
6231     // precision floating point values from 256-bit vectors.
6232     SDValue InVec2, InVec3;
6233     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6234         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6235         ((InVec0.getOpcode() == ISD::UNDEF ||
6236           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6237         ((InVec1.getOpcode() == ISD::UNDEF ||
6238           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6239       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6240
6241     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6242         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6243         ((InVec0.getOpcode() == ISD::UNDEF ||
6244           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6245         ((InVec1.getOpcode() == ISD::UNDEF ||
6246           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6247       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6248   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6249     // Try to match an AVX2 horizontal add/sub of signed integers.
6250     SDValue InVec2, InVec3;
6251     unsigned X86Opcode;
6252     bool CanFold = true;
6253
6254     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6255         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6256         ((InVec0.getOpcode() == ISD::UNDEF ||
6257           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6258         ((InVec1.getOpcode() == ISD::UNDEF ||
6259           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6260       X86Opcode = X86ISD::HADD;
6261     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6262         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6263         ((InVec0.getOpcode() == ISD::UNDEF ||
6264           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6265         ((InVec1.getOpcode() == ISD::UNDEF ||
6266           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6267       X86Opcode = X86ISD::HSUB;
6268     else
6269       CanFold = false;
6270
6271     if (CanFold) {
6272       // Fold this build_vector into a single horizontal add/sub.
6273       // Do this only if the target has AVX2.
6274       if (Subtarget->hasAVX2())
6275         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6276
6277       // Do not try to expand this build_vector into a pair of horizontal
6278       // add/sub if we can emit a pair of scalar add/sub.
6279       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6280         return SDValue();
6281
6282       // Convert this build_vector into a pair of horizontal binop followed by
6283       // a concat vector.
6284       bool isUndefLO = NumUndefsLO == Half;
6285       bool isUndefHI = NumUndefsHI == Half;
6286       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6287                                    isUndefLO, isUndefHI);
6288     }
6289   }
6290
6291   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6292        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6293     unsigned X86Opcode;
6294     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6295       X86Opcode = X86ISD::HADD;
6296     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6297       X86Opcode = X86ISD::HSUB;
6298     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6299       X86Opcode = X86ISD::FHADD;
6300     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6301       X86Opcode = X86ISD::FHSUB;
6302     else
6303       return SDValue();
6304
6305     // Don't try to expand this build_vector into a pair of horizontal add/sub
6306     // if we can simply emit a pair of scalar add/sub.
6307     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6308       return SDValue();
6309
6310     // Convert this build_vector into two horizontal add/sub followed by
6311     // a concat vector.
6312     bool isUndefLO = NumUndefsLO == Half;
6313     bool isUndefHI = NumUndefsHI == Half;
6314     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6315                                  isUndefLO, isUndefHI);
6316   }
6317
6318   return SDValue();
6319 }
6320
6321 SDValue
6322 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6323   SDLoc dl(Op);
6324
6325   MVT VT = Op.getSimpleValueType();
6326   MVT ExtVT = VT.getVectorElementType();
6327   unsigned NumElems = Op.getNumOperands();
6328
6329   // Generate vectors for predicate vectors.
6330   if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6331     return LowerBUILD_VECTORvXi1(Op, DAG);
6332
6333   // Vectors containing all zeros can be matched by pxor and xorps later
6334   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6335     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6336     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6337     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6338       return Op;
6339
6340     return getZeroVector(VT, Subtarget, DAG, dl);
6341   }
6342
6343   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6344   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6345   // vpcmpeqd on 256-bit vectors.
6346   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6347     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6348       return Op;
6349
6350     if (!VT.is512BitVector())
6351       return getOnesVector(VT, Subtarget, DAG, dl);
6352   }
6353
6354   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6355   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6356     return AddSub;
6357   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6358     return HorizontalOp;
6359   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6360     return Broadcast;
6361
6362   unsigned EVTBits = ExtVT.getSizeInBits();
6363
6364   unsigned NumZero  = 0;
6365   unsigned NumNonZero = 0;
6366   uint64_t NonZeros = 0;
6367   bool IsAllConstants = true;
6368   SmallSet<SDValue, 8> Values;
6369   for (unsigned i = 0; i < NumElems; ++i) {
6370     SDValue Elt = Op.getOperand(i);
6371     if (Elt.getOpcode() == ISD::UNDEF)
6372       continue;
6373     Values.insert(Elt);
6374     if (Elt.getOpcode() != ISD::Constant &&
6375         Elt.getOpcode() != ISD::ConstantFP)
6376       IsAllConstants = false;
6377     if (X86::isZeroNode(Elt))
6378       NumZero++;
6379     else {
6380       assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6381       NonZeros |= ((uint64_t)1 << i);
6382       NumNonZero++;
6383     }
6384   }
6385
6386   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6387   if (NumNonZero == 0)
6388     return DAG.getUNDEF(VT);
6389
6390   // Special case for single non-zero, non-undef, element.
6391   if (NumNonZero == 1) {
6392     unsigned Idx = countTrailingZeros(NonZeros);
6393     SDValue Item = Op.getOperand(Idx);
6394
6395     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6396     // the value are obviously zero, truncate the value to i32 and do the
6397     // insertion that way.  Only do this if the value is non-constant or if the
6398     // value is a constant being inserted into element 0.  It is cheaper to do
6399     // a constant pool load than it is to do a movd + shuffle.
6400     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6401         (!IsAllConstants || Idx == 0)) {
6402       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6403         // Handle SSE only.
6404         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6405         MVT VecVT = MVT::v4i32;
6406
6407         // Truncate the value (which may itself be a constant) to i32, and
6408         // convert it to a vector with movd (S2V+shuffle to zero extend).
6409         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6410         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6411         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6412                                       Item, Idx * 2, true, Subtarget, DAG));
6413       }
6414     }
6415
6416     // If we have a constant or non-constant insertion into the low element of
6417     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6418     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6419     // depending on what the source datatype is.
6420     if (Idx == 0) {
6421       if (NumZero == 0)
6422         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6423
6424       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6425           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6426         if (VT.is512BitVector()) {
6427           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6428           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6429                              Item, DAG.getIntPtrConstant(0, dl));
6430         }
6431         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6432                "Expected an SSE value type!");
6433         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6434         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6435         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6436       }
6437
6438       // We can't directly insert an i8 or i16 into a vector, so zero extend
6439       // it to i32 first.
6440       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6441         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6442         if (VT.is256BitVector()) {
6443           if (Subtarget->hasAVX()) {
6444             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6445             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6446           } else {
6447             // Without AVX, we need to extend to a 128-bit vector and then
6448             // insert into the 256-bit vector.
6449             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6450             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6451             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6452           }
6453         } else {
6454           assert(VT.is128BitVector() && "Expected an SSE value type!");
6455           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6456           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6457         }
6458         return DAG.getBitcast(VT, Item);
6459       }
6460     }
6461
6462     // Is it a vector logical left shift?
6463     if (NumElems == 2 && Idx == 1 &&
6464         X86::isZeroNode(Op.getOperand(0)) &&
6465         !X86::isZeroNode(Op.getOperand(1))) {
6466       unsigned NumBits = VT.getSizeInBits();
6467       return getVShift(true, VT,
6468                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6469                                    VT, Op.getOperand(1)),
6470                        NumBits/2, DAG, *this, dl);
6471     }
6472
6473     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6474       return SDValue();
6475
6476     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6477     // is a non-constant being inserted into an element other than the low one,
6478     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6479     // movd/movss) to move this into the low element, then shuffle it into
6480     // place.
6481     if (EVTBits == 32) {
6482       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6483       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6484     }
6485   }
6486
6487   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6488   if (Values.size() == 1) {
6489     if (EVTBits == 32) {
6490       // Instead of a shuffle like this:
6491       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6492       // Check if it's possible to issue this instead.
6493       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6494       unsigned Idx = countTrailingZeros(NonZeros);
6495       SDValue Item = Op.getOperand(Idx);
6496       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6497         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6498     }
6499     return SDValue();
6500   }
6501
6502   // A vector full of immediates; various special cases are already
6503   // handled, so this is best done with a single constant-pool load.
6504   if (IsAllConstants)
6505     return SDValue();
6506
6507   // For AVX-length vectors, see if we can use a vector load to get all of the
6508   // elements, otherwise build the individual 128-bit pieces and use
6509   // shuffles to put them in place.
6510   if (VT.is256BitVector() || VT.is512BitVector()) {
6511     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6512
6513     // Check for a build vector of consecutive loads.
6514     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6515       return LD;
6516
6517     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6518
6519     // Build both the lower and upper subvector.
6520     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6521                                 makeArrayRef(&V[0], NumElems/2));
6522     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6523                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6524
6525     // Recreate the wider vector with the lower and upper part.
6526     if (VT.is256BitVector())
6527       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6528     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6529   }
6530
6531   // Let legalizer expand 2-wide build_vectors.
6532   if (EVTBits == 64) {
6533     if (NumNonZero == 1) {
6534       // One half is zero or undef.
6535       unsigned Idx = countTrailingZeros(NonZeros);
6536       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6537                                Op.getOperand(Idx));
6538       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6539     }
6540     return SDValue();
6541   }
6542
6543   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6544   if (EVTBits == 8 && NumElems == 16)
6545     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6546                                           DAG, Subtarget, *this))
6547       return V;
6548
6549   if (EVTBits == 16 && NumElems == 8)
6550     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6551                                           DAG, Subtarget, *this))
6552       return V;
6553
6554   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6555   if (EVTBits == 32 && NumElems == 4)
6556     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6557       return V;
6558
6559   // If element VT is == 32 bits, turn it into a number of shuffles.
6560   SmallVector<SDValue, 8> V(NumElems);
6561   if (NumElems == 4 && NumZero > 0) {
6562     for (unsigned i = 0; i < 4; ++i) {
6563       bool isZero = !(NonZeros & (1ULL << i));
6564       if (isZero)
6565         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6566       else
6567         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6568     }
6569
6570     for (unsigned i = 0; i < 2; ++i) {
6571       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6572         default: break;
6573         case 0:
6574           V[i] = V[i*2];  // Must be a zero vector.
6575           break;
6576         case 1:
6577           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6578           break;
6579         case 2:
6580           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6581           break;
6582         case 3:
6583           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6584           break;
6585       }
6586     }
6587
6588     bool Reverse1 = (NonZeros & 0x3) == 2;
6589     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6590     int MaskVec[] = {
6591       Reverse1 ? 1 : 0,
6592       Reverse1 ? 0 : 1,
6593       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6594       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6595     };
6596     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6597   }
6598
6599   if (Values.size() > 1 && VT.is128BitVector()) {
6600     // Check for a build vector of consecutive loads.
6601     for (unsigned i = 0; i < NumElems; ++i)
6602       V[i] = Op.getOperand(i);
6603
6604     // Check for elements which are consecutive loads.
6605     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6606       return LD;
6607
6608     // Check for a build vector from mostly shuffle plus few inserting.
6609     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6610       return Sh;
6611
6612     // For SSE 4.1, use insertps to put the high elements into the low element.
6613     if (Subtarget->hasSSE41()) {
6614       SDValue Result;
6615       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6616         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6617       else
6618         Result = DAG.getUNDEF(VT);
6619
6620       for (unsigned i = 1; i < NumElems; ++i) {
6621         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6622         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6623                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6624       }
6625       return Result;
6626     }
6627
6628     // Otherwise, expand into a number of unpckl*, start by extending each of
6629     // our (non-undef) elements to the full vector width with the element in the
6630     // bottom slot of the vector (which generates no code for SSE).
6631     for (unsigned i = 0; i < NumElems; ++i) {
6632       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6633         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6634       else
6635         V[i] = DAG.getUNDEF(VT);
6636     }
6637
6638     // Next, we iteratively mix elements, e.g. for v4f32:
6639     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6640     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6641     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6642     unsigned EltStride = NumElems >> 1;
6643     while (EltStride != 0) {
6644       for (unsigned i = 0; i < EltStride; ++i) {
6645         // If V[i+EltStride] is undef and this is the first round of mixing,
6646         // then it is safe to just drop this shuffle: V[i] is already in the
6647         // right place, the one element (since it's the first round) being
6648         // inserted as undef can be dropped.  This isn't safe for successive
6649         // rounds because they will permute elements within both vectors.
6650         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6651             EltStride == NumElems/2)
6652           continue;
6653
6654         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6655       }
6656       EltStride >>= 1;
6657     }
6658     return V[0];
6659   }
6660   return SDValue();
6661 }
6662
6663 // 256-bit AVX can use the vinsertf128 instruction
6664 // to create 256-bit vectors from two other 128-bit ones.
6665 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6666   SDLoc dl(Op);
6667   MVT ResVT = Op.getSimpleValueType();
6668
6669   assert((ResVT.is256BitVector() ||
6670           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6671
6672   SDValue V1 = Op.getOperand(0);
6673   SDValue V2 = Op.getOperand(1);
6674   unsigned NumElems = ResVT.getVectorNumElements();
6675   if (ResVT.is256BitVector())
6676     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6677
6678   if (Op.getNumOperands() == 4) {
6679     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6680                                   ResVT.getVectorNumElements()/2);
6681     SDValue V3 = Op.getOperand(2);
6682     SDValue V4 = Op.getOperand(3);
6683     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6684       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6685   }
6686   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6687 }
6688
6689 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6690                                        const X86Subtarget *Subtarget,
6691                                        SelectionDAG & DAG) {
6692   SDLoc dl(Op);
6693   MVT ResVT = Op.getSimpleValueType();
6694   unsigned NumOfOperands = Op.getNumOperands();
6695
6696   assert(isPowerOf2_32(NumOfOperands) &&
6697          "Unexpected number of operands in CONCAT_VECTORS");
6698
6699   SDValue Undef = DAG.getUNDEF(ResVT);
6700   if (NumOfOperands > 2) {
6701     // Specialize the cases when all, or all but one, of the operands are undef.
6702     unsigned NumOfDefinedOps = 0;
6703     unsigned OpIdx = 0;
6704     for (unsigned i = 0; i < NumOfOperands; i++)
6705       if (!Op.getOperand(i).isUndef()) {
6706         NumOfDefinedOps++;
6707         OpIdx = i;
6708       }
6709     if (NumOfDefinedOps == 0)
6710       return Undef;
6711     if (NumOfDefinedOps == 1) {
6712       unsigned SubVecNumElts =
6713         Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6714       SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6715       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6716                          Op.getOperand(OpIdx), IdxVal);
6717     }
6718
6719     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6720                                   ResVT.getVectorNumElements()/2);
6721     SmallVector<SDValue, 2> Ops;
6722     for (unsigned i = 0; i < NumOfOperands/2; i++)
6723       Ops.push_back(Op.getOperand(i));
6724     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6725     Ops.clear();
6726     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6727       Ops.push_back(Op.getOperand(i));
6728     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6729     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6730   }
6731
6732   // 2 operands
6733   SDValue V1 = Op.getOperand(0);
6734   SDValue V2 = Op.getOperand(1);
6735   unsigned NumElems = ResVT.getVectorNumElements();
6736   assert(V1.getValueType() == V2.getValueType() &&
6737          V1.getValueType().getVectorNumElements() == NumElems/2 &&
6738          "Unexpected operands in CONCAT_VECTORS");
6739
6740   if (ResVT.getSizeInBits() >= 16)
6741     return Op; // The operation is legal with KUNPCK
6742
6743   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6744   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6745   SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6746   if (IsZeroV1 && IsZeroV2)
6747     return ZeroVec;
6748
6749   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6750   if (V2.isUndef())
6751     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6752   if (IsZeroV2)
6753     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6754
6755   SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6756   if (V1.isUndef())
6757     V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6758
6759   if (IsZeroV1)
6760     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6761
6762   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6763   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6764 }
6765
6766 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6767                                    const X86Subtarget *Subtarget,
6768                                    SelectionDAG &DAG) {
6769   MVT VT = Op.getSimpleValueType();
6770   if (VT.getVectorElementType() == MVT::i1)
6771     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6772
6773   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6774          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6775           Op.getNumOperands() == 4)));
6776
6777   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6778   // from two other 128-bit ones.
6779
6780   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6781   return LowerAVXCONCAT_VECTORS(Op, DAG);
6782 }
6783
6784 //===----------------------------------------------------------------------===//
6785 // Vector shuffle lowering
6786 //
6787 // This is an experimental code path for lowering vector shuffles on x86. It is
6788 // designed to handle arbitrary vector shuffles and blends, gracefully
6789 // degrading performance as necessary. It works hard to recognize idiomatic
6790 // shuffles and lower them to optimal instruction patterns without leaving
6791 // a framework that allows reasonably efficient handling of all vector shuffle
6792 // patterns.
6793 //===----------------------------------------------------------------------===//
6794
6795 /// \brief Tiny helper function to identify a no-op mask.
6796 ///
6797 /// This is a somewhat boring predicate function. It checks whether the mask
6798 /// array input, which is assumed to be a single-input shuffle mask of the kind
6799 /// used by the X86 shuffle instructions (not a fully general
6800 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6801 /// in-place shuffle are 'no-op's.
6802 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6803   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6804     if (Mask[i] != -1 && Mask[i] != i)
6805       return false;
6806   return true;
6807 }
6808
6809 /// \brief Helper function to classify a mask as a single-input mask.
6810 ///
6811 /// This isn't a generic single-input test because in the vector shuffle
6812 /// lowering we canonicalize single inputs to be the first input operand. This
6813 /// means we can more quickly test for a single input by only checking whether
6814 /// an input from the second operand exists. We also assume that the size of
6815 /// mask corresponds to the size of the input vectors which isn't true in the
6816 /// fully general case.
6817 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6818   for (int M : Mask)
6819     if (M >= (int)Mask.size())
6820       return false;
6821   return true;
6822 }
6823
6824 /// \brief Test whether there are elements crossing 128-bit lanes in this
6825 /// shuffle mask.
6826 ///
6827 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6828 /// and we routinely test for these.
6829 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6830   int LaneSize = 128 / VT.getScalarSizeInBits();
6831   int Size = Mask.size();
6832   for (int i = 0; i < Size; ++i)
6833     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6834       return true;
6835   return false;
6836 }
6837
6838 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6839 ///
6840 /// This checks a shuffle mask to see if it is performing the same
6841 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6842 /// that it is also not lane-crossing. It may however involve a blend from the
6843 /// same lane of a second vector.
6844 ///
6845 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6846 /// non-trivial to compute in the face of undef lanes. The representation is
6847 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6848 /// entries from both V1 and V2 inputs to the wider mask.
6849 static bool
6850 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6851                                 SmallVectorImpl<int> &RepeatedMask) {
6852   int LaneSize = 128 / VT.getScalarSizeInBits();
6853   RepeatedMask.resize(LaneSize, -1);
6854   int Size = Mask.size();
6855   for (int i = 0; i < Size; ++i) {
6856     if (Mask[i] < 0)
6857       continue;
6858     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6859       // This entry crosses lanes, so there is no way to model this shuffle.
6860       return false;
6861
6862     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6863     if (RepeatedMask[i % LaneSize] == -1)
6864       // This is the first non-undef entry in this slot of a 128-bit lane.
6865       RepeatedMask[i % LaneSize] =
6866           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6867     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6868       // Found a mismatch with the repeated mask.
6869       return false;
6870   }
6871   return true;
6872 }
6873
6874 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6875 /// arguments.
6876 ///
6877 /// This is a fast way to test a shuffle mask against a fixed pattern:
6878 ///
6879 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6880 ///
6881 /// It returns true if the mask is exactly as wide as the argument list, and
6882 /// each element of the mask is either -1 (signifying undef) or the value given
6883 /// in the argument.
6884 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6885                                 ArrayRef<int> ExpectedMask) {
6886   if (Mask.size() != ExpectedMask.size())
6887     return false;
6888
6889   int Size = Mask.size();
6890
6891   // If the values are build vectors, we can look through them to find
6892   // equivalent inputs that make the shuffles equivalent.
6893   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6894   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6895
6896   for (int i = 0; i < Size; ++i)
6897     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6898       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6899       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6900       if (!MaskBV || !ExpectedBV ||
6901           MaskBV->getOperand(Mask[i] % Size) !=
6902               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6903         return false;
6904     }
6905
6906   return true;
6907 }
6908
6909 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6910 ///
6911 /// This helper function produces an 8-bit shuffle immediate corresponding to
6912 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6913 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6914 /// example.
6915 ///
6916 /// NB: We rely heavily on "undef" masks preserving the input lane.
6917 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6918                                           SelectionDAG &DAG) {
6919   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6920   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6921   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6922   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6923   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6924
6925   unsigned Imm = 0;
6926   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6927   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6928   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6929   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6930   return DAG.getConstant(Imm, DL, MVT::i8);
6931 }
6932
6933 /// \brief Compute whether each element of a shuffle is zeroable.
6934 ///
6935 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6936 /// Either it is an undef element in the shuffle mask, the element of the input
6937 /// referenced is undef, or the element of the input referenced is known to be
6938 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6939 /// as many lanes with this technique as possible to simplify the remaining
6940 /// shuffle.
6941 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6942                                                      SDValue V1, SDValue V2) {
6943   SmallBitVector Zeroable(Mask.size(), false);
6944
6945   while (V1.getOpcode() == ISD::BITCAST)
6946     V1 = V1->getOperand(0);
6947   while (V2.getOpcode() == ISD::BITCAST)
6948     V2 = V2->getOperand(0);
6949
6950   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6951   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6952
6953   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6954     int M = Mask[i];
6955     // Handle the easy cases.
6956     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6957       Zeroable[i] = true;
6958       continue;
6959     }
6960
6961     // If this is an index into a build_vector node (which has the same number
6962     // of elements), dig out the input value and use it.
6963     SDValue V = M < Size ? V1 : V2;
6964     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6965       continue;
6966
6967     SDValue Input = V.getOperand(M % Size);
6968     // The UNDEF opcode check really should be dead code here, but not quite
6969     // worth asserting on (it isn't invalid, just unexpected).
6970     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6971       Zeroable[i] = true;
6972   }
6973
6974   return Zeroable;
6975 }
6976
6977 // X86 has dedicated unpack instructions that can handle specific blend
6978 // operations: UNPCKH and UNPCKL.
6979 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6980                                            SDValue V1, SDValue V2,
6981                                            SelectionDAG &DAG) {
6982   int NumElts = VT.getVectorNumElements();
6983   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6984   SmallVector<int, 8> Unpckl;
6985   SmallVector<int, 8> Unpckh;
6986
6987   for (int i = 0; i < NumElts; ++i) {
6988     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6989     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6990     int HiPos = LoPos + NumEltsInLane / 2;
6991     Unpckl.push_back(LoPos);
6992     Unpckh.push_back(HiPos);
6993   }
6994
6995   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6996     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6997   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6998     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6999
7000   // Commute and try again.
7001   ShuffleVectorSDNode::commuteMask(Unpckl);
7002   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
7003     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
7004
7005   ShuffleVectorSDNode::commuteMask(Unpckh);
7006   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
7007     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
7008
7009   return SDValue();
7010 }
7011
7012 /// \brief Try to emit a bitmask instruction for a shuffle.
7013 ///
7014 /// This handles cases where we can model a blend exactly as a bitmask due to
7015 /// one of the inputs being zeroable.
7016 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
7017                                            SDValue V2, ArrayRef<int> Mask,
7018                                            SelectionDAG &DAG) {
7019   MVT EltVT = VT.getVectorElementType();
7020   int NumEltBits = EltVT.getSizeInBits();
7021   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
7022   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
7023   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7024                                     IntEltVT);
7025   if (EltVT.isFloatingPoint()) {
7026     Zero = DAG.getBitcast(EltVT, Zero);
7027     AllOnes = DAG.getBitcast(EltVT, AllOnes);
7028   }
7029   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
7030   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7031   SDValue V;
7032   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7033     if (Zeroable[i])
7034       continue;
7035     if (Mask[i] % Size != i)
7036       return SDValue(); // Not a blend.
7037     if (!V)
7038       V = Mask[i] < Size ? V1 : V2;
7039     else if (V != (Mask[i] < Size ? V1 : V2))
7040       return SDValue(); // Can only let one input through the mask.
7041
7042     VMaskOps[i] = AllOnes;
7043   }
7044   if (!V)
7045     return SDValue(); // No non-zeroable elements!
7046
7047   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
7048   V = DAG.getNode(VT.isFloatingPoint()
7049                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7050                   DL, VT, V, VMask);
7051   return V;
7052 }
7053
7054 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7055 ///
7056 /// This is used as a fallback approach when first class blend instructions are
7057 /// unavailable. Currently it is only suitable for integer vectors, but could
7058 /// be generalized for floating point vectors if desirable.
7059 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
7060                                             SDValue V2, ArrayRef<int> Mask,
7061                                             SelectionDAG &DAG) {
7062   assert(VT.isInteger() && "Only supports integer vector types!");
7063   MVT EltVT = VT.getVectorElementType();
7064   int NumEltBits = EltVT.getSizeInBits();
7065   SDValue Zero = DAG.getConstant(0, DL, EltVT);
7066   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7067                                     EltVT);
7068   SmallVector<SDValue, 16> MaskOps;
7069   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7070     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
7071       return SDValue(); // Shuffled input!
7072     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7073   }
7074
7075   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
7076   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7077   // We have to cast V2 around.
7078   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7079   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7080                                       DAG.getBitcast(MaskVT, V1Mask),
7081                                       DAG.getBitcast(MaskVT, V2)));
7082   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7083 }
7084
7085 /// \brief Try to emit a blend instruction for a shuffle.
7086 ///
7087 /// This doesn't do any checks for the availability of instructions for blending
7088 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7089 /// be matched in the backend with the type given. What it does check for is
7090 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7091 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7092                                          SDValue V2, ArrayRef<int> Original,
7093                                          const X86Subtarget *Subtarget,
7094                                          SelectionDAG &DAG) {
7095   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7096   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7097   SmallVector<int, 8> Mask(Original.begin(), Original.end());
7098   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7099   bool ForceV1Zero = false, ForceV2Zero = false;
7100
7101   // Attempt to generate the binary blend mask. If an input is zero then
7102   // we can use any lane.
7103   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7104   unsigned BlendMask = 0;
7105   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7106     int M = Mask[i];
7107     if (M < 0)
7108       continue;
7109     if (M == i)
7110       continue;
7111     if (M == i + Size) {
7112       BlendMask |= 1u << i;
7113       continue;
7114     }
7115     if (Zeroable[i]) {
7116       if (V1IsZero) {
7117         ForceV1Zero = true;
7118         Mask[i] = i;
7119         continue;
7120       }
7121       if (V2IsZero) {
7122         ForceV2Zero = true;
7123         BlendMask |= 1u << i;
7124         Mask[i] = i + Size;
7125         continue;
7126       }
7127     }
7128     return SDValue(); // Shuffled input!
7129   }
7130
7131   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7132   if (ForceV1Zero)
7133     V1 = getZeroVector(VT, Subtarget, DAG, DL);
7134   if (ForceV2Zero)
7135     V2 = getZeroVector(VT, Subtarget, DAG, DL);
7136
7137   auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7138     unsigned ScaledMask = 0;
7139     for (int i = 0; i != Size; ++i)
7140       if (BlendMask & (1u << i))
7141         for (int j = 0; j != Scale; ++j)
7142           ScaledMask |= 1u << (i * Scale + j);
7143     return ScaledMask;
7144   };
7145
7146   switch (VT.SimpleTy) {
7147   case MVT::v2f64:
7148   case MVT::v4f32:
7149   case MVT::v4f64:
7150   case MVT::v8f32:
7151     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7152                        DAG.getConstant(BlendMask, DL, MVT::i8));
7153
7154   case MVT::v4i64:
7155   case MVT::v8i32:
7156     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7157     // FALLTHROUGH
7158   case MVT::v2i64:
7159   case MVT::v4i32:
7160     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7161     // that instruction.
7162     if (Subtarget->hasAVX2()) {
7163       // Scale the blend by the number of 32-bit dwords per element.
7164       int Scale =  VT.getScalarSizeInBits() / 32;
7165       BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7166       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7167       V1 = DAG.getBitcast(BlendVT, V1);
7168       V2 = DAG.getBitcast(BlendVT, V2);
7169       return DAG.getBitcast(
7170           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7171                           DAG.getConstant(BlendMask, DL, MVT::i8)));
7172     }
7173     // FALLTHROUGH
7174   case MVT::v8i16: {
7175     // For integer shuffles we need to expand the mask and cast the inputs to
7176     // v8i16s prior to blending.
7177     int Scale = 8 / VT.getVectorNumElements();
7178     BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7179     V1 = DAG.getBitcast(MVT::v8i16, V1);
7180     V2 = DAG.getBitcast(MVT::v8i16, V2);
7181     return DAG.getBitcast(VT,
7182                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7183                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
7184   }
7185
7186   case MVT::v16i16: {
7187     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7188     SmallVector<int, 8> RepeatedMask;
7189     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7190       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7191       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7192       BlendMask = 0;
7193       for (int i = 0; i < 8; ++i)
7194         if (RepeatedMask[i] >= 16)
7195           BlendMask |= 1u << i;
7196       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7197                          DAG.getConstant(BlendMask, DL, MVT::i8));
7198     }
7199   }
7200     // FALLTHROUGH
7201   case MVT::v16i8:
7202   case MVT::v32i8: {
7203     assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7204            "256-bit byte-blends require AVX2 support!");
7205
7206     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7207     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7208       return Masked;
7209
7210     // Scale the blend by the number of bytes per element.
7211     int Scale = VT.getScalarSizeInBits() / 8;
7212
7213     // This form of blend is always done on bytes. Compute the byte vector
7214     // type.
7215     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7216
7217     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7218     // mix of LLVM's code generator and the x86 backend. We tell the code
7219     // generator that boolean values in the elements of an x86 vector register
7220     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7221     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7222     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7223     // of the element (the remaining are ignored) and 0 in that high bit would
7224     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7225     // the LLVM model for boolean values in vector elements gets the relevant
7226     // bit set, it is set backwards and over constrained relative to x86's
7227     // actual model.
7228     SmallVector<SDValue, 32> VSELECTMask;
7229     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7230       for (int j = 0; j < Scale; ++j)
7231         VSELECTMask.push_back(
7232             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7233                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7234                                           MVT::i8));
7235
7236     V1 = DAG.getBitcast(BlendVT, V1);
7237     V2 = DAG.getBitcast(BlendVT, V2);
7238     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7239                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7240                                                       BlendVT, VSELECTMask),
7241                                           V1, V2));
7242   }
7243
7244   default:
7245     llvm_unreachable("Not a supported integer vector type!");
7246   }
7247 }
7248
7249 /// \brief Try to lower as a blend of elements from two inputs followed by
7250 /// a single-input permutation.
7251 ///
7252 /// This matches the pattern where we can blend elements from two inputs and
7253 /// then reduce the shuffle to a single-input permutation.
7254 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7255                                                    SDValue V2,
7256                                                    ArrayRef<int> Mask,
7257                                                    SelectionDAG &DAG) {
7258   // We build up the blend mask while checking whether a blend is a viable way
7259   // to reduce the shuffle.
7260   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7261   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7262
7263   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7264     if (Mask[i] < 0)
7265       continue;
7266
7267     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7268
7269     if (BlendMask[Mask[i] % Size] == -1)
7270       BlendMask[Mask[i] % Size] = Mask[i];
7271     else if (BlendMask[Mask[i] % Size] != Mask[i])
7272       return SDValue(); // Can't blend in the needed input!
7273
7274     PermuteMask[i] = Mask[i] % Size;
7275   }
7276
7277   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7278   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7279 }
7280
7281 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7282 /// blends and permutes.
7283 ///
7284 /// This matches the extremely common pattern for handling combined
7285 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7286 /// operations. It will try to pick the best arrangement of shuffles and
7287 /// blends.
7288 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7289                                                           SDValue V1,
7290                                                           SDValue V2,
7291                                                           ArrayRef<int> Mask,
7292                                                           SelectionDAG &DAG) {
7293   // Shuffle the input elements into the desired positions in V1 and V2 and
7294   // blend them together.
7295   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7296   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7297   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7298   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7299     if (Mask[i] >= 0 && Mask[i] < Size) {
7300       V1Mask[i] = Mask[i];
7301       BlendMask[i] = i;
7302     } else if (Mask[i] >= Size) {
7303       V2Mask[i] = Mask[i] - Size;
7304       BlendMask[i] = i + Size;
7305     }
7306
7307   // Try to lower with the simpler initial blend strategy unless one of the
7308   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7309   // shuffle may be able to fold with a load or other benefit. However, when
7310   // we'll have to do 2x as many shuffles in order to achieve this, blending
7311   // first is a better strategy.
7312   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7313     if (SDValue BlendPerm =
7314             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7315       return BlendPerm;
7316
7317   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7318   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7319   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7320 }
7321
7322 /// \brief Try to lower a vector shuffle as a byte rotation.
7323 ///
7324 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7325 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7326 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7327 /// try to generically lower a vector shuffle through such an pattern. It
7328 /// does not check for the profitability of lowering either as PALIGNR or
7329 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7330 /// This matches shuffle vectors that look like:
7331 ///
7332 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7333 ///
7334 /// Essentially it concatenates V1 and V2, shifts right by some number of
7335 /// elements, and takes the low elements as the result. Note that while this is
7336 /// specified as a *right shift* because x86 is little-endian, it is a *left
7337 /// rotate* of the vector lanes.
7338 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7339                                               SDValue V2,
7340                                               ArrayRef<int> Mask,
7341                                               const X86Subtarget *Subtarget,
7342                                               SelectionDAG &DAG) {
7343   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7344
7345   int NumElts = Mask.size();
7346   int NumLanes = VT.getSizeInBits() / 128;
7347   int NumLaneElts = NumElts / NumLanes;
7348
7349   // We need to detect various ways of spelling a rotation:
7350   //   [11, 12, 13, 14, 15,  0,  1,  2]
7351   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7352   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7353   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7354   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7355   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7356   int Rotation = 0;
7357   SDValue Lo, Hi;
7358   for (int l = 0; l < NumElts; l += NumLaneElts) {
7359     for (int i = 0; i < NumLaneElts; ++i) {
7360       if (Mask[l + i] == -1)
7361         continue;
7362       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7363
7364       // Get the mod-Size index and lane correct it.
7365       int LaneIdx = (Mask[l + i] % NumElts) - l;
7366       // Make sure it was in this lane.
7367       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7368         return SDValue();
7369
7370       // Determine where a rotated vector would have started.
7371       int StartIdx = i - LaneIdx;
7372       if (StartIdx == 0)
7373         // The identity rotation isn't interesting, stop.
7374         return SDValue();
7375
7376       // If we found the tail of a vector the rotation must be the missing
7377       // front. If we found the head of a vector, it must be how much of the
7378       // head.
7379       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7380
7381       if (Rotation == 0)
7382         Rotation = CandidateRotation;
7383       else if (Rotation != CandidateRotation)
7384         // The rotations don't match, so we can't match this mask.
7385         return SDValue();
7386
7387       // Compute which value this mask is pointing at.
7388       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7389
7390       // Compute which of the two target values this index should be assigned
7391       // to. This reflects whether the high elements are remaining or the low
7392       // elements are remaining.
7393       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7394
7395       // Either set up this value if we've not encountered it before, or check
7396       // that it remains consistent.
7397       if (!TargetV)
7398         TargetV = MaskV;
7399       else if (TargetV != MaskV)
7400         // This may be a rotation, but it pulls from the inputs in some
7401         // unsupported interleaving.
7402         return SDValue();
7403     }
7404   }
7405
7406   // Check that we successfully analyzed the mask, and normalize the results.
7407   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7408   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7409   if (!Lo)
7410     Lo = Hi;
7411   else if (!Hi)
7412     Hi = Lo;
7413
7414   // The actual rotate instruction rotates bytes, so we need to scale the
7415   // rotation based on how many bytes are in the vector lane.
7416   int Scale = 16 / NumLaneElts;
7417
7418   // SSSE3 targets can use the palignr instruction.
7419   if (Subtarget->hasSSSE3()) {
7420     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7421     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7422     Lo = DAG.getBitcast(AlignVT, Lo);
7423     Hi = DAG.getBitcast(AlignVT, Hi);
7424
7425     return DAG.getBitcast(
7426         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7427                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7428   }
7429
7430   assert(VT.is128BitVector() &&
7431          "Rotate-based lowering only supports 128-bit lowering!");
7432   assert(Mask.size() <= 16 &&
7433          "Can shuffle at most 16 bytes in a 128-bit vector!");
7434
7435   // Default SSE2 implementation
7436   int LoByteShift = 16 - Rotation * Scale;
7437   int HiByteShift = Rotation * Scale;
7438
7439   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7440   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7441   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7442
7443   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7444                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7445   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7446                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7447   return DAG.getBitcast(VT,
7448                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7449 }
7450
7451 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7452 ///
7453 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7454 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7455 /// matches elements from one of the input vectors shuffled to the left or
7456 /// right with zeroable elements 'shifted in'. It handles both the strictly
7457 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7458 /// quad word lane.
7459 ///
7460 /// PSHL : (little-endian) left bit shift.
7461 /// [ zz, 0, zz,  2 ]
7462 /// [ -1, 4, zz, -1 ]
7463 /// PSRL : (little-endian) right bit shift.
7464 /// [  1, zz,  3, zz]
7465 /// [ -1, -1,  7, zz]
7466 /// PSLLDQ : (little-endian) left byte shift
7467 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7468 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7469 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7470 /// PSRLDQ : (little-endian) right byte shift
7471 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7472 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7473 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7474 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7475                                          SDValue V2, ArrayRef<int> Mask,
7476                                          SelectionDAG &DAG) {
7477   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7478
7479   int Size = Mask.size();
7480   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7481
7482   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7483     for (int i = 0; i < Size; i += Scale)
7484       for (int j = 0; j < Shift; ++j)
7485         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7486           return false;
7487
7488     return true;
7489   };
7490
7491   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7492     for (int i = 0; i != Size; i += Scale) {
7493       unsigned Pos = Left ? i + Shift : i;
7494       unsigned Low = Left ? i : i + Shift;
7495       unsigned Len = Scale - Shift;
7496       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7497                                       Low + (V == V1 ? 0 : Size)))
7498         return SDValue();
7499     }
7500
7501     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7502     bool ByteShift = ShiftEltBits > 64;
7503     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7504                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7505     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7506
7507     // Normalize the scale for byte shifts to still produce an i64 element
7508     // type.
7509     Scale = ByteShift ? Scale / 2 : Scale;
7510
7511     // We need to round trip through the appropriate type for the shift.
7512     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7513     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7514     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7515            "Illegal integer vector type");
7516     V = DAG.getBitcast(ShiftVT, V);
7517
7518     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7519                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7520     return DAG.getBitcast(VT, V);
7521   };
7522
7523   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7524   // keep doubling the size of the integer elements up to that. We can
7525   // then shift the elements of the integer vector by whole multiples of
7526   // their width within the elements of the larger integer vector. Test each
7527   // multiple to see if we can find a match with the moved element indices
7528   // and that the shifted in elements are all zeroable.
7529   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7530     for (int Shift = 1; Shift != Scale; ++Shift)
7531       for (bool Left : {true, false})
7532         if (CheckZeros(Shift, Scale, Left))
7533           for (SDValue V : {V1, V2})
7534             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7535               return Match;
7536
7537   // no match
7538   return SDValue();
7539 }
7540
7541 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7542 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7543                                            SDValue V2, ArrayRef<int> Mask,
7544                                            SelectionDAG &DAG) {
7545   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7546   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7547
7548   int Size = Mask.size();
7549   int HalfSize = Size / 2;
7550   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7551
7552   // Upper half must be undefined.
7553   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7554     return SDValue();
7555
7556   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7557   // Remainder of lower half result is zero and upper half is all undef.
7558   auto LowerAsEXTRQ = [&]() {
7559     // Determine the extraction length from the part of the
7560     // lower half that isn't zeroable.
7561     int Len = HalfSize;
7562     for (; Len > 0; --Len)
7563       if (!Zeroable[Len - 1])
7564         break;
7565     assert(Len > 0 && "Zeroable shuffle mask");
7566
7567     // Attempt to match first Len sequential elements from the lower half.
7568     SDValue Src;
7569     int Idx = -1;
7570     for (int i = 0; i != Len; ++i) {
7571       int M = Mask[i];
7572       if (M < 0)
7573         continue;
7574       SDValue &V = (M < Size ? V1 : V2);
7575       M = M % Size;
7576
7577       // The extracted elements must start at a valid index and all mask
7578       // elements must be in the lower half.
7579       if (i > M || M >= HalfSize)
7580         return SDValue();
7581
7582       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7583         Src = V;
7584         Idx = M - i;
7585         continue;
7586       }
7587       return SDValue();
7588     }
7589
7590     if (Idx < 0)
7591       return SDValue();
7592
7593     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7594     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7595     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7596     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7597                        DAG.getConstant(BitLen, DL, MVT::i8),
7598                        DAG.getConstant(BitIdx, DL, MVT::i8));
7599   };
7600
7601   if (SDValue ExtrQ = LowerAsEXTRQ())
7602     return ExtrQ;
7603
7604   // INSERTQ: Extract lowest Len elements from lower half of second source and
7605   // insert over first source, starting at Idx.
7606   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7607   auto LowerAsInsertQ = [&]() {
7608     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7609       SDValue Base;
7610
7611       // Attempt to match first source from mask before insertion point.
7612       if (isUndefInRange(Mask, 0, Idx)) {
7613         /* EMPTY */
7614       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7615         Base = V1;
7616       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7617         Base = V2;
7618       } else {
7619         continue;
7620       }
7621
7622       // Extend the extraction length looking to match both the insertion of
7623       // the second source and the remaining elements of the first.
7624       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7625         SDValue Insert;
7626         int Len = Hi - Idx;
7627
7628         // Match insertion.
7629         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7630           Insert = V1;
7631         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7632           Insert = V2;
7633         } else {
7634           continue;
7635         }
7636
7637         // Match the remaining elements of the lower half.
7638         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7639           /* EMPTY */
7640         } else if ((!Base || (Base == V1)) &&
7641                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7642           Base = V1;
7643         } else if ((!Base || (Base == V2)) &&
7644                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7645                                               Size + Hi)) {
7646           Base = V2;
7647         } else {
7648           continue;
7649         }
7650
7651         // We may not have a base (first source) - this can safely be undefined.
7652         if (!Base)
7653           Base = DAG.getUNDEF(VT);
7654
7655         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7656         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7657         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7658                            DAG.getConstant(BitLen, DL, MVT::i8),
7659                            DAG.getConstant(BitIdx, DL, MVT::i8));
7660       }
7661     }
7662
7663     return SDValue();
7664   };
7665
7666   if (SDValue InsertQ = LowerAsInsertQ())
7667     return InsertQ;
7668
7669   return SDValue();
7670 }
7671
7672 /// \brief Lower a vector shuffle as a zero or any extension.
7673 ///
7674 /// Given a specific number of elements, element bit width, and extension
7675 /// stride, produce either a zero or any extension based on the available
7676 /// features of the subtarget. The extended elements are consecutive and
7677 /// begin and can start from an offseted element index in the input; to
7678 /// avoid excess shuffling the offset must either being in the bottom lane
7679 /// or at the start of a higher lane. All extended elements must be from
7680 /// the same lane.
7681 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7682     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7683     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7684   assert(Scale > 1 && "Need a scale to extend.");
7685   int EltBits = VT.getScalarSizeInBits();
7686   int NumElements = VT.getVectorNumElements();
7687   int NumEltsPerLane = 128 / EltBits;
7688   int OffsetLane = Offset / NumEltsPerLane;
7689   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7690          "Only 8, 16, and 32 bit elements can be extended.");
7691   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7692   assert(0 <= Offset && "Extension offset must be positive.");
7693   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7694          "Extension offset must be in the first lane or start an upper lane.");
7695
7696   // Check that an index is in same lane as the base offset.
7697   auto SafeOffset = [&](int Idx) {
7698     return OffsetLane == (Idx / NumEltsPerLane);
7699   };
7700
7701   // Shift along an input so that the offset base moves to the first element.
7702   auto ShuffleOffset = [&](SDValue V) {
7703     if (!Offset)
7704       return V;
7705
7706     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7707     for (int i = 0; i * Scale < NumElements; ++i) {
7708       int SrcIdx = i + Offset;
7709       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7710     }
7711     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7712   };
7713
7714   // Found a valid zext mask! Try various lowering strategies based on the
7715   // input type and available ISA extensions.
7716   if (Subtarget->hasSSE41()) {
7717     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7718     // PUNPCK will catch this in a later shuffle match.
7719     if (Offset && Scale == 2 && VT.is128BitVector())
7720       return SDValue();
7721     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7722                                  NumElements / Scale);
7723     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7724     return DAG.getBitcast(VT, InputV);
7725   }
7726
7727   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7728
7729   // For any extends we can cheat for larger element sizes and use shuffle
7730   // instructions that can fold with a load and/or copy.
7731   if (AnyExt && EltBits == 32) {
7732     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7733                          -1};
7734     return DAG.getBitcast(
7735         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7736                         DAG.getBitcast(MVT::v4i32, InputV),
7737                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7738   }
7739   if (AnyExt && EltBits == 16 && Scale > 2) {
7740     int PSHUFDMask[4] = {Offset / 2, -1,
7741                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7742     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7743                          DAG.getBitcast(MVT::v4i32, InputV),
7744                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7745     int PSHUFWMask[4] = {1, -1, -1, -1};
7746     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7747     return DAG.getBitcast(
7748         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7749                         DAG.getBitcast(MVT::v8i16, InputV),
7750                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7751   }
7752
7753   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7754   // to 64-bits.
7755   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7756     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7757     assert(VT.is128BitVector() && "Unexpected vector width!");
7758
7759     int LoIdx = Offset * EltBits;
7760     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7761                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7762                                          DAG.getConstant(EltBits, DL, MVT::i8),
7763                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7764
7765     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7766         !SafeOffset(Offset + 1))
7767       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7768
7769     int HiIdx = (Offset + 1) * EltBits;
7770     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7771                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7772                                          DAG.getConstant(EltBits, DL, MVT::i8),
7773                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7774     return DAG.getNode(ISD::BITCAST, DL, VT,
7775                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7776   }
7777
7778   // If this would require more than 2 unpack instructions to expand, use
7779   // pshufb when available. We can only use more than 2 unpack instructions
7780   // when zero extending i8 elements which also makes it easier to use pshufb.
7781   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7782     assert(NumElements == 16 && "Unexpected byte vector width!");
7783     SDValue PSHUFBMask[16];
7784     for (int i = 0; i < 16; ++i) {
7785       int Idx = Offset + (i / Scale);
7786       PSHUFBMask[i] = DAG.getConstant(
7787           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7788     }
7789     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7790     return DAG.getBitcast(VT,
7791                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7792                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7793                                                   MVT::v16i8, PSHUFBMask)));
7794   }
7795
7796   // If we are extending from an offset, ensure we start on a boundary that
7797   // we can unpack from.
7798   int AlignToUnpack = Offset % (NumElements / Scale);
7799   if (AlignToUnpack) {
7800     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7801     for (int i = AlignToUnpack; i < NumElements; ++i)
7802       ShMask[i - AlignToUnpack] = i;
7803     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7804     Offset -= AlignToUnpack;
7805   }
7806
7807   // Otherwise emit a sequence of unpacks.
7808   do {
7809     unsigned UnpackLoHi = X86ISD::UNPCKL;
7810     if (Offset >= (NumElements / 2)) {
7811       UnpackLoHi = X86ISD::UNPCKH;
7812       Offset -= (NumElements / 2);
7813     }
7814
7815     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7816     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7817                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7818     InputV = DAG.getBitcast(InputVT, InputV);
7819     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7820     Scale /= 2;
7821     EltBits *= 2;
7822     NumElements /= 2;
7823   } while (Scale > 1);
7824   return DAG.getBitcast(VT, InputV);
7825 }
7826
7827 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7828 ///
7829 /// This routine will try to do everything in its power to cleverly lower
7830 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7831 /// check for the profitability of this lowering,  it tries to aggressively
7832 /// match this pattern. It will use all of the micro-architectural details it
7833 /// can to emit an efficient lowering. It handles both blends with all-zero
7834 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7835 /// masking out later).
7836 ///
7837 /// The reason we have dedicated lowering for zext-style shuffles is that they
7838 /// are both incredibly common and often quite performance sensitive.
7839 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7840     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7841     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7842   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7843
7844   int Bits = VT.getSizeInBits();
7845   int NumLanes = Bits / 128;
7846   int NumElements = VT.getVectorNumElements();
7847   int NumEltsPerLane = NumElements / NumLanes;
7848   assert(VT.getScalarSizeInBits() <= 32 &&
7849          "Exceeds 32-bit integer zero extension limit");
7850   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7851
7852   // Define a helper function to check a particular ext-scale and lower to it if
7853   // valid.
7854   auto Lower = [&](int Scale) -> SDValue {
7855     SDValue InputV;
7856     bool AnyExt = true;
7857     int Offset = 0;
7858     int Matches = 0;
7859     for (int i = 0; i < NumElements; ++i) {
7860       int M = Mask[i];
7861       if (M == -1)
7862         continue; // Valid anywhere but doesn't tell us anything.
7863       if (i % Scale != 0) {
7864         // Each of the extended elements need to be zeroable.
7865         if (!Zeroable[i])
7866           return SDValue();
7867
7868         // We no longer are in the anyext case.
7869         AnyExt = false;
7870         continue;
7871       }
7872
7873       // Each of the base elements needs to be consecutive indices into the
7874       // same input vector.
7875       SDValue V = M < NumElements ? V1 : V2;
7876       M = M % NumElements;
7877       if (!InputV) {
7878         InputV = V;
7879         Offset = M - (i / Scale);
7880       } else if (InputV != V)
7881         return SDValue(); // Flip-flopping inputs.
7882
7883       // Offset must start in the lowest 128-bit lane or at the start of an
7884       // upper lane.
7885       // FIXME: Is it ever worth allowing a negative base offset?
7886       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7887             (Offset % NumEltsPerLane) == 0))
7888         return SDValue();
7889
7890       // If we are offsetting, all referenced entries must come from the same
7891       // lane.
7892       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7893         return SDValue();
7894
7895       if ((M % NumElements) != (Offset + (i / Scale)))
7896         return SDValue(); // Non-consecutive strided elements.
7897       Matches++;
7898     }
7899
7900     // If we fail to find an input, we have a zero-shuffle which should always
7901     // have already been handled.
7902     // FIXME: Maybe handle this here in case during blending we end up with one?
7903     if (!InputV)
7904       return SDValue();
7905
7906     // If we are offsetting, don't extend if we only match a single input, we
7907     // can always do better by using a basic PSHUF or PUNPCK.
7908     if (Offset != 0 && Matches < 2)
7909       return SDValue();
7910
7911     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7912         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7913   };
7914
7915   // The widest scale possible for extending is to a 64-bit integer.
7916   assert(Bits % 64 == 0 &&
7917          "The number of bits in a vector must be divisible by 64 on x86!");
7918   int NumExtElements = Bits / 64;
7919
7920   // Each iteration, try extending the elements half as much, but into twice as
7921   // many elements.
7922   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7923     assert(NumElements % NumExtElements == 0 &&
7924            "The input vector size must be divisible by the extended size.");
7925     if (SDValue V = Lower(NumElements / NumExtElements))
7926       return V;
7927   }
7928
7929   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7930   if (Bits != 128)
7931     return SDValue();
7932
7933   // Returns one of the source operands if the shuffle can be reduced to a
7934   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7935   auto CanZExtLowHalf = [&]() {
7936     for (int i = NumElements / 2; i != NumElements; ++i)
7937       if (!Zeroable[i])
7938         return SDValue();
7939     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7940       return V1;
7941     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7942       return V2;
7943     return SDValue();
7944   };
7945
7946   if (SDValue V = CanZExtLowHalf()) {
7947     V = DAG.getBitcast(MVT::v2i64, V);
7948     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7949     return DAG.getBitcast(VT, V);
7950   }
7951
7952   // No viable ext lowering found.
7953   return SDValue();
7954 }
7955
7956 /// \brief Try to get a scalar value for a specific element of a vector.
7957 ///
7958 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7959 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7960                                               SelectionDAG &DAG) {
7961   MVT VT = V.getSimpleValueType();
7962   MVT EltVT = VT.getVectorElementType();
7963   while (V.getOpcode() == ISD::BITCAST)
7964     V = V.getOperand(0);
7965   // If the bitcasts shift the element size, we can't extract an equivalent
7966   // element from it.
7967   MVT NewVT = V.getSimpleValueType();
7968   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7969     return SDValue();
7970
7971   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7972       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7973     // Ensure the scalar operand is the same size as the destination.
7974     // FIXME: Add support for scalar truncation where possible.
7975     SDValue S = V.getOperand(Idx);
7976     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7977       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7978   }
7979
7980   return SDValue();
7981 }
7982
7983 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7984 ///
7985 /// This is particularly important because the set of instructions varies
7986 /// significantly based on whether the operand is a load or not.
7987 static bool isShuffleFoldableLoad(SDValue V) {
7988   while (V.getOpcode() == ISD::BITCAST)
7989     V = V.getOperand(0);
7990
7991   return ISD::isNON_EXTLoad(V.getNode());
7992 }
7993
7994 /// \brief Try to lower insertion of a single element into a zero vector.
7995 ///
7996 /// This is a common pattern that we have especially efficient patterns to lower
7997 /// across all subtarget feature sets.
7998 static SDValue lowerVectorShuffleAsElementInsertion(
7999     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
8000     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8001   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8002   MVT ExtVT = VT;
8003   MVT EltVT = VT.getVectorElementType();
8004
8005   int V2Index = std::find_if(Mask.begin(), Mask.end(),
8006                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
8007                 Mask.begin();
8008   bool IsV1Zeroable = true;
8009   for (int i = 0, Size = Mask.size(); i < Size; ++i)
8010     if (i != V2Index && !Zeroable[i]) {
8011       IsV1Zeroable = false;
8012       break;
8013     }
8014
8015   // Check for a single input from a SCALAR_TO_VECTOR node.
8016   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
8017   // all the smarts here sunk into that routine. However, the current
8018   // lowering of BUILD_VECTOR makes that nearly impossible until the old
8019   // vector shuffle lowering is dead.
8020   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
8021                                                DAG);
8022   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
8023     // We need to zext the scalar if it is smaller than an i32.
8024     V2S = DAG.getBitcast(EltVT, V2S);
8025     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
8026       // Using zext to expand a narrow element won't work for non-zero
8027       // insertions.
8028       if (!IsV1Zeroable)
8029         return SDValue();
8030
8031       // Zero-extend directly to i32.
8032       ExtVT = MVT::v4i32;
8033       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
8034     }
8035     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
8036   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
8037              EltVT == MVT::i16) {
8038     // Either not inserting from the low element of the input or the input
8039     // element size is too small to use VZEXT_MOVL to clear the high bits.
8040     return SDValue();
8041   }
8042
8043   if (!IsV1Zeroable) {
8044     // If V1 can't be treated as a zero vector we have fewer options to lower
8045     // this. We can't support integer vectors or non-zero targets cheaply, and
8046     // the V1 elements can't be permuted in any way.
8047     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8048     if (!VT.isFloatingPoint() || V2Index != 0)
8049       return SDValue();
8050     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8051     V1Mask[V2Index] = -1;
8052     if (!isNoopShuffleMask(V1Mask))
8053       return SDValue();
8054     // This is essentially a special case blend operation, but if we have
8055     // general purpose blend operations, they are always faster. Bail and let
8056     // the rest of the lowering handle these as blends.
8057     if (Subtarget->hasSSE41())
8058       return SDValue();
8059
8060     // Otherwise, use MOVSD or MOVSS.
8061     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8062            "Only two types of floating point element types to handle!");
8063     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8064                        ExtVT, V1, V2);
8065   }
8066
8067   // This lowering only works for the low element with floating point vectors.
8068   if (VT.isFloatingPoint() && V2Index != 0)
8069     return SDValue();
8070
8071   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8072   if (ExtVT != VT)
8073     V2 = DAG.getBitcast(VT, V2);
8074
8075   if (V2Index != 0) {
8076     // If we have 4 or fewer lanes we can cheaply shuffle the element into
8077     // the desired position. Otherwise it is more efficient to do a vector
8078     // shift left. We know that we can do a vector shift left because all
8079     // the inputs are zero.
8080     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8081       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8082       V2Shuffle[V2Index] = 0;
8083       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8084     } else {
8085       V2 = DAG.getBitcast(MVT::v2i64, V2);
8086       V2 = DAG.getNode(
8087           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8088           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8089                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8090                               DAG.getDataLayout(), VT)));
8091       V2 = DAG.getBitcast(VT, V2);
8092     }
8093   }
8094   return V2;
8095 }
8096
8097 /// \brief Try to lower broadcast of a single - truncated - integer element,
8098 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8099 ///
8100 /// This assumes we have AVX2.
8101 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
8102                                                   int BroadcastIdx,
8103                                                   const X86Subtarget *Subtarget,
8104                                                   SelectionDAG &DAG) {
8105   assert(Subtarget->hasAVX2() &&
8106          "We can only lower integer broadcasts with AVX2!");
8107
8108   EVT EltVT = VT.getVectorElementType();
8109   EVT V0VT = V0.getValueType();
8110
8111   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8112   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8113
8114   EVT V0EltVT = V0VT.getVectorElementType();
8115   if (!V0EltVT.isInteger())
8116     return SDValue();
8117
8118   const unsigned EltSize = EltVT.getSizeInBits();
8119   const unsigned V0EltSize = V0EltVT.getSizeInBits();
8120
8121   // This is only a truncation if the original element type is larger.
8122   if (V0EltSize <= EltSize)
8123     return SDValue();
8124
8125   assert(((V0EltSize % EltSize) == 0) &&
8126          "Scalar type sizes must all be powers of 2 on x86!");
8127
8128   const unsigned V0Opc = V0.getOpcode();
8129   const unsigned Scale = V0EltSize / EltSize;
8130   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8131
8132   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8133       V0Opc != ISD::BUILD_VECTOR)
8134     return SDValue();
8135
8136   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8137
8138   // If we're extracting non-least-significant bits, shift so we can truncate.
8139   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8140   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8141   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8142   if (const int OffsetIdx = BroadcastIdx % Scale)
8143     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8144             DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8145
8146   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8147                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8148 }
8149
8150 /// \brief Try to lower broadcast of a single element.
8151 ///
8152 /// For convenience, this code also bundles all of the subtarget feature set
8153 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8154 /// a convenient way to factor it out.
8155 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8156 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8157                                              ArrayRef<int> Mask,
8158                                              const X86Subtarget *Subtarget,
8159                                              SelectionDAG &DAG) {
8160   if (!Subtarget->hasAVX())
8161     return SDValue();
8162   if (VT.isInteger() && !Subtarget->hasAVX2())
8163     return SDValue();
8164
8165   // Check that the mask is a broadcast.
8166   int BroadcastIdx = -1;
8167   for (int M : Mask)
8168     if (M >= 0 && BroadcastIdx == -1)
8169       BroadcastIdx = M;
8170     else if (M >= 0 && M != BroadcastIdx)
8171       return SDValue();
8172
8173   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8174                                             "a sorted mask where the broadcast "
8175                                             "comes from V1.");
8176
8177   // Go up the chain of (vector) values to find a scalar load that we can
8178   // combine with the broadcast.
8179   for (;;) {
8180     switch (V.getOpcode()) {
8181     case ISD::CONCAT_VECTORS: {
8182       int OperandSize = Mask.size() / V.getNumOperands();
8183       V = V.getOperand(BroadcastIdx / OperandSize);
8184       BroadcastIdx %= OperandSize;
8185       continue;
8186     }
8187
8188     case ISD::INSERT_SUBVECTOR: {
8189       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8190       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8191       if (!ConstantIdx)
8192         break;
8193
8194       int BeginIdx = (int)ConstantIdx->getZExtValue();
8195       int EndIdx =
8196           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8197       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8198         BroadcastIdx -= BeginIdx;
8199         V = VInner;
8200       } else {
8201         V = VOuter;
8202       }
8203       continue;
8204     }
8205     }
8206     break;
8207   }
8208
8209   // Check if this is a broadcast of a scalar. We special case lowering
8210   // for scalars so that we can more effectively fold with loads.
8211   // First, look through bitcast: if the original value has a larger element
8212   // type than the shuffle, the broadcast element is in essence truncated.
8213   // Make that explicit to ease folding.
8214   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8215     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8216             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8217       return TruncBroadcast;
8218
8219   MVT BroadcastVT = VT;
8220
8221   // Peek through any bitcast (only useful for loads).
8222   SDValue BC = V;
8223   while (BC.getOpcode() == ISD::BITCAST)
8224     BC = BC.getOperand(0);
8225
8226   // Also check the simpler case, where we can directly reuse the scalar.
8227   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8228       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8229     V = V.getOperand(BroadcastIdx);
8230
8231     // If the scalar isn't a load, we can't broadcast from it in AVX1.
8232     // Only AVX2 has register broadcasts.
8233     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8234       return SDValue();
8235   } else if (MayFoldLoad(BC) && !cast<LoadSDNode>(BC)->isVolatile()) {
8236     // 32-bit targets need to load i64 as a f64 and then bitcast the result.
8237     if (!Subtarget->is64Bit() && VT.getScalarType() == MVT::i64)
8238       BroadcastVT = MVT::getVectorVT(MVT::f64, VT.getVectorNumElements());
8239
8240     // If we are broadcasting a load that is only used by the shuffle
8241     // then we can reduce the vector load to the broadcasted scalar load.
8242     LoadSDNode *Ld = cast<LoadSDNode>(BC);
8243     SDValue BaseAddr = Ld->getOperand(1);
8244     EVT AddrVT = BaseAddr.getValueType();
8245     EVT SVT = BroadcastVT.getScalarType();
8246     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8247     SDValue NewAddr = DAG.getNode(
8248         ISD::ADD, DL, AddrVT, BaseAddr,
8249         DAG.getConstant(Offset, DL, AddrVT));
8250     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8251                     DAG.getMachineFunction().getMachineMemOperand(
8252                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8253   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8254     // We can't broadcast from a vector register without AVX2, and we can only
8255     // broadcast from the zero-element of a vector register.
8256     return SDValue();
8257   }
8258
8259   V = DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, V);
8260   return DAG.getBitcast(VT, V);
8261 }
8262
8263 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8264 // INSERTPS when the V1 elements are already in the correct locations
8265 // because otherwise we can just always use two SHUFPS instructions which
8266 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8267 // perform INSERTPS if a single V1 element is out of place and all V2
8268 // elements are zeroable.
8269 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8270                                             ArrayRef<int> Mask,
8271                                             SelectionDAG &DAG) {
8272   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8273   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8274   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8275   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8276
8277   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8278
8279   unsigned ZMask = 0;
8280   int V1DstIndex = -1;
8281   int V2DstIndex = -1;
8282   bool V1UsedInPlace = false;
8283
8284   for (int i = 0; i < 4; ++i) {
8285     // Synthesize a zero mask from the zeroable elements (includes undefs).
8286     if (Zeroable[i]) {
8287       ZMask |= 1 << i;
8288       continue;
8289     }
8290
8291     // Flag if we use any V1 inputs in place.
8292     if (i == Mask[i]) {
8293       V1UsedInPlace = true;
8294       continue;
8295     }
8296
8297     // We can only insert a single non-zeroable element.
8298     if (V1DstIndex != -1 || V2DstIndex != -1)
8299       return SDValue();
8300
8301     if (Mask[i] < 4) {
8302       // V1 input out of place for insertion.
8303       V1DstIndex = i;
8304     } else {
8305       // V2 input for insertion.
8306       V2DstIndex = i;
8307     }
8308   }
8309
8310   // Don't bother if we have no (non-zeroable) element for insertion.
8311   if (V1DstIndex == -1 && V2DstIndex == -1)
8312     return SDValue();
8313
8314   // Determine element insertion src/dst indices. The src index is from the
8315   // start of the inserted vector, not the start of the concatenated vector.
8316   unsigned V2SrcIndex = 0;
8317   if (V1DstIndex != -1) {
8318     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8319     // and don't use the original V2 at all.
8320     V2SrcIndex = Mask[V1DstIndex];
8321     V2DstIndex = V1DstIndex;
8322     V2 = V1;
8323   } else {
8324     V2SrcIndex = Mask[V2DstIndex] - 4;
8325   }
8326
8327   // If no V1 inputs are used in place, then the result is created only from
8328   // the zero mask and the V2 insertion - so remove V1 dependency.
8329   if (!V1UsedInPlace)
8330     V1 = DAG.getUNDEF(MVT::v4f32);
8331
8332   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8333   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8334
8335   // Insert the V2 element into the desired position.
8336   SDLoc DL(Op);
8337   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8338                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8339 }
8340
8341 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8342 /// UNPCK instruction.
8343 ///
8344 /// This specifically targets cases where we end up with alternating between
8345 /// the two inputs, and so can permute them into something that feeds a single
8346 /// UNPCK instruction. Note that this routine only targets integer vectors
8347 /// because for floating point vectors we have a generalized SHUFPS lowering
8348 /// strategy that handles everything that doesn't *exactly* match an unpack,
8349 /// making this clever lowering unnecessary.
8350 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8351                                                     SDValue V1, SDValue V2,
8352                                                     ArrayRef<int> Mask,
8353                                                     SelectionDAG &DAG) {
8354   assert(!VT.isFloatingPoint() &&
8355          "This routine only supports integer vectors.");
8356   assert(!isSingleInputShuffleMask(Mask) &&
8357          "This routine should only be used when blending two inputs.");
8358   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8359
8360   int Size = Mask.size();
8361
8362   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8363     return M >= 0 && M % Size < Size / 2;
8364   });
8365   int NumHiInputs = std::count_if(
8366       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8367
8368   bool UnpackLo = NumLoInputs >= NumHiInputs;
8369
8370   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8371     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8372     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8373
8374     for (int i = 0; i < Size; ++i) {
8375       if (Mask[i] < 0)
8376         continue;
8377
8378       // Each element of the unpack contains Scale elements from this mask.
8379       int UnpackIdx = i / Scale;
8380
8381       // We only handle the case where V1 feeds the first slots of the unpack.
8382       // We rely on canonicalization to ensure this is the case.
8383       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8384         return SDValue();
8385
8386       // Setup the mask for this input. The indexing is tricky as we have to
8387       // handle the unpack stride.
8388       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8389       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8390           Mask[i] % Size;
8391     }
8392
8393     // If we will have to shuffle both inputs to use the unpack, check whether
8394     // we can just unpack first and shuffle the result. If so, skip this unpack.
8395     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8396         !isNoopShuffleMask(V2Mask))
8397       return SDValue();
8398
8399     // Shuffle the inputs into place.
8400     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8401     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8402
8403     // Cast the inputs to the type we will use to unpack them.
8404     V1 = DAG.getBitcast(UnpackVT, V1);
8405     V2 = DAG.getBitcast(UnpackVT, V2);
8406
8407     // Unpack the inputs and cast the result back to the desired type.
8408     return DAG.getBitcast(
8409         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8410                         UnpackVT, V1, V2));
8411   };
8412
8413   // We try each unpack from the largest to the smallest to try and find one
8414   // that fits this mask.
8415   int OrigNumElements = VT.getVectorNumElements();
8416   int OrigScalarSize = VT.getScalarSizeInBits();
8417   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8418     int Scale = ScalarSize / OrigScalarSize;
8419     int NumElements = OrigNumElements / Scale;
8420     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8421     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8422       return Unpack;
8423   }
8424
8425   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8426   // initial unpack.
8427   if (NumLoInputs == 0 || NumHiInputs == 0) {
8428     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8429            "We have to have *some* inputs!");
8430     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8431
8432     // FIXME: We could consider the total complexity of the permute of each
8433     // possible unpacking. Or at the least we should consider how many
8434     // half-crossings are created.
8435     // FIXME: We could consider commuting the unpacks.
8436
8437     SmallVector<int, 32> PermMask;
8438     PermMask.assign(Size, -1);
8439     for (int i = 0; i < Size; ++i) {
8440       if (Mask[i] < 0)
8441         continue;
8442
8443       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8444
8445       PermMask[i] =
8446           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8447     }
8448     return DAG.getVectorShuffle(
8449         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8450                             DL, VT, V1, V2),
8451         DAG.getUNDEF(VT), PermMask);
8452   }
8453
8454   return SDValue();
8455 }
8456
8457 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8458 ///
8459 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8460 /// support for floating point shuffles but not integer shuffles. These
8461 /// instructions will incur a domain crossing penalty on some chips though so
8462 /// it is better to avoid lowering through this for integer vectors where
8463 /// possible.
8464 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8465                                        const X86Subtarget *Subtarget,
8466                                        SelectionDAG &DAG) {
8467   SDLoc DL(Op);
8468   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8469   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8470   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8471   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8472   ArrayRef<int> Mask = SVOp->getMask();
8473   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8474
8475   if (isSingleInputShuffleMask(Mask)) {
8476     // Use low duplicate instructions for masks that match their pattern.
8477     if (Subtarget->hasSSE3())
8478       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8479         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8480
8481     // Straight shuffle of a single input vector. Simulate this by using the
8482     // single input as both of the "inputs" to this instruction..
8483     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8484
8485     if (Subtarget->hasAVX()) {
8486       // If we have AVX, we can use VPERMILPS which will allow folding a load
8487       // into the shuffle.
8488       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8489                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8490     }
8491
8492     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8493                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8494   }
8495   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8496   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8497
8498   // If we have a single input, insert that into V1 if we can do so cheaply.
8499   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8500     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8501             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8502       return Insertion;
8503     // Try inverting the insertion since for v2 masks it is easy to do and we
8504     // can't reliably sort the mask one way or the other.
8505     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8506                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8507     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8508             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8509       return Insertion;
8510   }
8511
8512   // Try to use one of the special instruction patterns to handle two common
8513   // blend patterns if a zero-blend above didn't work.
8514   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8515       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8516     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8517       // We can either use a special instruction to load over the low double or
8518       // to move just the low double.
8519       return DAG.getNode(
8520           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8521           DL, MVT::v2f64, V2,
8522           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8523
8524   if (Subtarget->hasSSE41())
8525     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8526                                                   Subtarget, DAG))
8527       return Blend;
8528
8529   // Use dedicated unpack instructions for masks that match their pattern.
8530   if (SDValue V =
8531           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8532     return V;
8533
8534   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8535   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8536                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8537 }
8538
8539 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8540 ///
8541 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8542 /// the integer unit to minimize domain crossing penalties. However, for blends
8543 /// it falls back to the floating point shuffle operation with appropriate bit
8544 /// casting.
8545 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8546                                        const X86Subtarget *Subtarget,
8547                                        SelectionDAG &DAG) {
8548   SDLoc DL(Op);
8549   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8550   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8551   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8552   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8553   ArrayRef<int> Mask = SVOp->getMask();
8554   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8555
8556   if (isSingleInputShuffleMask(Mask)) {
8557     // Check for being able to broadcast a single element.
8558     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8559                                                           Mask, Subtarget, DAG))
8560       return Broadcast;
8561
8562     // Straight shuffle of a single input vector. For everything from SSE2
8563     // onward this has a single fast instruction with no scary immediates.
8564     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8565     V1 = DAG.getBitcast(MVT::v4i32, V1);
8566     int WidenedMask[4] = {
8567         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8568         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8569     return DAG.getBitcast(
8570         MVT::v2i64,
8571         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8572                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8573   }
8574   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8575   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8576   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8577   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8578
8579   // If we have a blend of two PACKUS operations an the blend aligns with the
8580   // low and half halves, we can just merge the PACKUS operations. This is
8581   // particularly important as it lets us merge shuffles that this routine itself
8582   // creates.
8583   auto GetPackNode = [](SDValue V) {
8584     while (V.getOpcode() == ISD::BITCAST)
8585       V = V.getOperand(0);
8586
8587     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8588   };
8589   if (SDValue V1Pack = GetPackNode(V1))
8590     if (SDValue V2Pack = GetPackNode(V2))
8591       return DAG.getBitcast(MVT::v2i64,
8592                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8593                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8594                                                      : V1Pack.getOperand(1),
8595                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8596                                                      : V2Pack.getOperand(1)));
8597
8598   // Try to use shift instructions.
8599   if (SDValue Shift =
8600           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8601     return Shift;
8602
8603   // When loading a scalar and then shuffling it into a vector we can often do
8604   // the insertion cheaply.
8605   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8606           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8607     return Insertion;
8608   // Try inverting the insertion since for v2 masks it is easy to do and we
8609   // can't reliably sort the mask one way or the other.
8610   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8611   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8612           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8613     return Insertion;
8614
8615   // We have different paths for blend lowering, but they all must use the
8616   // *exact* same predicate.
8617   bool IsBlendSupported = Subtarget->hasSSE41();
8618   if (IsBlendSupported)
8619     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8620                                                   Subtarget, DAG))
8621       return Blend;
8622
8623   // Use dedicated unpack instructions for masks that match their pattern.
8624   if (SDValue V =
8625           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8626     return V;
8627
8628   // Try to use byte rotation instructions.
8629   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8630   if (Subtarget->hasSSSE3())
8631     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8632             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8633       return Rotate;
8634
8635   // If we have direct support for blends, we should lower by decomposing into
8636   // a permute. That will be faster than the domain cross.
8637   if (IsBlendSupported)
8638     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8639                                                       Mask, DAG);
8640
8641   // We implement this with SHUFPD which is pretty lame because it will likely
8642   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8643   // However, all the alternatives are still more cycles and newer chips don't
8644   // have this problem. It would be really nice if x86 had better shuffles here.
8645   V1 = DAG.getBitcast(MVT::v2f64, V1);
8646   V2 = DAG.getBitcast(MVT::v2f64, V2);
8647   return DAG.getBitcast(MVT::v2i64,
8648                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8649 }
8650
8651 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8652 ///
8653 /// This is used to disable more specialized lowerings when the shufps lowering
8654 /// will happen to be efficient.
8655 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8656   // This routine only handles 128-bit shufps.
8657   assert(Mask.size() == 4 && "Unsupported mask size!");
8658
8659   // To lower with a single SHUFPS we need to have the low half and high half
8660   // each requiring a single input.
8661   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8662     return false;
8663   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8664     return false;
8665
8666   return true;
8667 }
8668
8669 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8670 ///
8671 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8672 /// It makes no assumptions about whether this is the *best* lowering, it simply
8673 /// uses it.
8674 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8675                                             ArrayRef<int> Mask, SDValue V1,
8676                                             SDValue V2, SelectionDAG &DAG) {
8677   SDValue LowV = V1, HighV = V2;
8678   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8679
8680   int NumV2Elements =
8681       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8682
8683   if (NumV2Elements == 1) {
8684     int V2Index =
8685         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8686         Mask.begin();
8687
8688     // Compute the index adjacent to V2Index and in the same half by toggling
8689     // the low bit.
8690     int V2AdjIndex = V2Index ^ 1;
8691
8692     if (Mask[V2AdjIndex] == -1) {
8693       // Handles all the cases where we have a single V2 element and an undef.
8694       // This will only ever happen in the high lanes because we commute the
8695       // vector otherwise.
8696       if (V2Index < 2)
8697         std::swap(LowV, HighV);
8698       NewMask[V2Index] -= 4;
8699     } else {
8700       // Handle the case where the V2 element ends up adjacent to a V1 element.
8701       // To make this work, blend them together as the first step.
8702       int V1Index = V2AdjIndex;
8703       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8704       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8705                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8706
8707       // Now proceed to reconstruct the final blend as we have the necessary
8708       // high or low half formed.
8709       if (V2Index < 2) {
8710         LowV = V2;
8711         HighV = V1;
8712       } else {
8713         HighV = V2;
8714       }
8715       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8716       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8717     }
8718   } else if (NumV2Elements == 2) {
8719     if (Mask[0] < 4 && Mask[1] < 4) {
8720       // Handle the easy case where we have V1 in the low lanes and V2 in the
8721       // high lanes.
8722       NewMask[2] -= 4;
8723       NewMask[3] -= 4;
8724     } else if (Mask[2] < 4 && Mask[3] < 4) {
8725       // We also handle the reversed case because this utility may get called
8726       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8727       // arrange things in the right direction.
8728       NewMask[0] -= 4;
8729       NewMask[1] -= 4;
8730       HighV = V1;
8731       LowV = V2;
8732     } else {
8733       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8734       // trying to place elements directly, just blend them and set up the final
8735       // shuffle to place them.
8736
8737       // The first two blend mask elements are for V1, the second two are for
8738       // V2.
8739       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8740                           Mask[2] < 4 ? Mask[2] : Mask[3],
8741                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8742                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8743       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8744                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8745
8746       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8747       // a blend.
8748       LowV = HighV = V1;
8749       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8750       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8751       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8752       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8753     }
8754   }
8755   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8756                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8757 }
8758
8759 /// \brief Lower 4-lane 32-bit floating point shuffles.
8760 ///
8761 /// Uses instructions exclusively from the floating point unit to minimize
8762 /// domain crossing penalties, as these are sufficient to implement all v4f32
8763 /// shuffles.
8764 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8765                                        const X86Subtarget *Subtarget,
8766                                        SelectionDAG &DAG) {
8767   SDLoc DL(Op);
8768   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8769   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8770   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8771   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8772   ArrayRef<int> Mask = SVOp->getMask();
8773   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8774
8775   int NumV2Elements =
8776       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8777
8778   if (NumV2Elements == 0) {
8779     // Check for being able to broadcast a single element.
8780     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8781                                                           Mask, Subtarget, DAG))
8782       return Broadcast;
8783
8784     // Use even/odd duplicate instructions for masks that match their pattern.
8785     if (Subtarget->hasSSE3()) {
8786       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8787         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8788       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8789         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8790     }
8791
8792     if (Subtarget->hasAVX()) {
8793       // If we have AVX, we can use VPERMILPS which will allow folding a load
8794       // into the shuffle.
8795       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8796                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8797     }
8798
8799     // Otherwise, use a straight shuffle of a single input vector. We pass the
8800     // input vector to both operands to simulate this with a SHUFPS.
8801     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8802                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8803   }
8804
8805   // There are special ways we can lower some single-element blends. However, we
8806   // have custom ways we can lower more complex single-element blends below that
8807   // we defer to if both this and BLENDPS fail to match, so restrict this to
8808   // when the V2 input is targeting element 0 of the mask -- that is the fast
8809   // case here.
8810   if (NumV2Elements == 1 && Mask[0] >= 4)
8811     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8812                                                          Mask, Subtarget, DAG))
8813       return V;
8814
8815   if (Subtarget->hasSSE41()) {
8816     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8817                                                   Subtarget, DAG))
8818       return Blend;
8819
8820     // Use INSERTPS if we can complete the shuffle efficiently.
8821     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8822       return V;
8823
8824     if (!isSingleSHUFPSMask(Mask))
8825       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8826               DL, MVT::v4f32, V1, V2, Mask, DAG))
8827         return BlendPerm;
8828   }
8829
8830   // Use dedicated unpack instructions for masks that match their pattern.
8831   if (SDValue V =
8832           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8833     return V;
8834
8835   // Otherwise fall back to a SHUFPS lowering strategy.
8836   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8837 }
8838
8839 /// \brief Lower 4-lane i32 vector shuffles.
8840 ///
8841 /// We try to handle these with integer-domain shuffles where we can, but for
8842 /// blends we use the floating point domain blend instructions.
8843 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8844                                        const X86Subtarget *Subtarget,
8845                                        SelectionDAG &DAG) {
8846   SDLoc DL(Op);
8847   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8848   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8849   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8850   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8851   ArrayRef<int> Mask = SVOp->getMask();
8852   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8853
8854   // Whenever we can lower this as a zext, that instruction is strictly faster
8855   // than any alternative. It also allows us to fold memory operands into the
8856   // shuffle in many cases.
8857   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8858                                                          Mask, Subtarget, DAG))
8859     return ZExt;
8860
8861   int NumV2Elements =
8862       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8863
8864   if (NumV2Elements == 0) {
8865     // Check for being able to broadcast a single element.
8866     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8867                                                           Mask, Subtarget, DAG))
8868       return Broadcast;
8869
8870     // Straight shuffle of a single input vector. For everything from SSE2
8871     // onward this has a single fast instruction with no scary immediates.
8872     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8873     // but we aren't actually going to use the UNPCK instruction because doing
8874     // so prevents folding a load into this instruction or making a copy.
8875     const int UnpackLoMask[] = {0, 0, 1, 1};
8876     const int UnpackHiMask[] = {2, 2, 3, 3};
8877     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8878       Mask = UnpackLoMask;
8879     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8880       Mask = UnpackHiMask;
8881
8882     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8883                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8884   }
8885
8886   // Try to use shift instructions.
8887   if (SDValue Shift =
8888           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8889     return Shift;
8890
8891   // There are special ways we can lower some single-element blends.
8892   if (NumV2Elements == 1)
8893     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8894                                                          Mask, Subtarget, DAG))
8895       return V;
8896
8897   // We have different paths for blend lowering, but they all must use the
8898   // *exact* same predicate.
8899   bool IsBlendSupported = Subtarget->hasSSE41();
8900   if (IsBlendSupported)
8901     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8902                                                   Subtarget, DAG))
8903       return Blend;
8904
8905   if (SDValue Masked =
8906           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8907     return Masked;
8908
8909   // Use dedicated unpack instructions for masks that match their pattern.
8910   if (SDValue V =
8911           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8912     return V;
8913
8914   // Try to use byte rotation instructions.
8915   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8916   if (Subtarget->hasSSSE3())
8917     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8918             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8919       return Rotate;
8920
8921   // If we have direct support for blends, we should lower by decomposing into
8922   // a permute. That will be faster than the domain cross.
8923   if (IsBlendSupported)
8924     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8925                                                       Mask, DAG);
8926
8927   // Try to lower by permuting the inputs into an unpack instruction.
8928   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8929                                                             V2, Mask, DAG))
8930     return Unpack;
8931
8932   // We implement this with SHUFPS because it can blend from two vectors.
8933   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8934   // up the inputs, bypassing domain shift penalties that we would encur if we
8935   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8936   // relevant.
8937   return DAG.getBitcast(
8938       MVT::v4i32,
8939       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8940                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8941 }
8942
8943 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8944 /// shuffle lowering, and the most complex part.
8945 ///
8946 /// The lowering strategy is to try to form pairs of input lanes which are
8947 /// targeted at the same half of the final vector, and then use a dword shuffle
8948 /// to place them onto the right half, and finally unpack the paired lanes into
8949 /// their final position.
8950 ///
8951 /// The exact breakdown of how to form these dword pairs and align them on the
8952 /// correct sides is really tricky. See the comments within the function for
8953 /// more of the details.
8954 ///
8955 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8956 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8957 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8958 /// vector, form the analogous 128-bit 8-element Mask.
8959 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8960     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8961     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8962   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8963   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8964
8965   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8966   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8967   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8968
8969   SmallVector<int, 4> LoInputs;
8970   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8971                [](int M) { return M >= 0; });
8972   std::sort(LoInputs.begin(), LoInputs.end());
8973   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8974   SmallVector<int, 4> HiInputs;
8975   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8976                [](int M) { return M >= 0; });
8977   std::sort(HiInputs.begin(), HiInputs.end());
8978   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8979   int NumLToL =
8980       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8981   int NumHToL = LoInputs.size() - NumLToL;
8982   int NumLToH =
8983       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8984   int NumHToH = HiInputs.size() - NumLToH;
8985   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8986   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8987   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8988   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8989
8990   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8991   // such inputs we can swap two of the dwords across the half mark and end up
8992   // with <=2 inputs to each half in each half. Once there, we can fall through
8993   // to the generic code below. For example:
8994   //
8995   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8996   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8997   //
8998   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8999   // and an existing 2-into-2 on the other half. In this case we may have to
9000   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
9001   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
9002   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
9003   // because any other situation (including a 3-into-1 or 1-into-3 in the other
9004   // half than the one we target for fixing) will be fixed when we re-enter this
9005   // path. We will also combine away any sequence of PSHUFD instructions that
9006   // result into a single instruction. Here is an example of the tricky case:
9007   //
9008   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
9009   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
9010   //
9011   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
9012   //
9013   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
9014   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
9015   //
9016   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
9017   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
9018   //
9019   // The result is fine to be handled by the generic logic.
9020   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
9021                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
9022                           int AOffset, int BOffset) {
9023     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
9024            "Must call this with A having 3 or 1 inputs from the A half.");
9025     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
9026            "Must call this with B having 1 or 3 inputs from the B half.");
9027     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
9028            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
9029
9030     bool ThreeAInputs = AToAInputs.size() == 3;
9031
9032     // Compute the index of dword with only one word among the three inputs in
9033     // a half by taking the sum of the half with three inputs and subtracting
9034     // the sum of the actual three inputs. The difference is the remaining
9035     // slot.
9036     int ADWord, BDWord;
9037     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
9038     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
9039     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
9040     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
9041     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
9042     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
9043     int TripleNonInputIdx =
9044         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
9045     TripleDWord = TripleNonInputIdx / 2;
9046
9047     // We use xor with one to compute the adjacent DWord to whichever one the
9048     // OneInput is in.
9049     OneInputDWord = (OneInput / 2) ^ 1;
9050
9051     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
9052     // and BToA inputs. If there is also such a problem with the BToB and AToB
9053     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
9054     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
9055     // is essential that we don't *create* a 3<-1 as then we might oscillate.
9056     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
9057       // Compute how many inputs will be flipped by swapping these DWords. We
9058       // need
9059       // to balance this to ensure we don't form a 3-1 shuffle in the other
9060       // half.
9061       int NumFlippedAToBInputs =
9062           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9063           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9064       int NumFlippedBToBInputs =
9065           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9066           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9067       if ((NumFlippedAToBInputs == 1 &&
9068            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9069           (NumFlippedBToBInputs == 1 &&
9070            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9071         // We choose whether to fix the A half or B half based on whether that
9072         // half has zero flipped inputs. At zero, we may not be able to fix it
9073         // with that half. We also bias towards fixing the B half because that
9074         // will more commonly be the high half, and we have to bias one way.
9075         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9076                                                        ArrayRef<int> Inputs) {
9077           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9078           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9079                                          PinnedIdx ^ 1) != Inputs.end();
9080           // Determine whether the free index is in the flipped dword or the
9081           // unflipped dword based on where the pinned index is. We use this bit
9082           // in an xor to conditionally select the adjacent dword.
9083           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9084           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9085                                              FixFreeIdx) != Inputs.end();
9086           if (IsFixIdxInput == IsFixFreeIdxInput)
9087             FixFreeIdx += 1;
9088           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9089                                         FixFreeIdx) != Inputs.end();
9090           assert(IsFixIdxInput != IsFixFreeIdxInput &&
9091                  "We need to be changing the number of flipped inputs!");
9092           int PSHUFHalfMask[] = {0, 1, 2, 3};
9093           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9094           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9095                           MVT::v8i16, V,
9096                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9097
9098           for (int &M : Mask)
9099             if (M != -1 && M == FixIdx)
9100               M = FixFreeIdx;
9101             else if (M != -1 && M == FixFreeIdx)
9102               M = FixIdx;
9103         };
9104         if (NumFlippedBToBInputs != 0) {
9105           int BPinnedIdx =
9106               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9107           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9108         } else {
9109           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9110           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9111           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9112         }
9113       }
9114     }
9115
9116     int PSHUFDMask[] = {0, 1, 2, 3};
9117     PSHUFDMask[ADWord] = BDWord;
9118     PSHUFDMask[BDWord] = ADWord;
9119     V = DAG.getBitcast(
9120         VT,
9121         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9122                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9123
9124     // Adjust the mask to match the new locations of A and B.
9125     for (int &M : Mask)
9126       if (M != -1 && M/2 == ADWord)
9127         M = 2 * BDWord + M % 2;
9128       else if (M != -1 && M/2 == BDWord)
9129         M = 2 * ADWord + M % 2;
9130
9131     // Recurse back into this routine to re-compute state now that this isn't
9132     // a 3 and 1 problem.
9133     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9134                                                      DAG);
9135   };
9136   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9137     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9138   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9139     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9140
9141   // At this point there are at most two inputs to the low and high halves from
9142   // each half. That means the inputs can always be grouped into dwords and
9143   // those dwords can then be moved to the correct half with a dword shuffle.
9144   // We use at most one low and one high word shuffle to collect these paired
9145   // inputs into dwords, and finally a dword shuffle to place them.
9146   int PSHUFLMask[4] = {-1, -1, -1, -1};
9147   int PSHUFHMask[4] = {-1, -1, -1, -1};
9148   int PSHUFDMask[4] = {-1, -1, -1, -1};
9149
9150   // First fix the masks for all the inputs that are staying in their
9151   // original halves. This will then dictate the targets of the cross-half
9152   // shuffles.
9153   auto fixInPlaceInputs =
9154       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9155                     MutableArrayRef<int> SourceHalfMask,
9156                     MutableArrayRef<int> HalfMask, int HalfOffset) {
9157     if (InPlaceInputs.empty())
9158       return;
9159     if (InPlaceInputs.size() == 1) {
9160       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9161           InPlaceInputs[0] - HalfOffset;
9162       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9163       return;
9164     }
9165     if (IncomingInputs.empty()) {
9166       // Just fix all of the in place inputs.
9167       for (int Input : InPlaceInputs) {
9168         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9169         PSHUFDMask[Input / 2] = Input / 2;
9170       }
9171       return;
9172     }
9173
9174     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9175     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9176         InPlaceInputs[0] - HalfOffset;
9177     // Put the second input next to the first so that they are packed into
9178     // a dword. We find the adjacent index by toggling the low bit.
9179     int AdjIndex = InPlaceInputs[0] ^ 1;
9180     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9181     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9182     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9183   };
9184   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9185   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9186
9187   // Now gather the cross-half inputs and place them into a free dword of
9188   // their target half.
9189   // FIXME: This operation could almost certainly be simplified dramatically to
9190   // look more like the 3-1 fixing operation.
9191   auto moveInputsToRightHalf = [&PSHUFDMask](
9192       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9193       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9194       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9195       int DestOffset) {
9196     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9197       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9198     };
9199     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9200                                                int Word) {
9201       int LowWord = Word & ~1;
9202       int HighWord = Word | 1;
9203       return isWordClobbered(SourceHalfMask, LowWord) ||
9204              isWordClobbered(SourceHalfMask, HighWord);
9205     };
9206
9207     if (IncomingInputs.empty())
9208       return;
9209
9210     if (ExistingInputs.empty()) {
9211       // Map any dwords with inputs from them into the right half.
9212       for (int Input : IncomingInputs) {
9213         // If the source half mask maps over the inputs, turn those into
9214         // swaps and use the swapped lane.
9215         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9216           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9217             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9218                 Input - SourceOffset;
9219             // We have to swap the uses in our half mask in one sweep.
9220             for (int &M : HalfMask)
9221               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9222                 M = Input;
9223               else if (M == Input)
9224                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9225           } else {
9226             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9227                        Input - SourceOffset &&
9228                    "Previous placement doesn't match!");
9229           }
9230           // Note that this correctly re-maps both when we do a swap and when
9231           // we observe the other side of the swap above. We rely on that to
9232           // avoid swapping the members of the input list directly.
9233           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9234         }
9235
9236         // Map the input's dword into the correct half.
9237         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9238           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9239         else
9240           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9241                      Input / 2 &&
9242                  "Previous placement doesn't match!");
9243       }
9244
9245       // And just directly shift any other-half mask elements to be same-half
9246       // as we will have mirrored the dword containing the element into the
9247       // same position within that half.
9248       for (int &M : HalfMask)
9249         if (M >= SourceOffset && M < SourceOffset + 4) {
9250           M = M - SourceOffset + DestOffset;
9251           assert(M >= 0 && "This should never wrap below zero!");
9252         }
9253       return;
9254     }
9255
9256     // Ensure we have the input in a viable dword of its current half. This
9257     // is particularly tricky because the original position may be clobbered
9258     // by inputs being moved and *staying* in that half.
9259     if (IncomingInputs.size() == 1) {
9260       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9261         int InputFixed = std::find(std::begin(SourceHalfMask),
9262                                    std::end(SourceHalfMask), -1) -
9263                          std::begin(SourceHalfMask) + SourceOffset;
9264         SourceHalfMask[InputFixed - SourceOffset] =
9265             IncomingInputs[0] - SourceOffset;
9266         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9267                      InputFixed);
9268         IncomingInputs[0] = InputFixed;
9269       }
9270     } else if (IncomingInputs.size() == 2) {
9271       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9272           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9273         // We have two non-adjacent or clobbered inputs we need to extract from
9274         // the source half. To do this, we need to map them into some adjacent
9275         // dword slot in the source mask.
9276         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9277                               IncomingInputs[1] - SourceOffset};
9278
9279         // If there is a free slot in the source half mask adjacent to one of
9280         // the inputs, place the other input in it. We use (Index XOR 1) to
9281         // compute an adjacent index.
9282         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9283             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9284           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9285           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9286           InputsFixed[1] = InputsFixed[0] ^ 1;
9287         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9288                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9289           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9290           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9291           InputsFixed[0] = InputsFixed[1] ^ 1;
9292         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9293                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9294           // The two inputs are in the same DWord but it is clobbered and the
9295           // adjacent DWord isn't used at all. Move both inputs to the free
9296           // slot.
9297           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9298           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9299           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9300           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9301         } else {
9302           // The only way we hit this point is if there is no clobbering
9303           // (because there are no off-half inputs to this half) and there is no
9304           // free slot adjacent to one of the inputs. In this case, we have to
9305           // swap an input with a non-input.
9306           for (int i = 0; i < 4; ++i)
9307             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9308                    "We can't handle any clobbers here!");
9309           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9310                  "Cannot have adjacent inputs here!");
9311
9312           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9313           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9314
9315           // We also have to update the final source mask in this case because
9316           // it may need to undo the above swap.
9317           for (int &M : FinalSourceHalfMask)
9318             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9319               M = InputsFixed[1] + SourceOffset;
9320             else if (M == InputsFixed[1] + SourceOffset)
9321               M = (InputsFixed[0] ^ 1) + SourceOffset;
9322
9323           InputsFixed[1] = InputsFixed[0] ^ 1;
9324         }
9325
9326         // Point everything at the fixed inputs.
9327         for (int &M : HalfMask)
9328           if (M == IncomingInputs[0])
9329             M = InputsFixed[0] + SourceOffset;
9330           else if (M == IncomingInputs[1])
9331             M = InputsFixed[1] + SourceOffset;
9332
9333         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9334         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9335       }
9336     } else {
9337       llvm_unreachable("Unhandled input size!");
9338     }
9339
9340     // Now hoist the DWord down to the right half.
9341     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9342     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9343     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9344     for (int &M : HalfMask)
9345       for (int Input : IncomingInputs)
9346         if (M == Input)
9347           M = FreeDWord * 2 + Input % 2;
9348   };
9349   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9350                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9351   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9352                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9353
9354   // Now enact all the shuffles we've computed to move the inputs into their
9355   // target half.
9356   if (!isNoopShuffleMask(PSHUFLMask))
9357     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9358                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9359   if (!isNoopShuffleMask(PSHUFHMask))
9360     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9361                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9362   if (!isNoopShuffleMask(PSHUFDMask))
9363     V = DAG.getBitcast(
9364         VT,
9365         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9366                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9367
9368   // At this point, each half should contain all its inputs, and we can then
9369   // just shuffle them into their final position.
9370   assert(std::count_if(LoMask.begin(), LoMask.end(),
9371                        [](int M) { return M >= 4; }) == 0 &&
9372          "Failed to lift all the high half inputs to the low mask!");
9373   assert(std::count_if(HiMask.begin(), HiMask.end(),
9374                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9375          "Failed to lift all the low half inputs to the high mask!");
9376
9377   // Do a half shuffle for the low mask.
9378   if (!isNoopShuffleMask(LoMask))
9379     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9380                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9381
9382   // Do a half shuffle with the high mask after shifting its values down.
9383   for (int &M : HiMask)
9384     if (M >= 0)
9385       M -= 4;
9386   if (!isNoopShuffleMask(HiMask))
9387     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9388                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9389
9390   return V;
9391 }
9392
9393 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9394 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9395                                           SDValue V2, ArrayRef<int> Mask,
9396                                           SelectionDAG &DAG, bool &V1InUse,
9397                                           bool &V2InUse) {
9398   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9399   SDValue V1Mask[16];
9400   SDValue V2Mask[16];
9401   V1InUse = false;
9402   V2InUse = false;
9403
9404   int Size = Mask.size();
9405   int Scale = 16 / Size;
9406   for (int i = 0; i < 16; ++i) {
9407     if (Mask[i / Scale] == -1) {
9408       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9409     } else {
9410       const int ZeroMask = 0x80;
9411       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9412                                           : ZeroMask;
9413       int V2Idx = Mask[i / Scale] < Size
9414                       ? ZeroMask
9415                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9416       if (Zeroable[i / Scale])
9417         V1Idx = V2Idx = ZeroMask;
9418       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9419       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9420       V1InUse |= (ZeroMask != V1Idx);
9421       V2InUse |= (ZeroMask != V2Idx);
9422     }
9423   }
9424
9425   if (V1InUse)
9426     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9427                      DAG.getBitcast(MVT::v16i8, V1),
9428                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9429   if (V2InUse)
9430     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9431                      DAG.getBitcast(MVT::v16i8, V2),
9432                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9433
9434   // If we need shuffled inputs from both, blend the two.
9435   SDValue V;
9436   if (V1InUse && V2InUse)
9437     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9438   else
9439     V = V1InUse ? V1 : V2;
9440
9441   // Cast the result back to the correct type.
9442   return DAG.getBitcast(VT, V);
9443 }
9444
9445 /// \brief Generic lowering of 8-lane i16 shuffles.
9446 ///
9447 /// This handles both single-input shuffles and combined shuffle/blends with
9448 /// two inputs. The single input shuffles are immediately delegated to
9449 /// a dedicated lowering routine.
9450 ///
9451 /// The blends are lowered in one of three fundamental ways. If there are few
9452 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9453 /// of the input is significantly cheaper when lowered as an interleaving of
9454 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9455 /// halves of the inputs separately (making them have relatively few inputs)
9456 /// and then concatenate them.
9457 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9458                                        const X86Subtarget *Subtarget,
9459                                        SelectionDAG &DAG) {
9460   SDLoc DL(Op);
9461   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9462   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9463   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9464   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9465   ArrayRef<int> OrigMask = SVOp->getMask();
9466   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9467                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9468   MutableArrayRef<int> Mask(MaskStorage);
9469
9470   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9471
9472   // Whenever we can lower this as a zext, that instruction is strictly faster
9473   // than any alternative.
9474   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9475           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9476     return ZExt;
9477
9478   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9479   (void)isV1;
9480   auto isV2 = [](int M) { return M >= 8; };
9481
9482   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9483
9484   if (NumV2Inputs == 0) {
9485     // Check for being able to broadcast a single element.
9486     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9487                                                           Mask, Subtarget, DAG))
9488       return Broadcast;
9489
9490     // Try to use shift instructions.
9491     if (SDValue Shift =
9492             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9493       return Shift;
9494
9495     // Use dedicated unpack instructions for masks that match their pattern.
9496     if (SDValue V =
9497             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9498       return V;
9499
9500     // Try to use byte rotation instructions.
9501     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9502                                                         Mask, Subtarget, DAG))
9503       return Rotate;
9504
9505     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9506                                                      Subtarget, DAG);
9507   }
9508
9509   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9510          "All single-input shuffles should be canonicalized to be V1-input "
9511          "shuffles.");
9512
9513   // Try to use shift instructions.
9514   if (SDValue Shift =
9515           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9516     return Shift;
9517
9518   // See if we can use SSE4A Extraction / Insertion.
9519   if (Subtarget->hasSSE4A())
9520     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9521       return V;
9522
9523   // There are special ways we can lower some single-element blends.
9524   if (NumV2Inputs == 1)
9525     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9526                                                          Mask, Subtarget, DAG))
9527       return V;
9528
9529   // We have different paths for blend lowering, but they all must use the
9530   // *exact* same predicate.
9531   bool IsBlendSupported = Subtarget->hasSSE41();
9532   if (IsBlendSupported)
9533     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9534                                                   Subtarget, DAG))
9535       return Blend;
9536
9537   if (SDValue Masked =
9538           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9539     return Masked;
9540
9541   // Use dedicated unpack instructions for masks that match their pattern.
9542   if (SDValue V =
9543           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9544     return V;
9545
9546   // Try to use byte rotation instructions.
9547   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9548           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9549     return Rotate;
9550
9551   if (SDValue BitBlend =
9552           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9553     return BitBlend;
9554
9555   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9556                                                             V2, Mask, DAG))
9557     return Unpack;
9558
9559   // If we can't directly blend but can use PSHUFB, that will be better as it
9560   // can both shuffle and set up the inefficient blend.
9561   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9562     bool V1InUse, V2InUse;
9563     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9564                                       V1InUse, V2InUse);
9565   }
9566
9567   // We can always bit-blend if we have to so the fallback strategy is to
9568   // decompose into single-input permutes and blends.
9569   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9570                                                       Mask, DAG);
9571 }
9572
9573 /// \brief Check whether a compaction lowering can be done by dropping even
9574 /// elements and compute how many times even elements must be dropped.
9575 ///
9576 /// This handles shuffles which take every Nth element where N is a power of
9577 /// two. Example shuffle masks:
9578 ///
9579 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9580 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9581 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9582 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9583 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9584 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9585 ///
9586 /// Any of these lanes can of course be undef.
9587 ///
9588 /// This routine only supports N <= 3.
9589 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9590 /// for larger N.
9591 ///
9592 /// \returns N above, or the number of times even elements must be dropped if
9593 /// there is such a number. Otherwise returns zero.
9594 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9595   // Figure out whether we're looping over two inputs or just one.
9596   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9597
9598   // The modulus for the shuffle vector entries is based on whether this is
9599   // a single input or not.
9600   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9601   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9602          "We should only be called with masks with a power-of-2 size!");
9603
9604   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9605
9606   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9607   // and 2^3 simultaneously. This is because we may have ambiguity with
9608   // partially undef inputs.
9609   bool ViableForN[3] = {true, true, true};
9610
9611   for (int i = 0, e = Mask.size(); i < e; ++i) {
9612     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9613     // want.
9614     if (Mask[i] == -1)
9615       continue;
9616
9617     bool IsAnyViable = false;
9618     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9619       if (ViableForN[j]) {
9620         uint64_t N = j + 1;
9621
9622         // The shuffle mask must be equal to (i * 2^N) % M.
9623         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9624           IsAnyViable = true;
9625         else
9626           ViableForN[j] = false;
9627       }
9628     // Early exit if we exhaust the possible powers of two.
9629     if (!IsAnyViable)
9630       break;
9631   }
9632
9633   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9634     if (ViableForN[j])
9635       return j + 1;
9636
9637   // Return 0 as there is no viable power of two.
9638   return 0;
9639 }
9640
9641 /// \brief Generic lowering of v16i8 shuffles.
9642 ///
9643 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9644 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9645 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9646 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9647 /// back together.
9648 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9649                                        const X86Subtarget *Subtarget,
9650                                        SelectionDAG &DAG) {
9651   SDLoc DL(Op);
9652   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9653   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9654   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9655   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9656   ArrayRef<int> Mask = SVOp->getMask();
9657   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9658
9659   // Try to use shift instructions.
9660   if (SDValue Shift =
9661           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9662     return Shift;
9663
9664   // Try to use byte rotation instructions.
9665   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9666           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9667     return Rotate;
9668
9669   // Try to use a zext lowering.
9670   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9671           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9672     return ZExt;
9673
9674   // See if we can use SSE4A Extraction / Insertion.
9675   if (Subtarget->hasSSE4A())
9676     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9677       return V;
9678
9679   int NumV2Elements =
9680       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9681
9682   // For single-input shuffles, there are some nicer lowering tricks we can use.
9683   if (NumV2Elements == 0) {
9684     // Check for being able to broadcast a single element.
9685     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9686                                                           Mask, Subtarget, DAG))
9687       return Broadcast;
9688
9689     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9690     // Notably, this handles splat and partial-splat shuffles more efficiently.
9691     // However, it only makes sense if the pre-duplication shuffle simplifies
9692     // things significantly. Currently, this means we need to be able to
9693     // express the pre-duplication shuffle as an i16 shuffle.
9694     //
9695     // FIXME: We should check for other patterns which can be widened into an
9696     // i16 shuffle as well.
9697     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9698       for (int i = 0; i < 16; i += 2)
9699         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9700           return false;
9701
9702       return true;
9703     };
9704     auto tryToWidenViaDuplication = [&]() -> SDValue {
9705       if (!canWidenViaDuplication(Mask))
9706         return SDValue();
9707       SmallVector<int, 4> LoInputs;
9708       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9709                    [](int M) { return M >= 0 && M < 8; });
9710       std::sort(LoInputs.begin(), LoInputs.end());
9711       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9712                      LoInputs.end());
9713       SmallVector<int, 4> HiInputs;
9714       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9715                    [](int M) { return M >= 8; });
9716       std::sort(HiInputs.begin(), HiInputs.end());
9717       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9718                      HiInputs.end());
9719
9720       bool TargetLo = LoInputs.size() >= HiInputs.size();
9721       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9722       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9723
9724       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9725       SmallDenseMap<int, int, 8> LaneMap;
9726       for (int I : InPlaceInputs) {
9727         PreDupI16Shuffle[I/2] = I/2;
9728         LaneMap[I] = I;
9729       }
9730       int j = TargetLo ? 0 : 4, je = j + 4;
9731       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9732         // Check if j is already a shuffle of this input. This happens when
9733         // there are two adjacent bytes after we move the low one.
9734         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9735           // If we haven't yet mapped the input, search for a slot into which
9736           // we can map it.
9737           while (j < je && PreDupI16Shuffle[j] != -1)
9738             ++j;
9739
9740           if (j == je)
9741             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9742             return SDValue();
9743
9744           // Map this input with the i16 shuffle.
9745           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9746         }
9747
9748         // Update the lane map based on the mapping we ended up with.
9749         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9750       }
9751       V1 = DAG.getBitcast(
9752           MVT::v16i8,
9753           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9754                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9755
9756       // Unpack the bytes to form the i16s that will be shuffled into place.
9757       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9758                        MVT::v16i8, V1, V1);
9759
9760       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9761       for (int i = 0; i < 16; ++i)
9762         if (Mask[i] != -1) {
9763           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9764           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9765           if (PostDupI16Shuffle[i / 2] == -1)
9766             PostDupI16Shuffle[i / 2] = MappedMask;
9767           else
9768             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9769                    "Conflicting entrties in the original shuffle!");
9770         }
9771       return DAG.getBitcast(
9772           MVT::v16i8,
9773           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9774                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9775     };
9776     if (SDValue V = tryToWidenViaDuplication())
9777       return V;
9778   }
9779
9780   if (SDValue Masked =
9781           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9782     return Masked;
9783
9784   // Use dedicated unpack instructions for masks that match their pattern.
9785   if (SDValue V =
9786           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9787     return V;
9788
9789   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9790   // with PSHUFB. It is important to do this before we attempt to generate any
9791   // blends but after all of the single-input lowerings. If the single input
9792   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9793   // want to preserve that and we can DAG combine any longer sequences into
9794   // a PSHUFB in the end. But once we start blending from multiple inputs,
9795   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9796   // and there are *very* few patterns that would actually be faster than the
9797   // PSHUFB approach because of its ability to zero lanes.
9798   //
9799   // FIXME: The only exceptions to the above are blends which are exact
9800   // interleavings with direct instructions supporting them. We currently don't
9801   // handle those well here.
9802   if (Subtarget->hasSSSE3()) {
9803     bool V1InUse = false;
9804     bool V2InUse = false;
9805
9806     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9807                                                 DAG, V1InUse, V2InUse);
9808
9809     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9810     // do so. This avoids using them to handle blends-with-zero which is
9811     // important as a single pshufb is significantly faster for that.
9812     if (V1InUse && V2InUse) {
9813       if (Subtarget->hasSSE41())
9814         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9815                                                       Mask, Subtarget, DAG))
9816           return Blend;
9817
9818       // We can use an unpack to do the blending rather than an or in some
9819       // cases. Even though the or may be (very minorly) more efficient, we
9820       // preference this lowering because there are common cases where part of
9821       // the complexity of the shuffles goes away when we do the final blend as
9822       // an unpack.
9823       // FIXME: It might be worth trying to detect if the unpack-feeding
9824       // shuffles will both be pshufb, in which case we shouldn't bother with
9825       // this.
9826       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9827               DL, MVT::v16i8, V1, V2, Mask, DAG))
9828         return Unpack;
9829     }
9830
9831     return PSHUFB;
9832   }
9833
9834   // There are special ways we can lower some single-element blends.
9835   if (NumV2Elements == 1)
9836     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9837                                                          Mask, Subtarget, DAG))
9838       return V;
9839
9840   if (SDValue BitBlend =
9841           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9842     return BitBlend;
9843
9844   // Check whether a compaction lowering can be done. This handles shuffles
9845   // which take every Nth element for some even N. See the helper function for
9846   // details.
9847   //
9848   // We special case these as they can be particularly efficiently handled with
9849   // the PACKUSB instruction on x86 and they show up in common patterns of
9850   // rearranging bytes to truncate wide elements.
9851   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9852     // NumEvenDrops is the power of two stride of the elements. Another way of
9853     // thinking about it is that we need to drop the even elements this many
9854     // times to get the original input.
9855     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9856
9857     // First we need to zero all the dropped bytes.
9858     assert(NumEvenDrops <= 3 &&
9859            "No support for dropping even elements more than 3 times.");
9860     // We use the mask type to pick which bytes are preserved based on how many
9861     // elements are dropped.
9862     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9863     SDValue ByteClearMask = DAG.getBitcast(
9864         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9865     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9866     if (!IsSingleInput)
9867       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9868
9869     // Now pack things back together.
9870     V1 = DAG.getBitcast(MVT::v8i16, V1);
9871     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9872     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9873     for (int i = 1; i < NumEvenDrops; ++i) {
9874       Result = DAG.getBitcast(MVT::v8i16, Result);
9875       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9876     }
9877
9878     return Result;
9879   }
9880
9881   // Handle multi-input cases by blending single-input shuffles.
9882   if (NumV2Elements > 0)
9883     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9884                                                       Mask, DAG);
9885
9886   // The fallback path for single-input shuffles widens this into two v8i16
9887   // vectors with unpacks, shuffles those, and then pulls them back together
9888   // with a pack.
9889   SDValue V = V1;
9890
9891   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9892   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9893   for (int i = 0; i < 16; ++i)
9894     if (Mask[i] >= 0)
9895       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9896
9897   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9898
9899   SDValue VLoHalf, VHiHalf;
9900   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9901   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9902   // i16s.
9903   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9904                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9905       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9906                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9907     // Use a mask to drop the high bytes.
9908     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9909     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9910                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9911
9912     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9913     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9914
9915     // Squash the masks to point directly into VLoHalf.
9916     for (int &M : LoBlendMask)
9917       if (M >= 0)
9918         M /= 2;
9919     for (int &M : HiBlendMask)
9920       if (M >= 0)
9921         M /= 2;
9922   } else {
9923     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9924     // VHiHalf so that we can blend them as i16s.
9925     VLoHalf = DAG.getBitcast(
9926         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9927     VHiHalf = DAG.getBitcast(
9928         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9929   }
9930
9931   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9932   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9933
9934   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9935 }
9936
9937 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9938 ///
9939 /// This routine breaks down the specific type of 128-bit shuffle and
9940 /// dispatches to the lowering routines accordingly.
9941 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9942                                         MVT VT, const X86Subtarget *Subtarget,
9943                                         SelectionDAG &DAG) {
9944   switch (VT.SimpleTy) {
9945   case MVT::v2i64:
9946     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9947   case MVT::v2f64:
9948     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9949   case MVT::v4i32:
9950     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9951   case MVT::v4f32:
9952     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9953   case MVT::v8i16:
9954     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9955   case MVT::v16i8:
9956     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9957
9958   default:
9959     llvm_unreachable("Unimplemented!");
9960   }
9961 }
9962
9963 /// \brief Helper function to test whether a shuffle mask could be
9964 /// simplified by widening the elements being shuffled.
9965 ///
9966 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9967 /// leaves it in an unspecified state.
9968 ///
9969 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9970 /// shuffle masks. The latter have the special property of a '-2' representing
9971 /// a zero-ed lane of a vector.
9972 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9973                                     SmallVectorImpl<int> &WidenedMask) {
9974   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9975     // If both elements are undef, its trivial.
9976     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9977       WidenedMask.push_back(SM_SentinelUndef);
9978       continue;
9979     }
9980
9981     // Check for an undef mask and a mask value properly aligned to fit with
9982     // a pair of values. If we find such a case, use the non-undef mask's value.
9983     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9984       WidenedMask.push_back(Mask[i + 1] / 2);
9985       continue;
9986     }
9987     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9988       WidenedMask.push_back(Mask[i] / 2);
9989       continue;
9990     }
9991
9992     // When zeroing, we need to spread the zeroing across both lanes to widen.
9993     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9994       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9995           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9996         WidenedMask.push_back(SM_SentinelZero);
9997         continue;
9998       }
9999       return false;
10000     }
10001
10002     // Finally check if the two mask values are adjacent and aligned with
10003     // a pair.
10004     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
10005       WidenedMask.push_back(Mask[i] / 2);
10006       continue;
10007     }
10008
10009     // Otherwise we can't safely widen the elements used in this shuffle.
10010     return false;
10011   }
10012   assert(WidenedMask.size() == Mask.size() / 2 &&
10013          "Incorrect size of mask after widening the elements!");
10014
10015   return true;
10016 }
10017
10018 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
10019 ///
10020 /// This routine just extracts two subvectors, shuffles them independently, and
10021 /// then concatenates them back together. This should work effectively with all
10022 /// AVX vector shuffle types.
10023 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10024                                           SDValue V2, ArrayRef<int> Mask,
10025                                           SelectionDAG &DAG) {
10026   assert(VT.getSizeInBits() >= 256 &&
10027          "Only for 256-bit or wider vector shuffles!");
10028   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
10029   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
10030
10031   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
10032   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
10033
10034   int NumElements = VT.getVectorNumElements();
10035   int SplitNumElements = NumElements / 2;
10036   MVT ScalarVT = VT.getVectorElementType();
10037   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
10038
10039   // Rather than splitting build-vectors, just build two narrower build
10040   // vectors. This helps shuffling with splats and zeros.
10041   auto SplitVector = [&](SDValue V) {
10042     while (V.getOpcode() == ISD::BITCAST)
10043       V = V->getOperand(0);
10044
10045     MVT OrigVT = V.getSimpleValueType();
10046     int OrigNumElements = OrigVT.getVectorNumElements();
10047     int OrigSplitNumElements = OrigNumElements / 2;
10048     MVT OrigScalarVT = OrigVT.getVectorElementType();
10049     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
10050
10051     SDValue LoV, HiV;
10052
10053     auto *BV = dyn_cast<BuildVectorSDNode>(V);
10054     if (!BV) {
10055       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10056                         DAG.getIntPtrConstant(0, DL));
10057       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10058                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
10059     } else {
10060
10061       SmallVector<SDValue, 16> LoOps, HiOps;
10062       for (int i = 0; i < OrigSplitNumElements; ++i) {
10063         LoOps.push_back(BV->getOperand(i));
10064         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10065       }
10066       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10067       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10068     }
10069     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10070                           DAG.getBitcast(SplitVT, HiV));
10071   };
10072
10073   SDValue LoV1, HiV1, LoV2, HiV2;
10074   std::tie(LoV1, HiV1) = SplitVector(V1);
10075   std::tie(LoV2, HiV2) = SplitVector(V2);
10076
10077   // Now create two 4-way blends of these half-width vectors.
10078   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10079     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10080     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10081     for (int i = 0; i < SplitNumElements; ++i) {
10082       int M = HalfMask[i];
10083       if (M >= NumElements) {
10084         if (M >= NumElements + SplitNumElements)
10085           UseHiV2 = true;
10086         else
10087           UseLoV2 = true;
10088         V2BlendMask.push_back(M - NumElements);
10089         V1BlendMask.push_back(-1);
10090         BlendMask.push_back(SplitNumElements + i);
10091       } else if (M >= 0) {
10092         if (M >= SplitNumElements)
10093           UseHiV1 = true;
10094         else
10095           UseLoV1 = true;
10096         V2BlendMask.push_back(-1);
10097         V1BlendMask.push_back(M);
10098         BlendMask.push_back(i);
10099       } else {
10100         V2BlendMask.push_back(-1);
10101         V1BlendMask.push_back(-1);
10102         BlendMask.push_back(-1);
10103       }
10104     }
10105
10106     // Because the lowering happens after all combining takes place, we need to
10107     // manually combine these blend masks as much as possible so that we create
10108     // a minimal number of high-level vector shuffle nodes.
10109
10110     // First try just blending the halves of V1 or V2.
10111     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10112       return DAG.getUNDEF(SplitVT);
10113     if (!UseLoV2 && !UseHiV2)
10114       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10115     if (!UseLoV1 && !UseHiV1)
10116       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10117
10118     SDValue V1Blend, V2Blend;
10119     if (UseLoV1 && UseHiV1) {
10120       V1Blend =
10121         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10122     } else {
10123       // We only use half of V1 so map the usage down into the final blend mask.
10124       V1Blend = UseLoV1 ? LoV1 : HiV1;
10125       for (int i = 0; i < SplitNumElements; ++i)
10126         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10127           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10128     }
10129     if (UseLoV2 && UseHiV2) {
10130       V2Blend =
10131         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10132     } else {
10133       // We only use half of V2 so map the usage down into the final blend mask.
10134       V2Blend = UseLoV2 ? LoV2 : HiV2;
10135       for (int i = 0; i < SplitNumElements; ++i)
10136         if (BlendMask[i] >= SplitNumElements)
10137           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10138     }
10139     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10140   };
10141   SDValue Lo = HalfBlend(LoMask);
10142   SDValue Hi = HalfBlend(HiMask);
10143   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10144 }
10145
10146 /// \brief Either split a vector in halves or decompose the shuffles and the
10147 /// blend.
10148 ///
10149 /// This is provided as a good fallback for many lowerings of non-single-input
10150 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10151 /// between splitting the shuffle into 128-bit components and stitching those
10152 /// back together vs. extracting the single-input shuffles and blending those
10153 /// results.
10154 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10155                                                 SDValue V2, ArrayRef<int> Mask,
10156                                                 SelectionDAG &DAG) {
10157   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10158                                             "lower single-input shuffles as it "
10159                                             "could then recurse on itself.");
10160   int Size = Mask.size();
10161
10162   // If this can be modeled as a broadcast of two elements followed by a blend,
10163   // prefer that lowering. This is especially important because broadcasts can
10164   // often fold with memory operands.
10165   auto DoBothBroadcast = [&] {
10166     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10167     for (int M : Mask)
10168       if (M >= Size) {
10169         if (V2BroadcastIdx == -1)
10170           V2BroadcastIdx = M - Size;
10171         else if (M - Size != V2BroadcastIdx)
10172           return false;
10173       } else if (M >= 0) {
10174         if (V1BroadcastIdx == -1)
10175           V1BroadcastIdx = M;
10176         else if (M != V1BroadcastIdx)
10177           return false;
10178       }
10179     return true;
10180   };
10181   if (DoBothBroadcast())
10182     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10183                                                       DAG);
10184
10185   // If the inputs all stem from a single 128-bit lane of each input, then we
10186   // split them rather than blending because the split will decompose to
10187   // unusually few instructions.
10188   int LaneCount = VT.getSizeInBits() / 128;
10189   int LaneSize = Size / LaneCount;
10190   SmallBitVector LaneInputs[2];
10191   LaneInputs[0].resize(LaneCount, false);
10192   LaneInputs[1].resize(LaneCount, false);
10193   for (int i = 0; i < Size; ++i)
10194     if (Mask[i] >= 0)
10195       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10196   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10197     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10198
10199   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10200   // that the decomposed single-input shuffles don't end up here.
10201   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10202 }
10203
10204 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10205 /// a permutation and blend of those lanes.
10206 ///
10207 /// This essentially blends the out-of-lane inputs to each lane into the lane
10208 /// from a permuted copy of the vector. This lowering strategy results in four
10209 /// instructions in the worst case for a single-input cross lane shuffle which
10210 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10211 /// of. Special cases for each particular shuffle pattern should be handled
10212 /// prior to trying this lowering.
10213 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10214                                                        SDValue V1, SDValue V2,
10215                                                        ArrayRef<int> Mask,
10216                                                        SelectionDAG &DAG) {
10217   // FIXME: This should probably be generalized for 512-bit vectors as well.
10218   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10219   int LaneSize = Mask.size() / 2;
10220
10221   // If there are only inputs from one 128-bit lane, splitting will in fact be
10222   // less expensive. The flags track whether the given lane contains an element
10223   // that crosses to another lane.
10224   bool LaneCrossing[2] = {false, false};
10225   for (int i = 0, Size = Mask.size(); i < Size; ++i)
10226     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10227       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10228   if (!LaneCrossing[0] || !LaneCrossing[1])
10229     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10230
10231   if (isSingleInputShuffleMask(Mask)) {
10232     SmallVector<int, 32> FlippedBlendMask;
10233     for (int i = 0, Size = Mask.size(); i < Size; ++i)
10234       FlippedBlendMask.push_back(
10235           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10236                                   ? Mask[i]
10237                                   : Mask[i] % LaneSize +
10238                                         (i / LaneSize) * LaneSize + Size));
10239
10240     // Flip the vector, and blend the results which should now be in-lane. The
10241     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10242     // 5 for the high source. The value 3 selects the high half of source 2 and
10243     // the value 2 selects the low half of source 2. We only use source 2 to
10244     // allow folding it into a memory operand.
10245     unsigned PERMMask = 3 | 2 << 4;
10246     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10247                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10248     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10249   }
10250
10251   // This now reduces to two single-input shuffles of V1 and V2 which at worst
10252   // will be handled by the above logic and a blend of the results, much like
10253   // other patterns in AVX.
10254   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10255 }
10256
10257 /// \brief Handle lowering 2-lane 128-bit shuffles.
10258 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10259                                         SDValue V2, ArrayRef<int> Mask,
10260                                         const X86Subtarget *Subtarget,
10261                                         SelectionDAG &DAG) {
10262   // TODO: If minimizing size and one of the inputs is a zero vector and the
10263   // the zero vector has only one use, we could use a VPERM2X128 to save the
10264   // instruction bytes needed to explicitly generate the zero vector.
10265
10266   // Blends are faster and handle all the non-lane-crossing cases.
10267   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10268                                                 Subtarget, DAG))
10269     return Blend;
10270
10271   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10272   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10273
10274   // If either input operand is a zero vector, use VPERM2X128 because its mask
10275   // allows us to replace the zero input with an implicit zero.
10276   if (!IsV1Zero && !IsV2Zero) {
10277     // Check for patterns which can be matched with a single insert of a 128-bit
10278     // subvector.
10279     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10280     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10281       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10282                                    VT.getVectorNumElements() / 2);
10283       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10284                                 DAG.getIntPtrConstant(0, DL));
10285       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10286                                 OnlyUsesV1 ? V1 : V2,
10287                                 DAG.getIntPtrConstant(0, DL));
10288       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10289     }
10290   }
10291
10292   // Otherwise form a 128-bit permutation. After accounting for undefs,
10293   // convert the 64-bit shuffle mask selection values into 128-bit
10294   // selection bits by dividing the indexes by 2 and shifting into positions
10295   // defined by a vperm2*128 instruction's immediate control byte.
10296
10297   // The immediate permute control byte looks like this:
10298   //    [1:0] - select 128 bits from sources for low half of destination
10299   //    [2]   - ignore
10300   //    [3]   - zero low half of destination
10301   //    [5:4] - select 128 bits from sources for high half of destination
10302   //    [6]   - ignore
10303   //    [7]   - zero high half of destination
10304
10305   int MaskLO = Mask[0];
10306   if (MaskLO == SM_SentinelUndef)
10307     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10308
10309   int MaskHI = Mask[2];
10310   if (MaskHI == SM_SentinelUndef)
10311     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10312
10313   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10314
10315   // If either input is a zero vector, replace it with an undef input.
10316   // Shuffle mask values <  4 are selecting elements of V1.
10317   // Shuffle mask values >= 4 are selecting elements of V2.
10318   // Adjust each half of the permute mask by clearing the half that was
10319   // selecting the zero vector and setting the zero mask bit.
10320   if (IsV1Zero) {
10321     V1 = DAG.getUNDEF(VT);
10322     if (MaskLO < 4)
10323       PermMask = (PermMask & 0xf0) | 0x08;
10324     if (MaskHI < 4)
10325       PermMask = (PermMask & 0x0f) | 0x80;
10326   }
10327   if (IsV2Zero) {
10328     V2 = DAG.getUNDEF(VT);
10329     if (MaskLO >= 4)
10330       PermMask = (PermMask & 0xf0) | 0x08;
10331     if (MaskHI >= 4)
10332       PermMask = (PermMask & 0x0f) | 0x80;
10333   }
10334
10335   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10336                      DAG.getConstant(PermMask, DL, MVT::i8));
10337 }
10338
10339 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10340 /// shuffling each lane.
10341 ///
10342 /// This will only succeed when the result of fixing the 128-bit lanes results
10343 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10344 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10345 /// the lane crosses early and then use simpler shuffles within each lane.
10346 ///
10347 /// FIXME: It might be worthwhile at some point to support this without
10348 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10349 /// in x86 only floating point has interesting non-repeating shuffles, and even
10350 /// those are still *marginally* more expensive.
10351 static SDValue lowerVectorShuffleByMerging128BitLanes(
10352     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10353     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10354   assert(!isSingleInputShuffleMask(Mask) &&
10355          "This is only useful with multiple inputs.");
10356
10357   int Size = Mask.size();
10358   int LaneSize = 128 / VT.getScalarSizeInBits();
10359   int NumLanes = Size / LaneSize;
10360   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10361
10362   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10363   // check whether the in-128-bit lane shuffles share a repeating pattern.
10364   SmallVector<int, 4> Lanes;
10365   Lanes.resize(NumLanes, -1);
10366   SmallVector<int, 4> InLaneMask;
10367   InLaneMask.resize(LaneSize, -1);
10368   for (int i = 0; i < Size; ++i) {
10369     if (Mask[i] < 0)
10370       continue;
10371
10372     int j = i / LaneSize;
10373
10374     if (Lanes[j] < 0) {
10375       // First entry we've seen for this lane.
10376       Lanes[j] = Mask[i] / LaneSize;
10377     } else if (Lanes[j] != Mask[i] / LaneSize) {
10378       // This doesn't match the lane selected previously!
10379       return SDValue();
10380     }
10381
10382     // Check that within each lane we have a consistent shuffle mask.
10383     int k = i % LaneSize;
10384     if (InLaneMask[k] < 0) {
10385       InLaneMask[k] = Mask[i] % LaneSize;
10386     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10387       // This doesn't fit a repeating in-lane mask.
10388       return SDValue();
10389     }
10390   }
10391
10392   // First shuffle the lanes into place.
10393   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10394                                 VT.getSizeInBits() / 64);
10395   SmallVector<int, 8> LaneMask;
10396   LaneMask.resize(NumLanes * 2, -1);
10397   for (int i = 0; i < NumLanes; ++i)
10398     if (Lanes[i] >= 0) {
10399       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10400       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10401     }
10402
10403   V1 = DAG.getBitcast(LaneVT, V1);
10404   V2 = DAG.getBitcast(LaneVT, V2);
10405   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10406
10407   // Cast it back to the type we actually want.
10408   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10409
10410   // Now do a simple shuffle that isn't lane crossing.
10411   SmallVector<int, 8> NewMask;
10412   NewMask.resize(Size, -1);
10413   for (int i = 0; i < Size; ++i)
10414     if (Mask[i] >= 0)
10415       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10416   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10417          "Must not introduce lane crosses at this point!");
10418
10419   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10420 }
10421
10422 /// Lower shuffles where an entire half of a 256-bit vector is UNDEF.
10423 /// This allows for fast cases such as subvector extraction/insertion
10424 /// or shuffling smaller vector types which can lower more efficiently.
10425 static SDValue lowerVectorShuffleWithUndefHalf(SDLoc DL, MVT VT, SDValue V1,
10426                                                SDValue V2, ArrayRef<int> Mask,
10427                                                const X86Subtarget *Subtarget,
10428                                                SelectionDAG &DAG) {
10429   assert(VT.getSizeInBits() == 256 && "Expected 256-bit vector");
10430
10431   unsigned NumElts = VT.getVectorNumElements();
10432   unsigned HalfNumElts = NumElts / 2;
10433   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
10434
10435   bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
10436   bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
10437   if (!UndefLower && !UndefUpper)
10438     return SDValue();
10439
10440   // Upper half is undef and lower half is whole upper subvector.
10441   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
10442   if (UndefUpper &&
10443       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
10444     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10445                              DAG.getIntPtrConstant(HalfNumElts, DL));
10446     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10447                        DAG.getIntPtrConstant(0, DL));
10448   }
10449
10450   // Lower half is undef and upper half is whole lower subvector.
10451   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
10452   if (UndefLower &&
10453       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
10454     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10455                              DAG.getIntPtrConstant(0, DL));
10456     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10457                        DAG.getIntPtrConstant(HalfNumElts, DL));
10458   }
10459
10460   // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
10461   if (UndefLower && Subtarget->hasAVX2() &&
10462       (VT == MVT::v4f64 || VT == MVT::v4i64))
10463     return SDValue();
10464
10465   // If the shuffle only uses the lower halves of the input operands,
10466   // then extract them and perform the 'half' shuffle at half width.
10467   // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
10468   int HalfIdx1 = -1, HalfIdx2 = -1;
10469   SmallVector<int, 8> HalfMask;
10470   unsigned Offset = UndefLower ? HalfNumElts : 0;
10471   for (unsigned i = 0; i != HalfNumElts; ++i) {
10472     int M = Mask[i + Offset];
10473     if (M < 0) {
10474       HalfMask.push_back(M);
10475       continue;
10476     }
10477
10478     // Determine which of the 4 half vectors this element is from.
10479     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
10480     int HalfIdx = M / HalfNumElts;
10481
10482     // Only shuffle using the lower halves of the inputs.
10483     // TODO: Investigate usefulness of shuffling with upper halves.
10484     if (HalfIdx != 0 && HalfIdx != 2)
10485       return SDValue();
10486
10487     // Determine the element index into its half vector source.
10488     int HalfElt = M % HalfNumElts;
10489
10490     // We can shuffle with up to 2 half vectors, set the new 'half'
10491     // shuffle mask accordingly.
10492     if (-1 == HalfIdx1 || HalfIdx1 == HalfIdx) {
10493       HalfMask.push_back(HalfElt);
10494       HalfIdx1 = HalfIdx;
10495       continue;
10496     }
10497     if (-1 == HalfIdx2 || HalfIdx2 == HalfIdx) {
10498       HalfMask.push_back(HalfElt + HalfNumElts);
10499       HalfIdx2 = HalfIdx;
10500       continue;
10501     }
10502
10503     // Too many half vectors referenced.
10504     return SDValue();
10505   }
10506   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
10507
10508   auto GetHalfVector = [&](int HalfIdx) {
10509     if (HalfIdx < 0)
10510       return DAG.getUNDEF(HalfVT);
10511     SDValue V = (HalfIdx < 2 ? V1 : V2);
10512     HalfIdx = (HalfIdx % 2) * HalfNumElts;
10513     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
10514                        DAG.getIntPtrConstant(HalfIdx, DL));
10515   };
10516
10517   SDValue Half1 = GetHalfVector(HalfIdx1);
10518   SDValue Half2 = GetHalfVector(HalfIdx2);
10519   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
10520   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
10521                      DAG.getIntPtrConstant(Offset, DL));
10522 }
10523
10524 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10525 /// given mask.
10526 ///
10527 /// This returns true if the elements from a particular input are already in the
10528 /// slot required by the given mask and require no permutation.
10529 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10530   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10531   int Size = Mask.size();
10532   for (int i = 0; i < Size; ++i)
10533     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10534       return false;
10535
10536   return true;
10537 }
10538
10539 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10540                                             ArrayRef<int> Mask, SDValue V1,
10541                                             SDValue V2, SelectionDAG &DAG) {
10542
10543   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10544   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10545   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10546   int NumElts = VT.getVectorNumElements();
10547   bool ShufpdMask = true;
10548   bool CommutableMask = true;
10549   unsigned Immediate = 0;
10550   for (int i = 0; i < NumElts; ++i) {
10551     if (Mask[i] < 0)
10552       continue;
10553     int Val = (i & 6) + NumElts * (i & 1);
10554     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10555     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10556       ShufpdMask = false;
10557     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10558       CommutableMask = false;
10559     Immediate |= (Mask[i] % 2) << i;
10560   }
10561   if (ShufpdMask)
10562     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10563                        DAG.getConstant(Immediate, DL, MVT::i8));
10564   if (CommutableMask)
10565     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10566                        DAG.getConstant(Immediate, DL, MVT::i8));
10567   return SDValue();
10568 }
10569
10570 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10571 ///
10572 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10573 /// isn't available.
10574 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10575                                        const X86Subtarget *Subtarget,
10576                                        SelectionDAG &DAG) {
10577   SDLoc DL(Op);
10578   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10579   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10580   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10581   ArrayRef<int> Mask = SVOp->getMask();
10582   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10583
10584   SmallVector<int, 4> WidenedMask;
10585   if (canWidenShuffleElements(Mask, WidenedMask))
10586     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10587                                     DAG);
10588
10589   if (isSingleInputShuffleMask(Mask)) {
10590     // Check for being able to broadcast a single element.
10591     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10592                                                           Mask, Subtarget, DAG))
10593       return Broadcast;
10594
10595     // Use low duplicate instructions for masks that match their pattern.
10596     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10597       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10598
10599     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10600       // Non-half-crossing single input shuffles can be lowerid with an
10601       // interleaved permutation.
10602       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10603                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10604       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10605                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10606     }
10607
10608     // With AVX2 we have direct support for this permutation.
10609     if (Subtarget->hasAVX2())
10610       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10611                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10612
10613     // Otherwise, fall back.
10614     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10615                                                    DAG);
10616   }
10617
10618   // Use dedicated unpack instructions for masks that match their pattern.
10619   if (SDValue V =
10620           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10621     return V;
10622
10623   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10624                                                 Subtarget, DAG))
10625     return Blend;
10626
10627   // Check if the blend happens to exactly fit that of SHUFPD.
10628   if (SDValue Op =
10629       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10630     return Op;
10631
10632   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10633   // shuffle. However, if we have AVX2 and either inputs are already in place,
10634   // we will be able to shuffle even across lanes the other input in a single
10635   // instruction so skip this pattern.
10636   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10637                                  isShuffleMaskInputInPlace(1, Mask))))
10638     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10639             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10640       return Result;
10641
10642   // If we have AVX2 then we always want to lower with a blend because an v4 we
10643   // can fully permute the elements.
10644   if (Subtarget->hasAVX2())
10645     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10646                                                       Mask, DAG);
10647
10648   // Otherwise fall back on generic lowering.
10649   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10650 }
10651
10652 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10653 ///
10654 /// This routine is only called when we have AVX2 and thus a reasonable
10655 /// instruction set for v4i64 shuffling..
10656 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10657                                        const X86Subtarget *Subtarget,
10658                                        SelectionDAG &DAG) {
10659   SDLoc DL(Op);
10660   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10661   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10662   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10663   ArrayRef<int> Mask = SVOp->getMask();
10664   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10665   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10666
10667   SmallVector<int, 4> WidenedMask;
10668   if (canWidenShuffleElements(Mask, WidenedMask))
10669     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10670                                     DAG);
10671
10672   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10673                                                 Subtarget, DAG))
10674     return Blend;
10675
10676   // Check for being able to broadcast a single element.
10677   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10678                                                         Mask, Subtarget, DAG))
10679     return Broadcast;
10680
10681   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10682   // use lower latency instructions that will operate on both 128-bit lanes.
10683   SmallVector<int, 2> RepeatedMask;
10684   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10685     if (isSingleInputShuffleMask(Mask)) {
10686       int PSHUFDMask[] = {-1, -1, -1, -1};
10687       for (int i = 0; i < 2; ++i)
10688         if (RepeatedMask[i] >= 0) {
10689           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10690           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10691         }
10692       return DAG.getBitcast(
10693           MVT::v4i64,
10694           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10695                       DAG.getBitcast(MVT::v8i32, V1),
10696                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10697     }
10698   }
10699
10700   // AVX2 provides a direct instruction for permuting a single input across
10701   // lanes.
10702   if (isSingleInputShuffleMask(Mask))
10703     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10704                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10705
10706   // Try to use shift instructions.
10707   if (SDValue Shift =
10708           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10709     return Shift;
10710
10711   // Use dedicated unpack instructions for masks that match their pattern.
10712   if (SDValue V =
10713           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10714     return V;
10715
10716   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10717   // shuffle. However, if we have AVX2 and either inputs are already in place,
10718   // we will be able to shuffle even across lanes the other input in a single
10719   // instruction so skip this pattern.
10720   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10721                                  isShuffleMaskInputInPlace(1, Mask))))
10722     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10723             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10724       return Result;
10725
10726   // Otherwise fall back on generic blend lowering.
10727   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10728                                                     Mask, DAG);
10729 }
10730
10731 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10732 ///
10733 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10734 /// isn't available.
10735 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10736                                        const X86Subtarget *Subtarget,
10737                                        SelectionDAG &DAG) {
10738   SDLoc DL(Op);
10739   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10740   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10741   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10742   ArrayRef<int> Mask = SVOp->getMask();
10743   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10744
10745   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10746                                                 Subtarget, DAG))
10747     return Blend;
10748
10749   // Check for being able to broadcast a single element.
10750   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10751                                                         Mask, Subtarget, DAG))
10752     return Broadcast;
10753
10754   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10755   // options to efficiently lower the shuffle.
10756   SmallVector<int, 4> RepeatedMask;
10757   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10758     assert(RepeatedMask.size() == 4 &&
10759            "Repeated masks must be half the mask width!");
10760
10761     // Use even/odd duplicate instructions for masks that match their pattern.
10762     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10763       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10764     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10765       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10766
10767     if (isSingleInputShuffleMask(Mask))
10768       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10769                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10770
10771     // Use dedicated unpack instructions for masks that match their pattern.
10772     if (SDValue V =
10773             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10774       return V;
10775
10776     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10777     // have already handled any direct blends. We also need to squash the
10778     // repeated mask into a simulated v4f32 mask.
10779     for (int i = 0; i < 4; ++i)
10780       if (RepeatedMask[i] >= 8)
10781         RepeatedMask[i] -= 4;
10782     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10783   }
10784
10785   // If we have a single input shuffle with different shuffle patterns in the
10786   // two 128-bit lanes use the variable mask to VPERMILPS.
10787   if (isSingleInputShuffleMask(Mask)) {
10788     SDValue VPermMask[8];
10789     for (int i = 0; i < 8; ++i)
10790       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10791                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10792     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10793       return DAG.getNode(
10794           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10795           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10796
10797     if (Subtarget->hasAVX2())
10798       return DAG.getNode(
10799           X86ISD::VPERMV, DL, MVT::v8f32,
10800           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10801
10802     // Otherwise, fall back.
10803     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10804                                                    DAG);
10805   }
10806
10807   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10808   // shuffle.
10809   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10810           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10811     return Result;
10812
10813   // If we have AVX2 then we always want to lower with a blend because at v8 we
10814   // can fully permute the elements.
10815   if (Subtarget->hasAVX2())
10816     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10817                                                       Mask, DAG);
10818
10819   // Otherwise fall back on generic lowering.
10820   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10821 }
10822
10823 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10824 ///
10825 /// This routine is only called when we have AVX2 and thus a reasonable
10826 /// instruction set for v8i32 shuffling..
10827 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10828                                        const X86Subtarget *Subtarget,
10829                                        SelectionDAG &DAG) {
10830   SDLoc DL(Op);
10831   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10832   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10833   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10834   ArrayRef<int> Mask = SVOp->getMask();
10835   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10836   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10837
10838   // Whenever we can lower this as a zext, that instruction is strictly faster
10839   // than any alternative. It also allows us to fold memory operands into the
10840   // shuffle in many cases.
10841   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10842                                                          Mask, Subtarget, DAG))
10843     return ZExt;
10844
10845   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10846                                                 Subtarget, DAG))
10847     return Blend;
10848
10849   // Check for being able to broadcast a single element.
10850   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10851                                                         Mask, Subtarget, DAG))
10852     return Broadcast;
10853
10854   // If the shuffle mask is repeated in each 128-bit lane we can use more
10855   // efficient instructions that mirror the shuffles across the two 128-bit
10856   // lanes.
10857   SmallVector<int, 4> RepeatedMask;
10858   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10859     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10860     if (isSingleInputShuffleMask(Mask))
10861       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10862                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10863
10864     // Use dedicated unpack instructions for masks that match their pattern.
10865     if (SDValue V =
10866             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10867       return V;
10868   }
10869
10870   // Try to use shift instructions.
10871   if (SDValue Shift =
10872           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10873     return Shift;
10874
10875   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10876           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10877     return Rotate;
10878
10879   // If the shuffle patterns aren't repeated but it is a single input, directly
10880   // generate a cross-lane VPERMD instruction.
10881   if (isSingleInputShuffleMask(Mask)) {
10882     SDValue VPermMask[8];
10883     for (int i = 0; i < 8; ++i)
10884       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10885                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10886     return DAG.getNode(
10887         X86ISD::VPERMV, DL, MVT::v8i32,
10888         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10889   }
10890
10891   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10892   // shuffle.
10893   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10894           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10895     return Result;
10896
10897   // Otherwise fall back on generic blend lowering.
10898   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10899                                                     Mask, DAG);
10900 }
10901
10902 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10903 ///
10904 /// This routine is only called when we have AVX2 and thus a reasonable
10905 /// instruction set for v16i16 shuffling..
10906 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10907                                         const X86Subtarget *Subtarget,
10908                                         SelectionDAG &DAG) {
10909   SDLoc DL(Op);
10910   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10911   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10912   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10913   ArrayRef<int> Mask = SVOp->getMask();
10914   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10915   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10916
10917   // Whenever we can lower this as a zext, that instruction is strictly faster
10918   // than any alternative. It also allows us to fold memory operands into the
10919   // shuffle in many cases.
10920   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10921                                                          Mask, Subtarget, DAG))
10922     return ZExt;
10923
10924   // Check for being able to broadcast a single element.
10925   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10926                                                         Mask, Subtarget, DAG))
10927     return Broadcast;
10928
10929   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10930                                                 Subtarget, DAG))
10931     return Blend;
10932
10933   // Use dedicated unpack instructions for masks that match their pattern.
10934   if (SDValue V =
10935           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10936     return V;
10937
10938   // Try to use shift instructions.
10939   if (SDValue Shift =
10940           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10941     return Shift;
10942
10943   // Try to use byte rotation instructions.
10944   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10945           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10946     return Rotate;
10947
10948   if (isSingleInputShuffleMask(Mask)) {
10949     // There are no generalized cross-lane shuffle operations available on i16
10950     // element types.
10951     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10952       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10953                                                      Mask, DAG);
10954
10955     SmallVector<int, 8> RepeatedMask;
10956     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10957       // As this is a single-input shuffle, the repeated mask should be
10958       // a strictly valid v8i16 mask that we can pass through to the v8i16
10959       // lowering to handle even the v16 case.
10960       return lowerV8I16GeneralSingleInputVectorShuffle(
10961           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10962     }
10963
10964     SDValue PSHUFBMask[32];
10965     for (int i = 0; i < 16; ++i) {
10966       if (Mask[i] == -1) {
10967         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10968         continue;
10969       }
10970
10971       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10972       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10973       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10974       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10975     }
10976     return DAG.getBitcast(MVT::v16i16,
10977                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10978                                       DAG.getBitcast(MVT::v32i8, V1),
10979                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10980                                                   MVT::v32i8, PSHUFBMask)));
10981   }
10982
10983   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10984   // shuffle.
10985   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10986           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10987     return Result;
10988
10989   // Otherwise fall back on generic lowering.
10990   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10991 }
10992
10993 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10994 ///
10995 /// This routine is only called when we have AVX2 and thus a reasonable
10996 /// instruction set for v32i8 shuffling..
10997 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10998                                        const X86Subtarget *Subtarget,
10999                                        SelectionDAG &DAG) {
11000   SDLoc DL(Op);
11001   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
11002   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
11003   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11004   ArrayRef<int> Mask = SVOp->getMask();
11005   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11006   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
11007
11008   // Whenever we can lower this as a zext, that instruction is strictly faster
11009   // than any alternative. It also allows us to fold memory operands into the
11010   // shuffle in many cases.
11011   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
11012                                                          Mask, Subtarget, DAG))
11013     return ZExt;
11014
11015   // Check for being able to broadcast a single element.
11016   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
11017                                                         Mask, Subtarget, DAG))
11018     return Broadcast;
11019
11020   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
11021                                                 Subtarget, DAG))
11022     return Blend;
11023
11024   // Use dedicated unpack instructions for masks that match their pattern.
11025   if (SDValue V =
11026           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
11027     return V;
11028
11029   // Try to use shift instructions.
11030   if (SDValue Shift =
11031           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
11032     return Shift;
11033
11034   // Try to use byte rotation instructions.
11035   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
11036           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11037     return Rotate;
11038
11039   if (isSingleInputShuffleMask(Mask)) {
11040     // There are no generalized cross-lane shuffle operations available on i8
11041     // element types.
11042     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
11043       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
11044                                                      Mask, DAG);
11045
11046     SDValue PSHUFBMask[32];
11047     for (int i = 0; i < 32; ++i)
11048       PSHUFBMask[i] =
11049           Mask[i] < 0
11050               ? DAG.getUNDEF(MVT::i8)
11051               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
11052                                 MVT::i8);
11053
11054     return DAG.getNode(
11055         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
11056         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
11057   }
11058
11059   // Try to simplify this by merging 128-bit lanes to enable a lane-based
11060   // shuffle.
11061   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11062           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11063     return Result;
11064
11065   // Otherwise fall back on generic lowering.
11066   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11067 }
11068
11069 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11070 ///
11071 /// This routine either breaks down the specific type of a 256-bit x86 vector
11072 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11073 /// together based on the available instructions.
11074 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11075                                         MVT VT, const X86Subtarget *Subtarget,
11076                                         SelectionDAG &DAG) {
11077   SDLoc DL(Op);
11078   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11079   ArrayRef<int> Mask = SVOp->getMask();
11080
11081   // If we have a single input to the zero element, insert that into V1 if we
11082   // can do so cheaply.
11083   int NumElts = VT.getVectorNumElements();
11084   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
11085     return M >= NumElts;
11086   });
11087
11088   if (NumV2Elements == 1 && Mask[0] >= NumElts)
11089     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
11090                               DL, VT, V1, V2, Mask, Subtarget, DAG))
11091       return Insertion;
11092
11093   // Handle special cases where the lower or upper half is UNDEF.
11094   if (SDValue V =
11095           lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
11096     return V;
11097
11098   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
11099   // can check for those subtargets here and avoid much of the subtarget
11100   // querying in the per-vector-type lowering routines. With AVX1 we have
11101   // essentially *zero* ability to manipulate a 256-bit vector with integer
11102   // types. Since we'll use floating point types there eventually, just
11103   // immediately cast everything to a float and operate entirely in that domain.
11104   if (VT.isInteger() && !Subtarget->hasAVX2()) {
11105     int ElementBits = VT.getScalarSizeInBits();
11106     if (ElementBits < 32)
11107       // No floating point type available, decompose into 128-bit vectors.
11108       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11109
11110     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11111                                 VT.getVectorNumElements());
11112     V1 = DAG.getBitcast(FpVT, V1);
11113     V2 = DAG.getBitcast(FpVT, V2);
11114     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11115   }
11116
11117   switch (VT.SimpleTy) {
11118   case MVT::v4f64:
11119     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11120   case MVT::v4i64:
11121     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11122   case MVT::v8f32:
11123     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11124   case MVT::v8i32:
11125     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11126   case MVT::v16i16:
11127     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11128   case MVT::v32i8:
11129     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11130
11131   default:
11132     llvm_unreachable("Not a valid 256-bit x86 vector type!");
11133   }
11134 }
11135
11136 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
11137 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
11138                                         ArrayRef<int> Mask,
11139                                         SDValue V1, SDValue V2,
11140                                         SelectionDAG &DAG) {
11141   assert(VT.getScalarSizeInBits() == 64 &&
11142          "Unexpected element type size for 128bit shuffle.");
11143
11144   // To handle 256 bit vector requires VLX and most probably
11145   // function lowerV2X128VectorShuffle() is better solution.
11146   assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
11147
11148   SmallVector<int, 4> WidenedMask;
11149   if (!canWidenShuffleElements(Mask, WidenedMask))
11150     return SDValue();
11151
11152   // Form a 128-bit permutation.
11153   // Convert the 64-bit shuffle mask selection values into 128-bit selection
11154   // bits defined by a vshuf64x2 instruction's immediate control byte.
11155   unsigned PermMask = 0, Imm = 0;
11156   unsigned ControlBitsNum = WidenedMask.size() / 2;
11157
11158   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11159     if (WidenedMask[i] == SM_SentinelZero)
11160       return SDValue();
11161
11162     // Use first element in place of undef mask.
11163     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
11164     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
11165   }
11166
11167   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
11168                      DAG.getConstant(PermMask, DL, MVT::i8));
11169 }
11170
11171 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
11172                                            ArrayRef<int> Mask, SDValue V1,
11173                                            SDValue V2, SelectionDAG &DAG) {
11174
11175   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11176
11177   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11178   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11179
11180   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11181   if (isSingleInputShuffleMask(Mask))
11182     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11183
11184   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11185 }
11186
11187 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11188 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11189                                        const X86Subtarget *Subtarget,
11190                                        SelectionDAG &DAG) {
11191   SDLoc DL(Op);
11192   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11193   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11194   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11195   ArrayRef<int> Mask = SVOp->getMask();
11196   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11197
11198   if (SDValue Shuf128 =
11199           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11200     return Shuf128;
11201
11202   if (SDValue Unpck =
11203           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11204     return Unpck;
11205
11206   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11207 }
11208
11209 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11210 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11211                                         const X86Subtarget *Subtarget,
11212                                         SelectionDAG &DAG) {
11213   SDLoc DL(Op);
11214   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11215   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11216   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11217   ArrayRef<int> Mask = SVOp->getMask();
11218   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11219
11220   if (SDValue Unpck =
11221           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11222     return Unpck;
11223
11224   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11225 }
11226
11227 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11228 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11229                                        const X86Subtarget *Subtarget,
11230                                        SelectionDAG &DAG) {
11231   SDLoc DL(Op);
11232   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11233   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11234   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11235   ArrayRef<int> Mask = SVOp->getMask();
11236   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11237
11238   if (SDValue Shuf128 =
11239           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11240     return Shuf128;
11241
11242   if (SDValue Unpck =
11243           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11244     return Unpck;
11245
11246   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11247 }
11248
11249 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11250 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11251                                         const X86Subtarget *Subtarget,
11252                                         SelectionDAG &DAG) {
11253   SDLoc DL(Op);
11254   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11255   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11256   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11257   ArrayRef<int> Mask = SVOp->getMask();
11258   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11259
11260   if (SDValue Unpck =
11261           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11262     return Unpck;
11263
11264   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11265 }
11266
11267 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11268 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11269                                         const X86Subtarget *Subtarget,
11270                                         SelectionDAG &DAG) {
11271   SDLoc DL(Op);
11272   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11273   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11274   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11275   ArrayRef<int> Mask = SVOp->getMask();
11276   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11277   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11278
11279   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11280 }
11281
11282 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11283 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11284                                        const X86Subtarget *Subtarget,
11285                                        SelectionDAG &DAG) {
11286   SDLoc DL(Op);
11287   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11288   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11289   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11290   ArrayRef<int> Mask = SVOp->getMask();
11291   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11292   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11293
11294   // FIXME: Implement direct support for this type!
11295   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11296 }
11297
11298 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11299 ///
11300 /// This routine either breaks down the specific type of a 512-bit x86 vector
11301 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11302 /// together based on the available instructions.
11303 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11304                                         MVT VT, const X86Subtarget *Subtarget,
11305                                         SelectionDAG &DAG) {
11306   SDLoc DL(Op);
11307   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11308   ArrayRef<int> Mask = SVOp->getMask();
11309   assert(Subtarget->hasAVX512() &&
11310          "Cannot lower 512-bit vectors w/ basic ISA!");
11311
11312   // Check for being able to broadcast a single element.
11313   if (SDValue Broadcast =
11314           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11315     return Broadcast;
11316
11317   // Dispatch to each element type for lowering. If we don't have supprot for
11318   // specific element type shuffles at 512 bits, immediately split them and
11319   // lower them. Each lowering routine of a given type is allowed to assume that
11320   // the requisite ISA extensions for that element type are available.
11321   switch (VT.SimpleTy) {
11322   case MVT::v8f64:
11323     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11324   case MVT::v16f32:
11325     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11326   case MVT::v8i64:
11327     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11328   case MVT::v16i32:
11329     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11330   case MVT::v32i16:
11331     if (Subtarget->hasBWI())
11332       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11333     break;
11334   case MVT::v64i8:
11335     if (Subtarget->hasBWI())
11336       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11337     break;
11338
11339   default:
11340     llvm_unreachable("Not a valid 512-bit x86 vector type!");
11341   }
11342
11343   // Otherwise fall back on splitting.
11344   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11345 }
11346
11347 // Lower vXi1 vector shuffles.
11348 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11349 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11350 // vector, shuffle and then truncate it back.
11351 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11352                                       MVT VT, const X86Subtarget *Subtarget,
11353                                       SelectionDAG &DAG) {
11354   SDLoc DL(Op);
11355   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11356   ArrayRef<int> Mask = SVOp->getMask();
11357   assert(Subtarget->hasAVX512() &&
11358          "Cannot lower 512-bit vectors w/o basic ISA!");
11359   MVT ExtVT;
11360   switch (VT.SimpleTy) {
11361   default:
11362     llvm_unreachable("Expected a vector of i1 elements");
11363   case MVT::v2i1:
11364     ExtVT = MVT::v2i64;
11365     break;
11366   case MVT::v4i1:
11367     ExtVT = MVT::v4i32;
11368     break;
11369   case MVT::v8i1:
11370     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11371     break;
11372   case MVT::v16i1:
11373     ExtVT = MVT::v16i32;
11374     break;
11375   case MVT::v32i1:
11376     ExtVT = MVT::v32i16;
11377     break;
11378   case MVT::v64i1:
11379     ExtVT = MVT::v64i8;
11380     break;
11381   }
11382
11383   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11384     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11385   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11386     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11387   else
11388     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11389
11390   if (V2.isUndef())
11391     V2 = DAG.getUNDEF(ExtVT);
11392   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11393     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11394   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11395     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11396   else
11397     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11398   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11399                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11400 }
11401 /// \brief Top-level lowering for x86 vector shuffles.
11402 ///
11403 /// This handles decomposition, canonicalization, and lowering of all x86
11404 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11405 /// above in helper routines. The canonicalization attempts to widen shuffles
11406 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11407 /// s.t. only one of the two inputs needs to be tested, etc.
11408 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11409                                   SelectionDAG &DAG) {
11410   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11411   ArrayRef<int> Mask = SVOp->getMask();
11412   SDValue V1 = Op.getOperand(0);
11413   SDValue V2 = Op.getOperand(1);
11414   MVT VT = Op.getSimpleValueType();
11415   int NumElements = VT.getVectorNumElements();
11416   SDLoc dl(Op);
11417   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11418
11419   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11420          "Can't lower MMX shuffles");
11421
11422   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11423   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11424   if (V1IsUndef && V2IsUndef)
11425     return DAG.getUNDEF(VT);
11426
11427   // When we create a shuffle node we put the UNDEF node to second operand,
11428   // but in some cases the first operand may be transformed to UNDEF.
11429   // In this case we should just commute the node.
11430   if (V1IsUndef)
11431     return DAG.getCommutedVectorShuffle(*SVOp);
11432
11433   // Check for non-undef masks pointing at an undef vector and make the masks
11434   // undef as well. This makes it easier to match the shuffle based solely on
11435   // the mask.
11436   if (V2IsUndef)
11437     for (int M : Mask)
11438       if (M >= NumElements) {
11439         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11440         for (int &M : NewMask)
11441           if (M >= NumElements)
11442             M = -1;
11443         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11444       }
11445
11446   // We actually see shuffles that are entirely re-arrangements of a set of
11447   // zero inputs. This mostly happens while decomposing complex shuffles into
11448   // simple ones. Directly lower these as a buildvector of zeros.
11449   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11450   if (Zeroable.all())
11451     return getZeroVector(VT, Subtarget, DAG, dl);
11452
11453   // Try to collapse shuffles into using a vector type with fewer elements but
11454   // wider element types. We cap this to not form integers or floating point
11455   // elements wider than 64 bits, but it might be interesting to form i128
11456   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11457   SmallVector<int, 16> WidenedMask;
11458   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11459       canWidenShuffleElements(Mask, WidenedMask)) {
11460     MVT NewEltVT = VT.isFloatingPoint()
11461                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11462                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11463     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11464     // Make sure that the new vector type is legal. For example, v2f64 isn't
11465     // legal on SSE1.
11466     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11467       V1 = DAG.getBitcast(NewVT, V1);
11468       V2 = DAG.getBitcast(NewVT, V2);
11469       return DAG.getBitcast(
11470           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11471     }
11472   }
11473
11474   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11475   for (int M : SVOp->getMask())
11476     if (M < 0)
11477       ++NumUndefElements;
11478     else if (M < NumElements)
11479       ++NumV1Elements;
11480     else
11481       ++NumV2Elements;
11482
11483   // Commute the shuffle as needed such that more elements come from V1 than
11484   // V2. This allows us to match the shuffle pattern strictly on how many
11485   // elements come from V1 without handling the symmetric cases.
11486   if (NumV2Elements > NumV1Elements)
11487     return DAG.getCommutedVectorShuffle(*SVOp);
11488
11489   // When the number of V1 and V2 elements are the same, try to minimize the
11490   // number of uses of V2 in the low half of the vector. When that is tied,
11491   // ensure that the sum of indices for V1 is equal to or lower than the sum
11492   // indices for V2. When those are equal, try to ensure that the number of odd
11493   // indices for V1 is lower than the number of odd indices for V2.
11494   if (NumV1Elements == NumV2Elements) {
11495     int LowV1Elements = 0, LowV2Elements = 0;
11496     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11497       if (M >= NumElements)
11498         ++LowV2Elements;
11499       else if (M >= 0)
11500         ++LowV1Elements;
11501     if (LowV2Elements > LowV1Elements) {
11502       return DAG.getCommutedVectorShuffle(*SVOp);
11503     } else if (LowV2Elements == LowV1Elements) {
11504       int SumV1Indices = 0, SumV2Indices = 0;
11505       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11506         if (SVOp->getMask()[i] >= NumElements)
11507           SumV2Indices += i;
11508         else if (SVOp->getMask()[i] >= 0)
11509           SumV1Indices += i;
11510       if (SumV2Indices < SumV1Indices) {
11511         return DAG.getCommutedVectorShuffle(*SVOp);
11512       } else if (SumV2Indices == SumV1Indices) {
11513         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11514         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11515           if (SVOp->getMask()[i] >= NumElements)
11516             NumV2OddIndices += i % 2;
11517           else if (SVOp->getMask()[i] >= 0)
11518             NumV1OddIndices += i % 2;
11519         if (NumV2OddIndices < NumV1OddIndices)
11520           return DAG.getCommutedVectorShuffle(*SVOp);
11521       }
11522     }
11523   }
11524
11525   // For each vector width, delegate to a specialized lowering routine.
11526   if (VT.is128BitVector())
11527     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11528
11529   if (VT.is256BitVector())
11530     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11531
11532   if (VT.is512BitVector())
11533     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11534
11535   if (Is1BitVector)
11536     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11537   llvm_unreachable("Unimplemented!");
11538 }
11539
11540 // This function assumes its argument is a BUILD_VECTOR of constants or
11541 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11542 // true.
11543 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11544                                     unsigned &MaskValue) {
11545   MaskValue = 0;
11546   unsigned NumElems = BuildVector->getNumOperands();
11547
11548   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11549   // We don't handle the >2 lanes case right now.
11550   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11551   if (NumLanes > 2)
11552     return false;
11553
11554   unsigned NumElemsInLane = NumElems / NumLanes;
11555
11556   // Blend for v16i16 should be symmetric for the both lanes.
11557   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11558     SDValue EltCond = BuildVector->getOperand(i);
11559     SDValue SndLaneEltCond =
11560         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11561
11562     int Lane1Cond = -1, Lane2Cond = -1;
11563     if (isa<ConstantSDNode>(EltCond))
11564       Lane1Cond = !isNullConstant(EltCond);
11565     if (isa<ConstantSDNode>(SndLaneEltCond))
11566       Lane2Cond = !isNullConstant(SndLaneEltCond);
11567
11568     unsigned LaneMask = 0;
11569     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11570       // Lane1Cond != 0, means we want the first argument.
11571       // Lane1Cond == 0, means we want the second argument.
11572       // The encoding of this argument is 0 for the first argument, 1
11573       // for the second. Therefore, invert the condition.
11574       LaneMask = !Lane1Cond << i;
11575     else if (Lane1Cond < 0)
11576       LaneMask = !Lane2Cond << i;
11577     else
11578       return false;
11579
11580     MaskValue |= LaneMask;
11581     if (NumLanes == 2)
11582       MaskValue |= LaneMask << NumElemsInLane;
11583   }
11584   return true;
11585 }
11586
11587 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11588 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11589                                            const X86Subtarget *Subtarget,
11590                                            SelectionDAG &DAG) {
11591   SDValue Cond = Op.getOperand(0);
11592   SDValue LHS = Op.getOperand(1);
11593   SDValue RHS = Op.getOperand(2);
11594   SDLoc dl(Op);
11595   MVT VT = Op.getSimpleValueType();
11596
11597   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11598     return SDValue();
11599   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11600
11601   // Only non-legal VSELECTs reach this lowering, convert those into generic
11602   // shuffles and re-use the shuffle lowering path for blends.
11603   SmallVector<int, 32> Mask;
11604   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11605     SDValue CondElt = CondBV->getOperand(i);
11606     Mask.push_back(
11607         isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11608                                      : -1);
11609   }
11610   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11611 }
11612
11613 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11614   // A vselect where all conditions and data are constants can be optimized into
11615   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11616   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11617       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11618       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11619     return SDValue();
11620
11621   // Try to lower this to a blend-style vector shuffle. This can handle all
11622   // constant condition cases.
11623   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11624     return BlendOp;
11625
11626   // Variable blends are only legal from SSE4.1 onward.
11627   if (!Subtarget->hasSSE41())
11628     return SDValue();
11629
11630   // Only some types will be legal on some subtargets. If we can emit a legal
11631   // VSELECT-matching blend, return Op, and but if we need to expand, return
11632   // a null value.
11633   switch (Op.getSimpleValueType().SimpleTy) {
11634   default:
11635     // Most of the vector types have blends past SSE4.1.
11636     return Op;
11637
11638   case MVT::v32i8:
11639     // The byte blends for AVX vectors were introduced only in AVX2.
11640     if (Subtarget->hasAVX2())
11641       return Op;
11642
11643     return SDValue();
11644
11645   case MVT::v8i16:
11646   case MVT::v16i16:
11647     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11648     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11649       return Op;
11650
11651     // FIXME: We should custom lower this by fixing the condition and using i8
11652     // blends.
11653     return SDValue();
11654   }
11655 }
11656
11657 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11658   MVT VT = Op.getSimpleValueType();
11659   SDLoc dl(Op);
11660
11661   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11662     return SDValue();
11663
11664   if (VT.getSizeInBits() == 8) {
11665     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11666                                   Op.getOperand(0), Op.getOperand(1));
11667     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11668                                   DAG.getValueType(VT));
11669     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11670   }
11671
11672   if (VT.getSizeInBits() == 16) {
11673     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11674     if (isNullConstant(Op.getOperand(1)))
11675       return DAG.getNode(
11676           ISD::TRUNCATE, dl, MVT::i16,
11677           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11678                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11679                       Op.getOperand(1)));
11680     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11681                                   Op.getOperand(0), Op.getOperand(1));
11682     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11683                                   DAG.getValueType(VT));
11684     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11685   }
11686
11687   if (VT == MVT::f32) {
11688     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11689     // the result back to FR32 register. It's only worth matching if the
11690     // result has a single use which is a store or a bitcast to i32.  And in
11691     // the case of a store, it's not worth it if the index is a constant 0,
11692     // because a MOVSSmr can be used instead, which is smaller and faster.
11693     if (!Op.hasOneUse())
11694       return SDValue();
11695     SDNode *User = *Op.getNode()->use_begin();
11696     if ((User->getOpcode() != ISD::STORE ||
11697          isNullConstant(Op.getOperand(1))) &&
11698         (User->getOpcode() != ISD::BITCAST ||
11699          User->getValueType(0) != MVT::i32))
11700       return SDValue();
11701     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11702                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11703                                   Op.getOperand(1));
11704     return DAG.getBitcast(MVT::f32, Extract);
11705   }
11706
11707   if (VT == MVT::i32 || VT == MVT::i64) {
11708     // ExtractPS/pextrq works with constant index.
11709     if (isa<ConstantSDNode>(Op.getOperand(1)))
11710       return Op;
11711   }
11712   return SDValue();
11713 }
11714
11715 /// Extract one bit from mask vector, like v16i1 or v8i1.
11716 /// AVX-512 feature.
11717 SDValue
11718 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11719   SDValue Vec = Op.getOperand(0);
11720   SDLoc dl(Vec);
11721   MVT VecVT = Vec.getSimpleValueType();
11722   SDValue Idx = Op.getOperand(1);
11723   MVT EltVT = Op.getSimpleValueType();
11724
11725   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11726   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11727          "Unexpected vector type in ExtractBitFromMaskVector");
11728
11729   // variable index can't be handled in mask registers,
11730   // extend vector to VR512
11731   if (!isa<ConstantSDNode>(Idx)) {
11732     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11733     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11734     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11735                               ExtVT.getVectorElementType(), Ext, Idx);
11736     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11737   }
11738
11739   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11740   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11741   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11742     rc = getRegClassFor(MVT::v16i1);
11743   unsigned MaxSift = rc->getSize()*8 - 1;
11744   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11745                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11746   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11747                     DAG.getConstant(MaxSift, dl, MVT::i8));
11748   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11749                        DAG.getIntPtrConstant(0, dl));
11750 }
11751
11752 SDValue
11753 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11754                                            SelectionDAG &DAG) const {
11755   SDLoc dl(Op);
11756   SDValue Vec = Op.getOperand(0);
11757   MVT VecVT = Vec.getSimpleValueType();
11758   SDValue Idx = Op.getOperand(1);
11759
11760   if (Op.getSimpleValueType() == MVT::i1)
11761     return ExtractBitFromMaskVector(Op, DAG);
11762
11763   if (!isa<ConstantSDNode>(Idx)) {
11764     if (VecVT.is512BitVector() ||
11765         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11766          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11767
11768       MVT MaskEltVT =
11769         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11770       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11771                                     MaskEltVT.getSizeInBits());
11772
11773       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11774       auto PtrVT = getPointerTy(DAG.getDataLayout());
11775       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11776                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11777                                  DAG.getConstant(0, dl, PtrVT));
11778       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11779       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11780                          DAG.getConstant(0, dl, PtrVT));
11781     }
11782     return SDValue();
11783   }
11784
11785   // If this is a 256-bit vector result, first extract the 128-bit vector and
11786   // then extract the element from the 128-bit vector.
11787   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11788
11789     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11790     // Get the 128-bit vector.
11791     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11792     MVT EltVT = VecVT.getVectorElementType();
11793
11794     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11795     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11796
11797     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11798     // this can be done with a mask.
11799     IdxVal &= ElemsPerChunk - 1;
11800     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11801                        DAG.getConstant(IdxVal, dl, MVT::i32));
11802   }
11803
11804   assert(VecVT.is128BitVector() && "Unexpected vector length");
11805
11806   if (Subtarget->hasSSE41())
11807     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11808       return Res;
11809
11810   MVT VT = Op.getSimpleValueType();
11811   // TODO: handle v16i8.
11812   if (VT.getSizeInBits() == 16) {
11813     SDValue Vec = Op.getOperand(0);
11814     if (isNullConstant(Op.getOperand(1)))
11815       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11816                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11817                                      DAG.getBitcast(MVT::v4i32, Vec),
11818                                      Op.getOperand(1)));
11819     // Transform it so it match pextrw which produces a 32-bit result.
11820     MVT EltVT = MVT::i32;
11821     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11822                                   Op.getOperand(0), Op.getOperand(1));
11823     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11824                                   DAG.getValueType(VT));
11825     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11826   }
11827
11828   if (VT.getSizeInBits() == 32) {
11829     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11830     if (Idx == 0)
11831       return Op;
11832
11833     // SHUFPS the element to the lowest double word, then movss.
11834     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11835     MVT VVT = Op.getOperand(0).getSimpleValueType();
11836     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11837                                        DAG.getUNDEF(VVT), Mask);
11838     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11839                        DAG.getIntPtrConstant(0, dl));
11840   }
11841
11842   if (VT.getSizeInBits() == 64) {
11843     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11844     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11845     //        to match extract_elt for f64.
11846     if (isNullConstant(Op.getOperand(1)))
11847       return Op;
11848
11849     // UNPCKHPD the element to the lowest double word, then movsd.
11850     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11851     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11852     int Mask[2] = { 1, -1 };
11853     MVT VVT = Op.getOperand(0).getSimpleValueType();
11854     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11855                                        DAG.getUNDEF(VVT), Mask);
11856     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11857                        DAG.getIntPtrConstant(0, dl));
11858   }
11859
11860   return SDValue();
11861 }
11862
11863 /// Insert one bit to mask vector, like v16i1 or v8i1.
11864 /// AVX-512 feature.
11865 SDValue
11866 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11867   SDLoc dl(Op);
11868   SDValue Vec = Op.getOperand(0);
11869   SDValue Elt = Op.getOperand(1);
11870   SDValue Idx = Op.getOperand(2);
11871   MVT VecVT = Vec.getSimpleValueType();
11872
11873   if (!isa<ConstantSDNode>(Idx)) {
11874     // Non constant index. Extend source and destination,
11875     // insert element and then truncate the result.
11876     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11877     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11878     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11879       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11880       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11881     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11882   }
11883
11884   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11885   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11886   if (IdxVal)
11887     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11888                            DAG.getConstant(IdxVal, dl, MVT::i8));
11889   if (Vec.getOpcode() == ISD::UNDEF)
11890     return EltInVec;
11891   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11892 }
11893
11894 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11895                                                   SelectionDAG &DAG) const {
11896   MVT VT = Op.getSimpleValueType();
11897   MVT EltVT = VT.getVectorElementType();
11898
11899   if (EltVT == MVT::i1)
11900     return InsertBitToMaskVector(Op, DAG);
11901
11902   SDLoc dl(Op);
11903   SDValue N0 = Op.getOperand(0);
11904   SDValue N1 = Op.getOperand(1);
11905   SDValue N2 = Op.getOperand(2);
11906   if (!isa<ConstantSDNode>(N2))
11907     return SDValue();
11908   auto *N2C = cast<ConstantSDNode>(N2);
11909   unsigned IdxVal = N2C->getZExtValue();
11910
11911   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11912   // into that, and then insert the subvector back into the result.
11913   if (VT.is256BitVector() || VT.is512BitVector()) {
11914     // With a 256-bit vector, we can insert into the zero element efficiently
11915     // using a blend if we have AVX or AVX2 and the right data type.
11916     if (VT.is256BitVector() && IdxVal == 0) {
11917       // TODO: It is worthwhile to cast integer to floating point and back
11918       // and incur a domain crossing penalty if that's what we'll end up
11919       // doing anyway after extracting to a 128-bit vector.
11920       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11921           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11922         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11923         N2 = DAG.getIntPtrConstant(1, dl);
11924         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11925       }
11926     }
11927
11928     // Get the desired 128-bit vector chunk.
11929     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11930
11931     // Insert the element into the desired chunk.
11932     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11933     assert(isPowerOf2_32(NumEltsIn128));
11934     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11935     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11936
11937     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11938                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11939
11940     // Insert the changed part back into the bigger vector
11941     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11942   }
11943   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11944
11945   if (Subtarget->hasSSE41()) {
11946     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11947       unsigned Opc;
11948       if (VT == MVT::v8i16) {
11949         Opc = X86ISD::PINSRW;
11950       } else {
11951         assert(VT == MVT::v16i8);
11952         Opc = X86ISD::PINSRB;
11953       }
11954
11955       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11956       // argument.
11957       if (N1.getValueType() != MVT::i32)
11958         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11959       if (N2.getValueType() != MVT::i32)
11960         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11961       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11962     }
11963
11964     if (EltVT == MVT::f32) {
11965       // Bits [7:6] of the constant are the source select. This will always be
11966       //   zero here. The DAG Combiner may combine an extract_elt index into
11967       //   these bits. For example (insert (extract, 3), 2) could be matched by
11968       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11969       // Bits [5:4] of the constant are the destination select. This is the
11970       //   value of the incoming immediate.
11971       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11972       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11973
11974       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11975       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11976         // If this is an insertion of 32-bits into the low 32-bits of
11977         // a vector, we prefer to generate a blend with immediate rather
11978         // than an insertps. Blends are simpler operations in hardware and so
11979         // will always have equal or better performance than insertps.
11980         // But if optimizing for size and there's a load folding opportunity,
11981         // generate insertps because blendps does not have a 32-bit memory
11982         // operand form.
11983         N2 = DAG.getIntPtrConstant(1, dl);
11984         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11985         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11986       }
11987       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11988       // Create this as a scalar to vector..
11989       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11990       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11991     }
11992
11993     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11994       // PINSR* works with constant index.
11995       return Op;
11996     }
11997   }
11998
11999   if (EltVT == MVT::i8)
12000     return SDValue();
12001
12002   if (EltVT.getSizeInBits() == 16) {
12003     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
12004     // as its second argument.
12005     if (N1.getValueType() != MVT::i32)
12006       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12007     if (N2.getValueType() != MVT::i32)
12008       N2 = DAG.getIntPtrConstant(IdxVal, dl);
12009     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
12010   }
12011   return SDValue();
12012 }
12013
12014 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
12015   SDLoc dl(Op);
12016   MVT OpVT = Op.getSimpleValueType();
12017
12018   // If this is a 256-bit vector result, first insert into a 128-bit
12019   // vector and then insert into the 256-bit vector.
12020   if (!OpVT.is128BitVector()) {
12021     // Insert into a 128-bit vector.
12022     unsigned SizeFactor = OpVT.getSizeInBits()/128;
12023     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
12024                                  OpVT.getVectorNumElements() / SizeFactor);
12025
12026     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
12027
12028     // Insert the 128-bit vector.
12029     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12030   }
12031
12032   if (OpVT == MVT::v1i64 &&
12033       Op.getOperand(0).getValueType() == MVT::i64)
12034     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12035
12036   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12037   assert(OpVT.is128BitVector() && "Expected an SSE type!");
12038   return DAG.getBitcast(
12039       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
12040 }
12041
12042 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
12043 // a simple subregister reference or explicit instructions to grab
12044 // upper bits of a vector.
12045 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12046                                       SelectionDAG &DAG) {
12047   SDLoc dl(Op);
12048   SDValue In =  Op.getOperand(0);
12049   SDValue Idx = Op.getOperand(1);
12050   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12051   MVT ResVT   = Op.getSimpleValueType();
12052   MVT InVT    = In.getSimpleValueType();
12053
12054   if (Subtarget->hasFp256()) {
12055     if (ResVT.is128BitVector() &&
12056         (InVT.is256BitVector() || InVT.is512BitVector()) &&
12057         isa<ConstantSDNode>(Idx)) {
12058       return Extract128BitVector(In, IdxVal, DAG, dl);
12059     }
12060     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12061         isa<ConstantSDNode>(Idx)) {
12062       return Extract256BitVector(In, IdxVal, DAG, dl);
12063     }
12064   }
12065   return SDValue();
12066 }
12067
12068 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
12069 // simple superregister reference or explicit instructions to insert
12070 // the upper bits of a vector.
12071 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12072                                      SelectionDAG &DAG) {
12073   if (!Subtarget->hasAVX())
12074     return SDValue();
12075
12076   SDLoc dl(Op);
12077   SDValue Vec = Op.getOperand(0);
12078   SDValue SubVec = Op.getOperand(1);
12079   SDValue Idx = Op.getOperand(2);
12080
12081   if (!isa<ConstantSDNode>(Idx))
12082     return SDValue();
12083
12084   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12085   MVT OpVT = Op.getSimpleValueType();
12086   MVT SubVecVT = SubVec.getSimpleValueType();
12087
12088   // Fold two 16-byte subvector loads into one 32-byte load:
12089   // (insert_subvector (insert_subvector undef, (load addr), 0),
12090   //                   (load addr + 16), Elts/2)
12091   // --> load32 addr
12092   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
12093       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
12094       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
12095     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
12096     if (Idx2 && Idx2->getZExtValue() == 0) {
12097       SDValue SubVec2 = Vec.getOperand(1);
12098       // If needed, look through a bitcast to get to the load.
12099       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
12100         SubVec2 = SubVec2.getOperand(0);
12101
12102       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
12103         bool Fast;
12104         unsigned Alignment = FirstLd->getAlignment();
12105         unsigned AS = FirstLd->getAddressSpace();
12106         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
12107         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
12108                                     OpVT, AS, Alignment, &Fast) && Fast) {
12109           SDValue Ops[] = { SubVec2, SubVec };
12110           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
12111             return Ld;
12112         }
12113       }
12114     }
12115   }
12116
12117   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
12118       SubVecVT.is128BitVector())
12119     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12120
12121   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
12122     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12123
12124   if (OpVT.getVectorElementType() == MVT::i1)
12125     return Insert1BitVector(Op, DAG);
12126
12127   return SDValue();
12128 }
12129
12130 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12131 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12132 // one of the above mentioned nodes. It has to be wrapped because otherwise
12133 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12134 // be used to form addressing mode. These wrapped nodes will be selected
12135 // into MOV32ri.
12136 SDValue
12137 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12138   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12139
12140   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12141   // global base reg.
12142   unsigned char OpFlag = 0;
12143   unsigned WrapperKind = X86ISD::Wrapper;
12144   CodeModel::Model M = DAG.getTarget().getCodeModel();
12145
12146   if (Subtarget->isPICStyleRIPRel() &&
12147       (M == CodeModel::Small || M == CodeModel::Kernel))
12148     WrapperKind = X86ISD::WrapperRIP;
12149   else if (Subtarget->isPICStyleGOT())
12150     OpFlag = X86II::MO_GOTOFF;
12151   else if (Subtarget->isPICStyleStubPIC())
12152     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12153
12154   auto PtrVT = getPointerTy(DAG.getDataLayout());
12155   SDValue Result = DAG.getTargetConstantPool(
12156       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
12157   SDLoc DL(CP);
12158   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12159   // With PIC, the address is actually $g + Offset.
12160   if (OpFlag) {
12161     Result =
12162         DAG.getNode(ISD::ADD, DL, PtrVT,
12163                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12164   }
12165
12166   return Result;
12167 }
12168
12169 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12170   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12171
12172   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12173   // global base reg.
12174   unsigned char OpFlag = 0;
12175   unsigned WrapperKind = X86ISD::Wrapper;
12176   CodeModel::Model M = DAG.getTarget().getCodeModel();
12177
12178   if (Subtarget->isPICStyleRIPRel() &&
12179       (M == CodeModel::Small || M == CodeModel::Kernel))
12180     WrapperKind = X86ISD::WrapperRIP;
12181   else if (Subtarget->isPICStyleGOT())
12182     OpFlag = X86II::MO_GOTOFF;
12183   else if (Subtarget->isPICStyleStubPIC())
12184     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12185
12186   auto PtrVT = getPointerTy(DAG.getDataLayout());
12187   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12188   SDLoc DL(JT);
12189   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12190
12191   // With PIC, the address is actually $g + Offset.
12192   if (OpFlag)
12193     Result =
12194         DAG.getNode(ISD::ADD, DL, PtrVT,
12195                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12196
12197   return Result;
12198 }
12199
12200 SDValue
12201 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12202   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12203
12204   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12205   // global base reg.
12206   unsigned char OpFlag = 0;
12207   unsigned WrapperKind = X86ISD::Wrapper;
12208   CodeModel::Model M = DAG.getTarget().getCodeModel();
12209
12210   if (Subtarget->isPICStyleRIPRel() &&
12211       (M == CodeModel::Small || M == CodeModel::Kernel)) {
12212     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12213       OpFlag = X86II::MO_GOTPCREL;
12214     WrapperKind = X86ISD::WrapperRIP;
12215   } else if (Subtarget->isPICStyleGOT()) {
12216     OpFlag = X86II::MO_GOT;
12217   } else if (Subtarget->isPICStyleStubPIC()) {
12218     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12219   } else if (Subtarget->isPICStyleStubNoDynamic()) {
12220     OpFlag = X86II::MO_DARWIN_NONLAZY;
12221   }
12222
12223   auto PtrVT = getPointerTy(DAG.getDataLayout());
12224   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12225
12226   SDLoc DL(Op);
12227   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12228
12229   // With PIC, the address is actually $g + Offset.
12230   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12231       !Subtarget->is64Bit()) {
12232     Result =
12233         DAG.getNode(ISD::ADD, DL, PtrVT,
12234                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12235   }
12236
12237   // For symbols that require a load from a stub to get the address, emit the
12238   // load.
12239   if (isGlobalStubReference(OpFlag))
12240     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12241                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12242                          false, false, false, 0);
12243
12244   return Result;
12245 }
12246
12247 SDValue
12248 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12249   // Create the TargetBlockAddressAddress node.
12250   unsigned char OpFlags =
12251     Subtarget->ClassifyBlockAddressReference();
12252   CodeModel::Model M = DAG.getTarget().getCodeModel();
12253   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12254   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12255   SDLoc dl(Op);
12256   auto PtrVT = getPointerTy(DAG.getDataLayout());
12257   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12258
12259   if (Subtarget->isPICStyleRIPRel() &&
12260       (M == CodeModel::Small || M == CodeModel::Kernel))
12261     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12262   else
12263     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12264
12265   // With PIC, the address is actually $g + Offset.
12266   if (isGlobalRelativeToPICBase(OpFlags)) {
12267     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12268                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12269   }
12270
12271   return Result;
12272 }
12273
12274 SDValue
12275 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12276                                       int64_t Offset, SelectionDAG &DAG) const {
12277   // Create the TargetGlobalAddress node, folding in the constant
12278   // offset if it is legal.
12279   unsigned char OpFlags =
12280       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12281   CodeModel::Model M = DAG.getTarget().getCodeModel();
12282   auto PtrVT = getPointerTy(DAG.getDataLayout());
12283   SDValue Result;
12284   if (OpFlags == X86II::MO_NO_FLAG &&
12285       X86::isOffsetSuitableForCodeModel(Offset, M)) {
12286     // A direct static reference to a global.
12287     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12288     Offset = 0;
12289   } else {
12290     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12291   }
12292
12293   if (Subtarget->isPICStyleRIPRel() &&
12294       (M == CodeModel::Small || M == CodeModel::Kernel))
12295     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12296   else
12297     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12298
12299   // With PIC, the address is actually $g + Offset.
12300   if (isGlobalRelativeToPICBase(OpFlags)) {
12301     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12302                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12303   }
12304
12305   // For globals that require a load from a stub to get the address, emit the
12306   // load.
12307   if (isGlobalStubReference(OpFlags))
12308     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12309                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12310                          false, false, false, 0);
12311
12312   // If there was a non-zero offset that we didn't fold, create an explicit
12313   // addition for it.
12314   if (Offset != 0)
12315     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12316                          DAG.getConstant(Offset, dl, PtrVT));
12317
12318   return Result;
12319 }
12320
12321 SDValue
12322 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12323   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12324   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12325   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12326 }
12327
12328 static SDValue
12329 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12330            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12331            unsigned char OperandFlags, bool LocalDynamic = false) {
12332   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12333   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12334   SDLoc dl(GA);
12335   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12336                                            GA->getValueType(0),
12337                                            GA->getOffset(),
12338                                            OperandFlags);
12339
12340   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12341                                            : X86ISD::TLSADDR;
12342
12343   if (InFlag) {
12344     SDValue Ops[] = { Chain,  TGA, *InFlag };
12345     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12346   } else {
12347     SDValue Ops[]  = { Chain, TGA };
12348     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12349   }
12350
12351   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12352   MFI->setAdjustsStack(true);
12353   MFI->setHasCalls(true);
12354
12355   SDValue Flag = Chain.getValue(1);
12356   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12357 }
12358
12359 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12360 static SDValue
12361 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12362                                 const EVT PtrVT) {
12363   SDValue InFlag;
12364   SDLoc dl(GA);  // ? function entry point might be better
12365   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12366                                    DAG.getNode(X86ISD::GlobalBaseReg,
12367                                                SDLoc(), PtrVT), InFlag);
12368   InFlag = Chain.getValue(1);
12369
12370   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12371 }
12372
12373 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12374 static SDValue
12375 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12376                                 const EVT PtrVT) {
12377   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12378                     X86::RAX, X86II::MO_TLSGD);
12379 }
12380
12381 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12382                                            SelectionDAG &DAG,
12383                                            const EVT PtrVT,
12384                                            bool is64Bit) {
12385   SDLoc dl(GA);
12386
12387   // Get the start address of the TLS block for this module.
12388   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12389       .getInfo<X86MachineFunctionInfo>();
12390   MFI->incNumLocalDynamicTLSAccesses();
12391
12392   SDValue Base;
12393   if (is64Bit) {
12394     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12395                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12396   } else {
12397     SDValue InFlag;
12398     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12399         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12400     InFlag = Chain.getValue(1);
12401     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12402                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12403   }
12404
12405   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12406   // of Base.
12407
12408   // Build x@dtpoff.
12409   unsigned char OperandFlags = X86II::MO_DTPOFF;
12410   unsigned WrapperKind = X86ISD::Wrapper;
12411   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12412                                            GA->getValueType(0),
12413                                            GA->getOffset(), OperandFlags);
12414   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12415
12416   // Add x@dtpoff with the base.
12417   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12418 }
12419
12420 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12421 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12422                                    const EVT PtrVT, TLSModel::Model model,
12423                                    bool is64Bit, bool isPIC) {
12424   SDLoc dl(GA);
12425
12426   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12427   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12428                                                          is64Bit ? 257 : 256));
12429
12430   SDValue ThreadPointer =
12431       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12432                   MachinePointerInfo(Ptr), false, false, false, 0);
12433
12434   unsigned char OperandFlags = 0;
12435   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12436   // initialexec.
12437   unsigned WrapperKind = X86ISD::Wrapper;
12438   if (model == TLSModel::LocalExec) {
12439     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12440   } else if (model == TLSModel::InitialExec) {
12441     if (is64Bit) {
12442       OperandFlags = X86II::MO_GOTTPOFF;
12443       WrapperKind = X86ISD::WrapperRIP;
12444     } else {
12445       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12446     }
12447   } else {
12448     llvm_unreachable("Unexpected model");
12449   }
12450
12451   // emit "addl x@ntpoff,%eax" (local exec)
12452   // or "addl x@indntpoff,%eax" (initial exec)
12453   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12454   SDValue TGA =
12455       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12456                                  GA->getOffset(), OperandFlags);
12457   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12458
12459   if (model == TLSModel::InitialExec) {
12460     if (isPIC && !is64Bit) {
12461       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12462                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12463                            Offset);
12464     }
12465
12466     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12467                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12468                          false, false, false, 0);
12469   }
12470
12471   // The address of the thread local variable is the add of the thread
12472   // pointer with the offset of the variable.
12473   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12474 }
12475
12476 SDValue
12477 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12478
12479   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12480
12481   // Cygwin uses emutls.
12482   // FIXME: It may be EmulatedTLS-generic also for X86-Android.
12483   if (Subtarget->isTargetWindowsCygwin())
12484     return LowerToTLSEmulatedModel(GA, DAG);
12485
12486   const GlobalValue *GV = GA->getGlobal();
12487   auto PtrVT = getPointerTy(DAG.getDataLayout());
12488
12489   if (Subtarget->isTargetELF()) {
12490     if (DAG.getTarget().Options.EmulatedTLS)
12491       return LowerToTLSEmulatedModel(GA, DAG);
12492     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12493     switch (model) {
12494       case TLSModel::GeneralDynamic:
12495         if (Subtarget->is64Bit())
12496           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12497         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12498       case TLSModel::LocalDynamic:
12499         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12500                                            Subtarget->is64Bit());
12501       case TLSModel::InitialExec:
12502       case TLSModel::LocalExec:
12503         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12504                                    DAG.getTarget().getRelocationModel() ==
12505                                        Reloc::PIC_);
12506     }
12507     llvm_unreachable("Unknown TLS model.");
12508   }
12509
12510   if (Subtarget->isTargetDarwin()) {
12511     // Darwin only has one model of TLS.  Lower to that.
12512     unsigned char OpFlag = 0;
12513     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12514                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12515
12516     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12517     // global base reg.
12518     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12519                  !Subtarget->is64Bit();
12520     if (PIC32)
12521       OpFlag = X86II::MO_TLVP_PIC_BASE;
12522     else
12523       OpFlag = X86II::MO_TLVP;
12524     SDLoc DL(Op);
12525     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12526                                                 GA->getValueType(0),
12527                                                 GA->getOffset(), OpFlag);
12528     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12529
12530     // With PIC32, the address is actually $g + Offset.
12531     if (PIC32)
12532       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12533                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12534                            Offset);
12535
12536     // Lowering the machine isd will make sure everything is in the right
12537     // location.
12538     SDValue Chain = DAG.getEntryNode();
12539     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12540     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, DL, true), DL);
12541     SDValue Args[] = { Chain, Offset };
12542     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12543     Chain =
12544         DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
12545                            DAG.getIntPtrConstant(0, DL, true), SDValue(), DL);
12546
12547     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12548     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12549     MFI->setAdjustsStack(true);
12550
12551     // And our return value (tls address) is in the standard call return value
12552     // location.
12553     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12554     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12555   }
12556
12557   if (Subtarget->isTargetKnownWindowsMSVC() ||
12558       Subtarget->isTargetWindowsGNU()) {
12559     // Just use the implicit TLS architecture
12560     // Need to generate someting similar to:
12561     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12562     //                                  ; from TEB
12563     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12564     //   mov     rcx, qword [rdx+rcx*8]
12565     //   mov     eax, .tls$:tlsvar
12566     //   [rax+rcx] contains the address
12567     // Windows 64bit: gs:0x58
12568     // Windows 32bit: fs:__tls_array
12569
12570     SDLoc dl(GA);
12571     SDValue Chain = DAG.getEntryNode();
12572
12573     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12574     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12575     // use its literal value of 0x2C.
12576     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12577                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12578                                                              256)
12579                                         : Type::getInt32PtrTy(*DAG.getContext(),
12580                                                               257));
12581
12582     SDValue TlsArray = Subtarget->is64Bit()
12583                            ? DAG.getIntPtrConstant(0x58, dl)
12584                            : (Subtarget->isTargetWindowsGNU()
12585                                   ? DAG.getIntPtrConstant(0x2C, dl)
12586                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12587
12588     SDValue ThreadPointer =
12589         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12590                     false, false, 0);
12591
12592     SDValue res;
12593     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12594       res = ThreadPointer;
12595     } else {
12596       // Load the _tls_index variable
12597       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12598       if (Subtarget->is64Bit())
12599         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12600                              MachinePointerInfo(), MVT::i32, false, false,
12601                              false, 0);
12602       else
12603         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12604                           false, false, 0);
12605
12606       auto &DL = DAG.getDataLayout();
12607       SDValue Scale =
12608           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12609       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12610
12611       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12612     }
12613
12614     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12615                       false, 0);
12616
12617     // Get the offset of start of .tls section
12618     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12619                                              GA->getValueType(0),
12620                                              GA->getOffset(), X86II::MO_SECREL);
12621     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12622
12623     // The address of the thread local variable is the add of the thread
12624     // pointer with the offset of the variable.
12625     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12626   }
12627
12628   llvm_unreachable("TLS not implemented for this target.");
12629 }
12630
12631 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12632 /// and take a 2 x i32 value to shift plus a shift amount.
12633 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12634   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12635   MVT VT = Op.getSimpleValueType();
12636   unsigned VTBits = VT.getSizeInBits();
12637   SDLoc dl(Op);
12638   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12639   SDValue ShOpLo = Op.getOperand(0);
12640   SDValue ShOpHi = Op.getOperand(1);
12641   SDValue ShAmt  = Op.getOperand(2);
12642   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12643   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12644   // during isel.
12645   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12646                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12647   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12648                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12649                        : DAG.getConstant(0, dl, VT);
12650
12651   SDValue Tmp2, Tmp3;
12652   if (Op.getOpcode() == ISD::SHL_PARTS) {
12653     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12654     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12655   } else {
12656     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12657     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12658   }
12659
12660   // If the shift amount is larger or equal than the width of a part we can't
12661   // rely on the results of shld/shrd. Insert a test and select the appropriate
12662   // values for large shift amounts.
12663   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12664                                 DAG.getConstant(VTBits, dl, MVT::i8));
12665   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12666                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12667
12668   SDValue Hi, Lo;
12669   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12670   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12671   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12672
12673   if (Op.getOpcode() == ISD::SHL_PARTS) {
12674     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12675     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12676   } else {
12677     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12678     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12679   }
12680
12681   SDValue Ops[2] = { Lo, Hi };
12682   return DAG.getMergeValues(Ops, dl);
12683 }
12684
12685 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12686                                            SelectionDAG &DAG) const {
12687   SDValue Src = Op.getOperand(0);
12688   MVT SrcVT = Src.getSimpleValueType();
12689   MVT VT = Op.getSimpleValueType();
12690   SDLoc dl(Op);
12691
12692   if (SrcVT.isVector()) {
12693     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12694       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12695                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12696                          DAG.getUNDEF(SrcVT)));
12697     }
12698     if (SrcVT.getVectorElementType() == MVT::i1) {
12699       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12700       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12701                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12702     }
12703     return SDValue();
12704   }
12705
12706   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12707          "Unknown SINT_TO_FP to lower!");
12708
12709   // These are really Legal; return the operand so the caller accepts it as
12710   // Legal.
12711   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12712     return Op;
12713   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12714       Subtarget->is64Bit()) {
12715     return Op;
12716   }
12717
12718   SDValue ValueToStore = Op.getOperand(0);
12719   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12720       !Subtarget->is64Bit())
12721     // Bitcasting to f64 here allows us to do a single 64-bit store from
12722     // an SSE register, avoiding the store forwarding penalty that would come
12723     // with two 32-bit stores.
12724     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
12725
12726   unsigned Size = SrcVT.getSizeInBits()/8;
12727   MachineFunction &MF = DAG.getMachineFunction();
12728   auto PtrVT = getPointerTy(MF.getDataLayout());
12729   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12730   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12731   SDValue Chain = DAG.getStore(
12732       DAG.getEntryNode(), dl, ValueToStore, StackSlot,
12733       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12734       false, 0);
12735   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12736 }
12737
12738 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12739                                      SDValue StackSlot,
12740                                      SelectionDAG &DAG) const {
12741   // Build the FILD
12742   SDLoc DL(Op);
12743   SDVTList Tys;
12744   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12745   if (useSSE)
12746     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12747   else
12748     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12749
12750   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12751
12752   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12753   MachineMemOperand *MMO;
12754   if (FI) {
12755     int SSFI = FI->getIndex();
12756     MMO = DAG.getMachineFunction().getMachineMemOperand(
12757         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12758         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12759   } else {
12760     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12761     StackSlot = StackSlot.getOperand(1);
12762   }
12763   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12764   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12765                                            X86ISD::FILD, DL,
12766                                            Tys, Ops, SrcVT, MMO);
12767
12768   if (useSSE) {
12769     Chain = Result.getValue(1);
12770     SDValue InFlag = Result.getValue(2);
12771
12772     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12773     // shouldn't be necessary except that RFP cannot be live across
12774     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12775     MachineFunction &MF = DAG.getMachineFunction();
12776     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12777     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12778     auto PtrVT = getPointerTy(MF.getDataLayout());
12779     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12780     Tys = DAG.getVTList(MVT::Other);
12781     SDValue Ops[] = {
12782       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12783     };
12784     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12785         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12786         MachineMemOperand::MOStore, SSFISize, SSFISize);
12787
12788     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12789                                     Ops, Op.getValueType(), MMO);
12790     Result = DAG.getLoad(
12791         Op.getValueType(), DL, Chain, StackSlot,
12792         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12793         false, false, false, 0);
12794   }
12795
12796   return Result;
12797 }
12798
12799 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12800 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12801                                                SelectionDAG &DAG) const {
12802   // This algorithm is not obvious. Here it is what we're trying to output:
12803   /*
12804      movq       %rax,  %xmm0
12805      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12806      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12807      #ifdef __SSE3__
12808        haddpd   %xmm0, %xmm0
12809      #else
12810        pshufd   $0x4e, %xmm0, %xmm1
12811        addpd    %xmm1, %xmm0
12812      #endif
12813   */
12814
12815   SDLoc dl(Op);
12816   LLVMContext *Context = DAG.getContext();
12817
12818   // Build some magic constants.
12819   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12820   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12821   auto PtrVT = getPointerTy(DAG.getDataLayout());
12822   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12823
12824   SmallVector<Constant*,2> CV1;
12825   CV1.push_back(
12826     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12827                                       APInt(64, 0x4330000000000000ULL))));
12828   CV1.push_back(
12829     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12830                                       APInt(64, 0x4530000000000000ULL))));
12831   Constant *C1 = ConstantVector::get(CV1);
12832   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12833
12834   // Load the 64-bit value into an XMM register.
12835   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12836                             Op.getOperand(0));
12837   SDValue CLod0 =
12838       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12839                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12840                   false, false, false, 16);
12841   SDValue Unpck1 =
12842       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12843
12844   SDValue CLod1 =
12845       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12846                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12847                   false, false, false, 16);
12848   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12849   // TODO: Are there any fast-math-flags to propagate here?
12850   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12851   SDValue Result;
12852
12853   if (Subtarget->hasSSE3()) {
12854     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12855     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12856   } else {
12857     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12858     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12859                                            S2F, 0x4E, DAG);
12860     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12861                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12862   }
12863
12864   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12865                      DAG.getIntPtrConstant(0, dl));
12866 }
12867
12868 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12869 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12870                                                SelectionDAG &DAG) const {
12871   SDLoc dl(Op);
12872   // FP constant to bias correct the final result.
12873   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12874                                    MVT::f64);
12875
12876   // Load the 32-bit value into an XMM register.
12877   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12878                              Op.getOperand(0));
12879
12880   // Zero out the upper parts of the register.
12881   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12882
12883   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12884                      DAG.getBitcast(MVT::v2f64, Load),
12885                      DAG.getIntPtrConstant(0, dl));
12886
12887   // Or the load with the bias.
12888   SDValue Or = DAG.getNode(
12889       ISD::OR, dl, MVT::v2i64,
12890       DAG.getBitcast(MVT::v2i64,
12891                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12892       DAG.getBitcast(MVT::v2i64,
12893                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12894   Or =
12895       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12896                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12897
12898   // Subtract the bias.
12899   // TODO: Are there any fast-math-flags to propagate here?
12900   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12901
12902   // Handle final rounding.
12903   MVT DestVT = Op.getSimpleValueType();
12904
12905   if (DestVT.bitsLT(MVT::f64))
12906     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12907                        DAG.getIntPtrConstant(0, dl));
12908   if (DestVT.bitsGT(MVT::f64))
12909     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12910
12911   // Handle final rounding.
12912   return Sub;
12913 }
12914
12915 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12916                                      const X86Subtarget &Subtarget) {
12917   // The algorithm is the following:
12918   // #ifdef __SSE4_1__
12919   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12920   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12921   //                                 (uint4) 0x53000000, 0xaa);
12922   // #else
12923   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12924   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12925   // #endif
12926   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12927   //     return (float4) lo + fhi;
12928
12929   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12930   // reassociate the two FADDs, and if we do that, the algorithm fails
12931   // spectacularly (PR24512).
12932   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12933   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12934   // there's also the MachineCombiner reassociations happening on Machine IR.
12935   if (DAG.getTarget().Options.UnsafeFPMath)
12936     return SDValue();
12937
12938   SDLoc DL(Op);
12939   SDValue V = Op->getOperand(0);
12940   MVT VecIntVT = V.getSimpleValueType();
12941   bool Is128 = VecIntVT == MVT::v4i32;
12942   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12943   // If we convert to something else than the supported type, e.g., to v4f64,
12944   // abort early.
12945   if (VecFloatVT != Op->getSimpleValueType(0))
12946     return SDValue();
12947
12948   unsigned NumElts = VecIntVT.getVectorNumElements();
12949   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12950          "Unsupported custom type");
12951   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12952
12953   // In the #idef/#else code, we have in common:
12954   // - The vector of constants:
12955   // -- 0x4b000000
12956   // -- 0x53000000
12957   // - A shift:
12958   // -- v >> 16
12959
12960   // Create the splat vector for 0x4b000000.
12961   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12962   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12963                            CstLow, CstLow, CstLow, CstLow};
12964   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12965                                   makeArrayRef(&CstLowArray[0], NumElts));
12966   // Create the splat vector for 0x53000000.
12967   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12968   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12969                             CstHigh, CstHigh, CstHigh, CstHigh};
12970   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12971                                    makeArrayRef(&CstHighArray[0], NumElts));
12972
12973   // Create the right shift.
12974   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12975   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12976                              CstShift, CstShift, CstShift, CstShift};
12977   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12978                                     makeArrayRef(&CstShiftArray[0], NumElts));
12979   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12980
12981   SDValue Low, High;
12982   if (Subtarget.hasSSE41()) {
12983     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12984     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12985     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12986     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12987     // Low will be bitcasted right away, so do not bother bitcasting back to its
12988     // original type.
12989     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12990                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12991     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12992     //                                 (uint4) 0x53000000, 0xaa);
12993     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12994     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12995     // High will be bitcasted right away, so do not bother bitcasting back to
12996     // its original type.
12997     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12998                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12999   } else {
13000     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
13001     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
13002                                      CstMask, CstMask, CstMask);
13003     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13004     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
13005     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
13006
13007     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13008     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
13009   }
13010
13011   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
13012   SDValue CstFAdd = DAG.getConstantFP(
13013       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
13014   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
13015                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
13016   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
13017                                    makeArrayRef(&CstFAddArray[0], NumElts));
13018
13019   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13020   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
13021   // TODO: Are there any fast-math-flags to propagate here?
13022   SDValue FHigh =
13023       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
13024   //     return (float4) lo + fhi;
13025   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
13026   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
13027 }
13028
13029 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13030                                                SelectionDAG &DAG) const {
13031   SDValue N0 = Op.getOperand(0);
13032   MVT SVT = N0.getSimpleValueType();
13033   SDLoc dl(Op);
13034
13035   switch (SVT.SimpleTy) {
13036   default:
13037     llvm_unreachable("Custom UINT_TO_FP is not supported!");
13038   case MVT::v4i8:
13039   case MVT::v4i16:
13040   case MVT::v8i8:
13041   case MVT::v8i16: {
13042     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13043     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13044                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13045   }
13046   case MVT::v4i32:
13047   case MVT::v8i32:
13048     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13049   case MVT::v16i8:
13050   case MVT::v16i16:
13051     assert(Subtarget->hasAVX512());
13052     return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
13053                        DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
13054   }
13055 }
13056
13057 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13058                                            SelectionDAG &DAG) const {
13059   SDValue N0 = Op.getOperand(0);
13060   SDLoc dl(Op);
13061   auto PtrVT = getPointerTy(DAG.getDataLayout());
13062
13063   if (Op.getSimpleValueType().isVector())
13064     return lowerUINT_TO_FP_vec(Op, DAG);
13065
13066   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13067   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13068   // the optimization here.
13069   if (DAG.SignBitIsZero(N0))
13070     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13071
13072   MVT SrcVT = N0.getSimpleValueType();
13073   MVT DstVT = Op.getSimpleValueType();
13074
13075   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
13076       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
13077     // Conversions from unsigned i32 to f32/f64 are legal,
13078     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
13079     return Op;
13080   }
13081
13082   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13083     return LowerUINT_TO_FP_i64(Op, DAG);
13084   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13085     return LowerUINT_TO_FP_i32(Op, DAG);
13086   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13087     return SDValue();
13088
13089   // Make a 64-bit buffer, and use it to build an FILD.
13090   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13091   if (SrcVT == MVT::i32) {
13092     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
13093     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
13094     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13095                                   StackSlot, MachinePointerInfo(),
13096                                   false, false, 0);
13097     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
13098                                   OffsetSlot, MachinePointerInfo(),
13099                                   false, false, 0);
13100     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13101     return Fild;
13102   }
13103
13104   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13105   SDValue ValueToStore = Op.getOperand(0);
13106   if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget->is64Bit())
13107     // Bitcasting to f64 here allows us to do a single 64-bit store from
13108     // an SSE register, avoiding the store forwarding penalty that would come
13109     // with two 32-bit stores.
13110     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
13111   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, ValueToStore,
13112                                StackSlot, MachinePointerInfo(),
13113                                false, false, 0);
13114   // For i64 source, we need to add the appropriate power of 2 if the input
13115   // was negative.  This is the same as the optimization in
13116   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13117   // we must be careful to do the computation in x87 extended precision, not
13118   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13119   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13120   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13121       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13122       MachineMemOperand::MOLoad, 8, 8);
13123
13124   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13125   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13126   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13127                                          MVT::i64, MMO);
13128
13129   APInt FF(32, 0x5F800000ULL);
13130
13131   // Check whether the sign bit is set.
13132   SDValue SignSet = DAG.getSetCC(
13133       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
13134       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
13135
13136   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13137   SDValue FudgePtr = DAG.getConstantPool(
13138       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
13139
13140   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13141   SDValue Zero = DAG.getIntPtrConstant(0, dl);
13142   SDValue Four = DAG.getIntPtrConstant(4, dl);
13143   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13144                                Zero, Four);
13145   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
13146
13147   // Load the value out, extending it from f32 to f80.
13148   // FIXME: Avoid the extend by constructing the right constant pool?
13149   SDValue Fudge = DAG.getExtLoad(
13150       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
13151       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
13152       false, false, false, 4);
13153   // Extend everything to 80 bits to force it to be done on x87.
13154   // TODO: Are there any fast-math-flags to propagate here?
13155   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13156   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
13157                      DAG.getIntPtrConstant(0, dl));
13158 }
13159
13160 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
13161 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
13162 // just return an <SDValue(), SDValue()> pair.
13163 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
13164 // to i16, i32 or i64, and we lower it to a legal sequence.
13165 // If lowered to the final integer result we return a <result, SDValue()> pair.
13166 // Otherwise we lower it to a sequence ending with a FIST, return a
13167 // <FIST, StackSlot> pair, and the caller is responsible for loading
13168 // the final integer result from StackSlot.
13169 std::pair<SDValue,SDValue>
13170 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13171                                    bool IsSigned, bool IsReplace) const {
13172   SDLoc DL(Op);
13173
13174   EVT DstTy = Op.getValueType();
13175   EVT TheVT = Op.getOperand(0).getValueType();
13176   auto PtrVT = getPointerTy(DAG.getDataLayout());
13177
13178   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
13179     // f16 must be promoted before using the lowering in this routine.
13180     // fp128 does not use this lowering.
13181     return std::make_pair(SDValue(), SDValue());
13182   }
13183
13184   // If using FIST to compute an unsigned i64, we'll need some fixup
13185   // to handle values above the maximum signed i64.  A FIST is always
13186   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13187   bool UnsignedFixup = !IsSigned &&
13188                        DstTy == MVT::i64 &&
13189                        (!Subtarget->is64Bit() ||
13190                         !isScalarFPTypeInSSEReg(TheVT));
13191
13192   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
13193     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13194     // The low 32 bits of the fist result will have the correct uint32 result.
13195     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13196     DstTy = MVT::i64;
13197   }
13198
13199   assert(DstTy.getSimpleVT() <= MVT::i64 &&
13200          DstTy.getSimpleVT() >= MVT::i16 &&
13201          "Unknown FP_TO_INT to lower!");
13202
13203   // These are really Legal.
13204   if (DstTy == MVT::i32 &&
13205       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13206     return std::make_pair(SDValue(), SDValue());
13207   if (Subtarget->is64Bit() &&
13208       DstTy == MVT::i64 &&
13209       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13210     return std::make_pair(SDValue(), SDValue());
13211
13212   // We lower FP->int64 into FISTP64 followed by a load from a temporary
13213   // stack slot.
13214   MachineFunction &MF = DAG.getMachineFunction();
13215   unsigned MemSize = DstTy.getSizeInBits()/8;
13216   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13217   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13218
13219   unsigned Opc;
13220   switch (DstTy.getSimpleVT().SimpleTy) {
13221   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13222   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13223   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13224   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13225   }
13226
13227   SDValue Chain = DAG.getEntryNode();
13228   SDValue Value = Op.getOperand(0);
13229   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13230
13231   if (UnsignedFixup) {
13232     //
13233     // Conversion to unsigned i64 is implemented with a select,
13234     // depending on whether the source value fits in the range
13235     // of a signed i64.  Let Thresh be the FP equivalent of
13236     // 0x8000000000000000ULL.
13237     //
13238     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13239     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
13240     //  Fist-to-mem64 FistSrc
13241     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13242     //  to XOR'ing the high 32 bits with Adjust.
13243     //
13244     // Being a power of 2, Thresh is exactly representable in all FP formats.
13245     // For X87 we'd like to use the smallest FP type for this constant, but
13246     // for DAG type consistency we have to match the FP operand type.
13247
13248     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13249     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13250     bool LosesInfo = false;
13251     if (TheVT == MVT::f64)
13252       // The rounding mode is irrelevant as the conversion should be exact.
13253       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13254                               &LosesInfo);
13255     else if (TheVT == MVT::f80)
13256       Status = Thresh.convert(APFloat::x87DoubleExtended,
13257                               APFloat::rmNearestTiesToEven, &LosesInfo);
13258
13259     assert(Status == APFloat::opOK && !LosesInfo &&
13260            "FP conversion should have been exact");
13261
13262     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13263
13264     SDValue Cmp = DAG.getSetCC(DL,
13265                                getSetCCResultType(DAG.getDataLayout(),
13266                                                   *DAG.getContext(), TheVT),
13267                                Value, ThreshVal, ISD::SETLT);
13268     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13269                            DAG.getConstant(0, DL, MVT::i32),
13270                            DAG.getConstant(0x80000000, DL, MVT::i32));
13271     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13272     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13273                                               *DAG.getContext(), TheVT),
13274                        Value, ThreshVal, ISD::SETLT);
13275     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13276   }
13277
13278   // FIXME This causes a redundant load/store if the SSE-class value is already
13279   // in memory, such as if it is on the callstack.
13280   if (isScalarFPTypeInSSEReg(TheVT)) {
13281     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13282     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13283                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
13284                          false, 0);
13285     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13286     SDValue Ops[] = {
13287       Chain, StackSlot, DAG.getValueType(TheVT)
13288     };
13289
13290     MachineMemOperand *MMO =
13291         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13292                                 MachineMemOperand::MOLoad, MemSize, MemSize);
13293     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13294     Chain = Value.getValue(1);
13295     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13296     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13297   }
13298
13299   MachineMemOperand *MMO =
13300       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13301                               MachineMemOperand::MOStore, MemSize, MemSize);
13302
13303   if (UnsignedFixup) {
13304
13305     // Insert the FIST, load its result as two i32's,
13306     // and XOR the high i32 with Adjust.
13307
13308     SDValue FistOps[] = { Chain, Value, StackSlot };
13309     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13310                                            FistOps, DstTy, MMO);
13311
13312     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13313                                 MachinePointerInfo(),
13314                                 false, false, false, 0);
13315     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13316                                    DAG.getConstant(4, DL, PtrVT));
13317
13318     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13319                                  MachinePointerInfo(),
13320                                  false, false, false, 0);
13321     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13322
13323     if (Subtarget->is64Bit()) {
13324       // Join High32 and Low32 into a 64-bit result.
13325       // (High32 << 32) | Low32
13326       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13327       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13328       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13329                            DAG.getConstant(32, DL, MVT::i8));
13330       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13331       return std::make_pair(Result, SDValue());
13332     }
13333
13334     SDValue ResultOps[] = { Low32, High32 };
13335
13336     SDValue pair = IsReplace
13337       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13338       : DAG.getMergeValues(ResultOps, DL);
13339     return std::make_pair(pair, SDValue());
13340   } else {
13341     // Build the FP_TO_INT*_IN_MEM
13342     SDValue Ops[] = { Chain, Value, StackSlot };
13343     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13344                                            Ops, DstTy, MMO);
13345     return std::make_pair(FIST, StackSlot);
13346   }
13347 }
13348
13349 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13350                               const X86Subtarget *Subtarget) {
13351   MVT VT = Op->getSimpleValueType(0);
13352   SDValue In = Op->getOperand(0);
13353   MVT InVT = In.getSimpleValueType();
13354   SDLoc dl(Op);
13355
13356   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13357     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13358
13359   // Optimize vectors in AVX mode:
13360   //
13361   //   v8i16 -> v8i32
13362   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13363   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13364   //   Concat upper and lower parts.
13365   //
13366   //   v4i32 -> v4i64
13367   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13368   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13369   //   Concat upper and lower parts.
13370   //
13371
13372   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13373       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13374       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13375     return SDValue();
13376
13377   if (Subtarget->hasInt256())
13378     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13379
13380   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13381   SDValue Undef = DAG.getUNDEF(InVT);
13382   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13383   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13384   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13385
13386   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13387                              VT.getVectorNumElements()/2);
13388
13389   OpLo = DAG.getBitcast(HVT, OpLo);
13390   OpHi = DAG.getBitcast(HVT, OpHi);
13391
13392   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13393 }
13394
13395 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13396                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13397   MVT VT = Op->getSimpleValueType(0);
13398   SDValue In = Op->getOperand(0);
13399   MVT InVT = In.getSimpleValueType();
13400   SDLoc DL(Op);
13401   unsigned int NumElts = VT.getVectorNumElements();
13402   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13403     return SDValue();
13404
13405   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13406     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13407
13408   assert(InVT.getVectorElementType() == MVT::i1);
13409   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13410   SDValue One =
13411    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13412   SDValue Zero =
13413    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13414
13415   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13416   if (VT.is512BitVector())
13417     return V;
13418   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13419 }
13420
13421 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13422                                SelectionDAG &DAG) {
13423   if (Subtarget->hasFp256())
13424     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13425       return Res;
13426
13427   return SDValue();
13428 }
13429
13430 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13431                                 SelectionDAG &DAG) {
13432   SDLoc DL(Op);
13433   MVT VT = Op.getSimpleValueType();
13434   SDValue In = Op.getOperand(0);
13435   MVT SVT = In.getSimpleValueType();
13436
13437   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13438     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13439
13440   if (Subtarget->hasFp256())
13441     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13442       return Res;
13443
13444   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13445          VT.getVectorNumElements() != SVT.getVectorNumElements());
13446   return SDValue();
13447 }
13448
13449 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
13450                                   const X86Subtarget *Subtarget) {
13451
13452   SDLoc DL(Op);
13453   MVT VT = Op.getSimpleValueType();
13454   SDValue In = Op.getOperand(0);
13455   MVT InVT = In.getSimpleValueType();
13456
13457   assert(VT.getVectorElementType() == MVT::i1 && "Unexected vector type.");
13458
13459   // Shift LSB to MSB and use VPMOVB2M - SKX.
13460   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
13461   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13462          Subtarget->hasBWI()) ||     // legal, will go to VPMOVB2M, VPMOVW2M
13463       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13464              InVT.getScalarSizeInBits() <= 16 && Subtarget->hasBWI() &&
13465              Subtarget->hasVLX())) { // legal, will go to VPMOVB2M, VPMOVW2M
13466     // Shift packed bytes not supported natively, bitcast to dword
13467     MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
13468     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, ExtVT,
13469                                      DAG.getBitcast(ExtVT, In),
13470                                      DAG.getConstant(ShiftInx, DL, ExtVT));
13471     ShiftNode = DAG.getBitcast(InVT, ShiftNode);
13472     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13473   }
13474   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13475          Subtarget->hasDQI()) ||  // legal, will go to VPMOVD2M, VPMOVQ2M
13476       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13477          InVT.getScalarSizeInBits() >= 32 && Subtarget->hasDQI() &&
13478          Subtarget->hasVLX())) {  // legal, will go to VPMOVD2M, VPMOVQ2M
13479
13480     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13481                                      DAG.getConstant(ShiftInx, DL, InVT));
13482     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13483   }
13484
13485   // Shift LSB to MSB, extend if necessary and use TESTM.
13486   unsigned NumElts = InVT.getVectorNumElements();
13487   if (InVT.getSizeInBits() < 512 &&
13488       (InVT.getScalarType() == MVT::i8 || InVT.getScalarType() == MVT::i16 ||
13489        !Subtarget->hasVLX())) {
13490     assert((NumElts == 8 || NumElts == 16) && "Unexected vector type.");
13491
13492     // TESTD/Q should be used (if BW supported we use CVT2MASK above),
13493     // so vector should be extended to packed dword/qword.
13494     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(512/NumElts), NumElts);
13495     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13496     InVT = ExtVT;
13497     ShiftInx = InVT.getScalarSizeInBits() - 1;
13498   }
13499
13500   SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13501                                    DAG.getConstant(ShiftInx, DL, InVT));
13502   return DAG.getNode(X86ISD::TESTM, DL, VT, ShiftNode, ShiftNode);
13503 }
13504
13505 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13506   SDLoc DL(Op);
13507   MVT VT = Op.getSimpleValueType();
13508   SDValue In = Op.getOperand(0);
13509   MVT InVT = In.getSimpleValueType();
13510
13511   if (VT == MVT::i1) {
13512     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13513            "Invalid scalar TRUNCATE operation");
13514     if (InVT.getSizeInBits() >= 32)
13515       return SDValue();
13516     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13517     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13518   }
13519   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13520          "Invalid TRUNCATE operation");
13521
13522   if (VT.getVectorElementType() == MVT::i1)
13523     return LowerTruncateVecI1(Op, DAG, Subtarget);
13524
13525   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13526   if (Subtarget->hasAVX512()) {
13527     // word to byte only under BWI
13528     if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13529       return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13530                          DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13531     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13532   }
13533   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13534     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13535     if (Subtarget->hasInt256()) {
13536       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13537       In = DAG.getBitcast(MVT::v8i32, In);
13538       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13539                                 ShufMask);
13540       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13541                          DAG.getIntPtrConstant(0, DL));
13542     }
13543
13544     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13545                                DAG.getIntPtrConstant(0, DL));
13546     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13547                                DAG.getIntPtrConstant(2, DL));
13548     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13549     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13550     static const int ShufMask[] = {0, 2, 4, 6};
13551     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13552   }
13553
13554   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13555     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13556     if (Subtarget->hasInt256()) {
13557       In = DAG.getBitcast(MVT::v32i8, In);
13558
13559       SmallVector<SDValue,32> pshufbMask;
13560       for (unsigned i = 0; i < 2; ++i) {
13561         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13562         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13563         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13564         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13565         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13566         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13567         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13568         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13569         for (unsigned j = 0; j < 8; ++j)
13570           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13571       }
13572       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13573       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13574       In = DAG.getBitcast(MVT::v4i64, In);
13575
13576       static const int ShufMask[] = {0,  2,  -1,  -1};
13577       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13578                                 &ShufMask[0]);
13579       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13580                        DAG.getIntPtrConstant(0, DL));
13581       return DAG.getBitcast(VT, In);
13582     }
13583
13584     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13585                                DAG.getIntPtrConstant(0, DL));
13586
13587     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13588                                DAG.getIntPtrConstant(4, DL));
13589
13590     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13591     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13592
13593     // The PSHUFB mask:
13594     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13595                                    -1, -1, -1, -1, -1, -1, -1, -1};
13596
13597     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13598     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13599     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13600
13601     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13602     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13603
13604     // The MOVLHPS Mask:
13605     static const int ShufMask2[] = {0, 1, 4, 5};
13606     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13607     return DAG.getBitcast(MVT::v8i16, res);
13608   }
13609
13610   // Handle truncation of V256 to V128 using shuffles.
13611   if (!VT.is128BitVector() || !InVT.is256BitVector())
13612     return SDValue();
13613
13614   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13615
13616   unsigned NumElems = VT.getVectorNumElements();
13617   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13618
13619   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13620   // Prepare truncation shuffle mask
13621   for (unsigned i = 0; i != NumElems; ++i)
13622     MaskVec[i] = i * 2;
13623   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13624                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13625   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13626                      DAG.getIntPtrConstant(0, DL));
13627 }
13628
13629 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13630                                            SelectionDAG &DAG) const {
13631   assert(!Op.getSimpleValueType().isVector());
13632
13633   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13634     /*IsSigned=*/ true, /*IsReplace=*/ false);
13635   SDValue FIST = Vals.first, StackSlot = Vals.second;
13636   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13637   if (!FIST.getNode())
13638     return Op;
13639
13640   if (StackSlot.getNode())
13641     // Load the result.
13642     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13643                        FIST, StackSlot, MachinePointerInfo(),
13644                        false, false, false, 0);
13645
13646   // The node is the result.
13647   return FIST;
13648 }
13649
13650 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13651                                            SelectionDAG &DAG) const {
13652   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13653     /*IsSigned=*/ false, /*IsReplace=*/ false);
13654   SDValue FIST = Vals.first, StackSlot = Vals.second;
13655   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13656   if (!FIST.getNode())
13657     return Op;
13658
13659   if (StackSlot.getNode())
13660     // Load the result.
13661     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13662                        FIST, StackSlot, MachinePointerInfo(),
13663                        false, false, false, 0);
13664
13665   // The node is the result.
13666   return FIST;
13667 }
13668
13669 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13670   SDLoc DL(Op);
13671   MVT VT = Op.getSimpleValueType();
13672   SDValue In = Op.getOperand(0);
13673   MVT SVT = In.getSimpleValueType();
13674
13675   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13676
13677   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13678                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13679                                  In, DAG.getUNDEF(SVT)));
13680 }
13681
13682 /// The only differences between FABS and FNEG are the mask and the logic op.
13683 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13684 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13685   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13686          "Wrong opcode for lowering FABS or FNEG.");
13687
13688   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13689
13690   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13691   // into an FNABS. We'll lower the FABS after that if it is still in use.
13692   if (IsFABS)
13693     for (SDNode *User : Op->uses())
13694       if (User->getOpcode() == ISD::FNEG)
13695         return Op;
13696
13697   SDLoc dl(Op);
13698   MVT VT = Op.getSimpleValueType();
13699
13700   bool IsF128 = (VT == MVT::f128);
13701
13702   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13703   // decide if we should generate a 16-byte constant mask when we only need 4 or
13704   // 8 bytes for the scalar case.
13705
13706   MVT LogicVT;
13707   MVT EltVT;
13708   unsigned NumElts;
13709
13710   if (VT.isVector()) {
13711     LogicVT = VT;
13712     EltVT = VT.getVectorElementType();
13713     NumElts = VT.getVectorNumElements();
13714   } else if (IsF128) {
13715     // SSE instructions are used for optimized f128 logical operations.
13716     LogicVT = MVT::f128;
13717     EltVT = VT;
13718     NumElts = 1;
13719   } else {
13720     // There are no scalar bitwise logical SSE/AVX instructions, so we
13721     // generate a 16-byte vector constant and logic op even for the scalar case.
13722     // Using a 16-byte mask allows folding the load of the mask with
13723     // the logic op, so it can save (~4 bytes) on code size.
13724     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13725     EltVT = VT;
13726     NumElts = (VT == MVT::f64) ? 2 : 4;
13727   }
13728
13729   unsigned EltBits = EltVT.getSizeInBits();
13730   LLVMContext *Context = DAG.getContext();
13731   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13732   APInt MaskElt =
13733     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13734   Constant *C = ConstantInt::get(*Context, MaskElt);
13735   C = ConstantVector::getSplat(NumElts, C);
13736   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13737   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13738   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13739   SDValue Mask =
13740       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13741                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13742                   false, false, false, Alignment);
13743
13744   SDValue Op0 = Op.getOperand(0);
13745   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13746   unsigned LogicOp =
13747     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13748   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13749
13750   if (VT.isVector() || IsF128)
13751     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13752
13753   // For the scalar case extend to a 128-bit vector, perform the logic op,
13754   // and extract the scalar result back out.
13755   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13756   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13757   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13758                      DAG.getIntPtrConstant(0, dl));
13759 }
13760
13761 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13763   LLVMContext *Context = DAG.getContext();
13764   SDValue Op0 = Op.getOperand(0);
13765   SDValue Op1 = Op.getOperand(1);
13766   SDLoc dl(Op);
13767   MVT VT = Op.getSimpleValueType();
13768   MVT SrcVT = Op1.getSimpleValueType();
13769   bool IsF128 = (VT == MVT::f128);
13770
13771   // If second operand is smaller, extend it first.
13772   if (SrcVT.bitsLT(VT)) {
13773     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13774     SrcVT = VT;
13775   }
13776   // And if it is bigger, shrink it first.
13777   if (SrcVT.bitsGT(VT)) {
13778     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13779     SrcVT = VT;
13780   }
13781
13782   // At this point the operands and the result should have the same
13783   // type, and that won't be f80 since that is not custom lowered.
13784   assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13785          "Unexpected type in LowerFCOPYSIGN");
13786
13787   const fltSemantics &Sem =
13788       VT == MVT::f64 ? APFloat::IEEEdouble :
13789           (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13790   const unsigned SizeInBits = VT.getSizeInBits();
13791
13792   SmallVector<Constant *, 4> CV(
13793       VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13794       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13795
13796   // First, clear all bits but the sign bit from the second operand (sign).
13797   CV[0] = ConstantFP::get(*Context,
13798                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13799   Constant *C = ConstantVector::get(CV);
13800   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13801   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13802
13803   // Perform all logic operations as 16-byte vectors because there are no
13804   // scalar FP logic instructions in SSE. This allows load folding of the
13805   // constants into the logic instructions.
13806   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13807   SDValue Mask1 =
13808       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13809                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13810                   false, false, false, 16);
13811   if (!IsF128)
13812     Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13813   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13814
13815   // Next, clear the sign bit from the first operand (magnitude).
13816   // If it's a constant, we can clear it here.
13817   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13818     APFloat APF = Op0CN->getValueAPF();
13819     // If the magnitude is a positive zero, the sign bit alone is enough.
13820     if (APF.isPosZero())
13821       return IsF128 ? SignBit :
13822           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13823                       DAG.getIntPtrConstant(0, dl));
13824     APF.clearSign();
13825     CV[0] = ConstantFP::get(*Context, APF);
13826   } else {
13827     CV[0] = ConstantFP::get(
13828         *Context,
13829         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13830   }
13831   C = ConstantVector::get(CV);
13832   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13833   SDValue Val =
13834       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13835                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13836                   false, false, false, 16);
13837   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13838   if (!isa<ConstantFPSDNode>(Op0)) {
13839     if (!IsF128)
13840       Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13841     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13842   }
13843   // OR the magnitude value with the sign bit.
13844   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13845   return IsF128 ? Val :
13846       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13847                   DAG.getIntPtrConstant(0, dl));
13848 }
13849
13850 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13851   SDValue N0 = Op.getOperand(0);
13852   SDLoc dl(Op);
13853   MVT VT = Op.getSimpleValueType();
13854
13855   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13856   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13857                                   DAG.getConstant(1, dl, VT));
13858   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13859 }
13860
13861 // Check whether an OR'd tree is PTEST-able.
13862 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13863                                       SelectionDAG &DAG) {
13864   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13865
13866   if (!Subtarget->hasSSE41())
13867     return SDValue();
13868
13869   if (!Op->hasOneUse())
13870     return SDValue();
13871
13872   SDNode *N = Op.getNode();
13873   SDLoc DL(N);
13874
13875   SmallVector<SDValue, 8> Opnds;
13876   DenseMap<SDValue, unsigned> VecInMap;
13877   SmallVector<SDValue, 8> VecIns;
13878   EVT VT = MVT::Other;
13879
13880   // Recognize a special case where a vector is casted into wide integer to
13881   // test all 0s.
13882   Opnds.push_back(N->getOperand(0));
13883   Opnds.push_back(N->getOperand(1));
13884
13885   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13886     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13887     // BFS traverse all OR'd operands.
13888     if (I->getOpcode() == ISD::OR) {
13889       Opnds.push_back(I->getOperand(0));
13890       Opnds.push_back(I->getOperand(1));
13891       // Re-evaluate the number of nodes to be traversed.
13892       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13893       continue;
13894     }
13895
13896     // Quit if a non-EXTRACT_VECTOR_ELT
13897     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13898       return SDValue();
13899
13900     // Quit if without a constant index.
13901     SDValue Idx = I->getOperand(1);
13902     if (!isa<ConstantSDNode>(Idx))
13903       return SDValue();
13904
13905     SDValue ExtractedFromVec = I->getOperand(0);
13906     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13907     if (M == VecInMap.end()) {
13908       VT = ExtractedFromVec.getValueType();
13909       // Quit if not 128/256-bit vector.
13910       if (!VT.is128BitVector() && !VT.is256BitVector())
13911         return SDValue();
13912       // Quit if not the same type.
13913       if (VecInMap.begin() != VecInMap.end() &&
13914           VT != VecInMap.begin()->first.getValueType())
13915         return SDValue();
13916       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13917       VecIns.push_back(ExtractedFromVec);
13918     }
13919     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13920   }
13921
13922   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13923          "Not extracted from 128-/256-bit vector.");
13924
13925   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13926
13927   for (DenseMap<SDValue, unsigned>::const_iterator
13928         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13929     // Quit if not all elements are used.
13930     if (I->second != FullMask)
13931       return SDValue();
13932   }
13933
13934   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13935
13936   // Cast all vectors into TestVT for PTEST.
13937   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13938     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13939
13940   // If more than one full vectors are evaluated, OR them first before PTEST.
13941   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13942     // Each iteration will OR 2 nodes and append the result until there is only
13943     // 1 node left, i.e. the final OR'd value of all vectors.
13944     SDValue LHS = VecIns[Slot];
13945     SDValue RHS = VecIns[Slot + 1];
13946     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13947   }
13948
13949   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13950                      VecIns.back(), VecIns.back());
13951 }
13952
13953 /// \brief return true if \c Op has a use that doesn't just read flags.
13954 static bool hasNonFlagsUse(SDValue Op) {
13955   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13956        ++UI) {
13957     SDNode *User = *UI;
13958     unsigned UOpNo = UI.getOperandNo();
13959     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13960       // Look pass truncate.
13961       UOpNo = User->use_begin().getOperandNo();
13962       User = *User->use_begin();
13963     }
13964
13965     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13966         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13967       return true;
13968   }
13969   return false;
13970 }
13971
13972 /// Emit nodes that will be selected as "test Op0,Op0", or something
13973 /// equivalent.
13974 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13975                                     SelectionDAG &DAG) const {
13976   if (Op.getValueType() == MVT::i1) {
13977     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13978     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13979                        DAG.getConstant(0, dl, MVT::i8));
13980   }
13981   // CF and OF aren't always set the way we want. Determine which
13982   // of these we need.
13983   bool NeedCF = false;
13984   bool NeedOF = false;
13985   switch (X86CC) {
13986   default: break;
13987   case X86::COND_A: case X86::COND_AE:
13988   case X86::COND_B: case X86::COND_BE:
13989     NeedCF = true;
13990     break;
13991   case X86::COND_G: case X86::COND_GE:
13992   case X86::COND_L: case X86::COND_LE:
13993   case X86::COND_O: case X86::COND_NO: {
13994     // Check if we really need to set the
13995     // Overflow flag. If NoSignedWrap is present
13996     // that is not actually needed.
13997     switch (Op->getOpcode()) {
13998     case ISD::ADD:
13999     case ISD::SUB:
14000     case ISD::MUL:
14001     case ISD::SHL: {
14002       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
14003       if (BinNode->Flags.hasNoSignedWrap())
14004         break;
14005     }
14006     default:
14007       NeedOF = true;
14008       break;
14009     }
14010     break;
14011   }
14012   }
14013   // See if we can use the EFLAGS value from the operand instead of
14014   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
14015   // we prove that the arithmetic won't overflow, we can't use OF or CF.
14016   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
14017     // Emit a CMP with 0, which is the TEST pattern.
14018     //if (Op.getValueType() == MVT::i1)
14019     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
14020     //                     DAG.getConstant(0, MVT::i1));
14021     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14022                        DAG.getConstant(0, dl, Op.getValueType()));
14023   }
14024   unsigned Opcode = 0;
14025   unsigned NumOperands = 0;
14026
14027   // Truncate operations may prevent the merge of the SETCC instruction
14028   // and the arithmetic instruction before it. Attempt to truncate the operands
14029   // of the arithmetic instruction and use a reduced bit-width instruction.
14030   bool NeedTruncation = false;
14031   SDValue ArithOp = Op;
14032   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14033     SDValue Arith = Op->getOperand(0);
14034     // Both the trunc and the arithmetic op need to have one user each.
14035     if (Arith->hasOneUse())
14036       switch (Arith.getOpcode()) {
14037         default: break;
14038         case ISD::ADD:
14039         case ISD::SUB:
14040         case ISD::AND:
14041         case ISD::OR:
14042         case ISD::XOR: {
14043           NeedTruncation = true;
14044           ArithOp = Arith;
14045         }
14046       }
14047   }
14048
14049   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14050   // which may be the result of a CAST.  We use the variable 'Op', which is the
14051   // non-casted variable when we check for possible users.
14052   switch (ArithOp.getOpcode()) {
14053   case ISD::ADD:
14054     // Due to an isel shortcoming, be conservative if this add is likely to be
14055     // selected as part of a load-modify-store instruction. When the root node
14056     // in a match is a store, isel doesn't know how to remap non-chain non-flag
14057     // uses of other nodes in the match, such as the ADD in this case. This
14058     // leads to the ADD being left around and reselected, with the result being
14059     // two adds in the output.  Alas, even if none our users are stores, that
14060     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
14061     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
14062     // climbing the DAG back to the root, and it doesn't seem to be worth the
14063     // effort.
14064     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14065          UE = Op.getNode()->use_end(); UI != UE; ++UI)
14066       if (UI->getOpcode() != ISD::CopyToReg &&
14067           UI->getOpcode() != ISD::SETCC &&
14068           UI->getOpcode() != ISD::STORE)
14069         goto default_case;
14070
14071     if (ConstantSDNode *C =
14072         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14073       // An add of one will be selected as an INC.
14074       if (C->isOne() && !Subtarget->slowIncDec()) {
14075         Opcode = X86ISD::INC;
14076         NumOperands = 1;
14077         break;
14078       }
14079
14080       // An add of negative one (subtract of one) will be selected as a DEC.
14081       if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
14082         Opcode = X86ISD::DEC;
14083         NumOperands = 1;
14084         break;
14085       }
14086     }
14087
14088     // Otherwise use a regular EFLAGS-setting add.
14089     Opcode = X86ISD::ADD;
14090     NumOperands = 2;
14091     break;
14092   case ISD::SHL:
14093   case ISD::SRL:
14094     // If we have a constant logical shift that's only used in a comparison
14095     // against zero turn it into an equivalent AND. This allows turning it into
14096     // a TEST instruction later.
14097     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14098         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14099       EVT VT = Op.getValueType();
14100       unsigned BitWidth = VT.getSizeInBits();
14101       unsigned ShAmt = Op->getConstantOperandVal(1);
14102       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14103         break;
14104       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14105                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14106                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14107       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14108         break;
14109       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14110                                 DAG.getConstant(Mask, dl, VT));
14111       DAG.ReplaceAllUsesWith(Op, New);
14112       Op = New;
14113     }
14114     break;
14115
14116   case ISD::AND:
14117     // If the primary and result isn't used, don't bother using X86ISD::AND,
14118     // because a TEST instruction will be better.
14119     if (!hasNonFlagsUse(Op))
14120       break;
14121     // FALL THROUGH
14122   case ISD::SUB:
14123   case ISD::OR:
14124   case ISD::XOR:
14125     // Due to the ISEL shortcoming noted above, be conservative if this op is
14126     // likely to be selected as part of a load-modify-store instruction.
14127     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14128            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14129       if (UI->getOpcode() == ISD::STORE)
14130         goto default_case;
14131
14132     // Otherwise use a regular EFLAGS-setting instruction.
14133     switch (ArithOp.getOpcode()) {
14134     default: llvm_unreachable("unexpected operator!");
14135     case ISD::SUB: Opcode = X86ISD::SUB; break;
14136     case ISD::XOR: Opcode = X86ISD::XOR; break;
14137     case ISD::AND: Opcode = X86ISD::AND; break;
14138     case ISD::OR: {
14139       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14140         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14141         if (EFLAGS.getNode())
14142           return EFLAGS;
14143       }
14144       Opcode = X86ISD::OR;
14145       break;
14146     }
14147     }
14148
14149     NumOperands = 2;
14150     break;
14151   case X86ISD::ADD:
14152   case X86ISD::SUB:
14153   case X86ISD::INC:
14154   case X86ISD::DEC:
14155   case X86ISD::OR:
14156   case X86ISD::XOR:
14157   case X86ISD::AND:
14158     return SDValue(Op.getNode(), 1);
14159   default:
14160   default_case:
14161     break;
14162   }
14163
14164   // If we found that truncation is beneficial, perform the truncation and
14165   // update 'Op'.
14166   if (NeedTruncation) {
14167     EVT VT = Op.getValueType();
14168     SDValue WideVal = Op->getOperand(0);
14169     EVT WideVT = WideVal.getValueType();
14170     unsigned ConvertedOp = 0;
14171     // Use a target machine opcode to prevent further DAGCombine
14172     // optimizations that may separate the arithmetic operations
14173     // from the setcc node.
14174     switch (WideVal.getOpcode()) {
14175       default: break;
14176       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14177       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14178       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14179       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14180       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14181     }
14182
14183     if (ConvertedOp) {
14184       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14185       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14186         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14187         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14188         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14189       }
14190     }
14191   }
14192
14193   if (Opcode == 0)
14194     // Emit a CMP with 0, which is the TEST pattern.
14195     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14196                        DAG.getConstant(0, dl, Op.getValueType()));
14197
14198   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14199   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
14200
14201   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14202   DAG.ReplaceAllUsesWith(Op, New);
14203   return SDValue(New.getNode(), 1);
14204 }
14205
14206 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14207 /// equivalent.
14208 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14209                                    SDLoc dl, SelectionDAG &DAG) const {
14210   if (isNullConstant(Op1))
14211     return EmitTest(Op0, X86CC, dl, DAG);
14212
14213   assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14214          "Unexpected comparison operation for MVT::i1 operands");
14215
14216   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14217        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14218     // Do the comparison at i32 if it's smaller, besides the Atom case.
14219     // This avoids subregister aliasing issues. Keep the smaller reference
14220     // if we're optimizing for size, however, as that'll allow better folding
14221     // of memory operations.
14222     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14223         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14224         !Subtarget->isAtom()) {
14225       unsigned ExtendOp =
14226           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14227       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14228       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14229     }
14230     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14231     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14232     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14233                               Op0, Op1);
14234     return SDValue(Sub.getNode(), 1);
14235   }
14236   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14237 }
14238
14239 /// Convert a comparison if required by the subtarget.
14240 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14241                                                  SelectionDAG &DAG) const {
14242   // If the subtarget does not support the FUCOMI instruction, floating-point
14243   // comparisons have to be converted.
14244   if (Subtarget->hasCMov() ||
14245       Cmp.getOpcode() != X86ISD::CMP ||
14246       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14247       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14248     return Cmp;
14249
14250   // The instruction selector will select an FUCOM instruction instead of
14251   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14252   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14253   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14254   SDLoc dl(Cmp);
14255   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14256   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14257   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14258                             DAG.getConstant(8, dl, MVT::i8));
14259   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14260
14261   // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14262   assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14263   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14264 }
14265
14266 /// The minimum architected relative accuracy is 2^-12. We need one
14267 /// Newton-Raphson step to have a good float result (24 bits of precision).
14268 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14269                                             DAGCombinerInfo &DCI,
14270                                             unsigned &RefinementSteps,
14271                                             bool &UseOneConstNR) const {
14272   EVT VT = Op.getValueType();
14273   const char *RecipOp;
14274
14275   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14276   // TODO: Add support for AVX512 (v16f32).
14277   // It is likely not profitable to do this for f64 because a double-precision
14278   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14279   // instructions: convert to single, rsqrtss, convert back to double, refine
14280   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14281   // along with FMA, this could be a throughput win.
14282   if (VT == MVT::f32 && Subtarget->hasSSE1())
14283     RecipOp = "sqrtf";
14284   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14285            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14286     RecipOp = "vec-sqrtf";
14287   else
14288     return SDValue();
14289
14290   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14291   if (!Recips.isEnabled(RecipOp))
14292     return SDValue();
14293
14294   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14295   UseOneConstNR = false;
14296   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14297 }
14298
14299 /// The minimum architected relative accuracy is 2^-12. We need one
14300 /// Newton-Raphson step to have a good float result (24 bits of precision).
14301 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14302                                             DAGCombinerInfo &DCI,
14303                                             unsigned &RefinementSteps) const {
14304   EVT VT = Op.getValueType();
14305   const char *RecipOp;
14306
14307   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14308   // TODO: Add support for AVX512 (v16f32).
14309   // It is likely not profitable to do this for f64 because a double-precision
14310   // reciprocal estimate with refinement on x86 prior to FMA requires
14311   // 15 instructions: convert to single, rcpss, convert back to double, refine
14312   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14313   // along with FMA, this could be a throughput win.
14314   if (VT == MVT::f32 && Subtarget->hasSSE1())
14315     RecipOp = "divf";
14316   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14317            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14318     RecipOp = "vec-divf";
14319   else
14320     return SDValue();
14321
14322   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14323   if (!Recips.isEnabled(RecipOp))
14324     return SDValue();
14325
14326   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14327   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14328 }
14329
14330 /// If we have at least two divisions that use the same divisor, convert to
14331 /// multplication by a reciprocal. This may need to be adjusted for a given
14332 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14333 /// This is because we still need one division to calculate the reciprocal and
14334 /// then we need two multiplies by that reciprocal as replacements for the
14335 /// original divisions.
14336 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14337   return 2;
14338 }
14339
14340 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14341 /// if it's possible.
14342 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14343                                      SDLoc dl, SelectionDAG &DAG) const {
14344   SDValue Op0 = And.getOperand(0);
14345   SDValue Op1 = And.getOperand(1);
14346   if (Op0.getOpcode() == ISD::TRUNCATE)
14347     Op0 = Op0.getOperand(0);
14348   if (Op1.getOpcode() == ISD::TRUNCATE)
14349     Op1 = Op1.getOperand(0);
14350
14351   SDValue LHS, RHS;
14352   if (Op1.getOpcode() == ISD::SHL)
14353     std::swap(Op0, Op1);
14354   if (Op0.getOpcode() == ISD::SHL) {
14355     if (isOneConstant(Op0.getOperand(0))) {
14356         // If we looked past a truncate, check that it's only truncating away
14357         // known zeros.
14358         unsigned BitWidth = Op0.getValueSizeInBits();
14359         unsigned AndBitWidth = And.getValueSizeInBits();
14360         if (BitWidth > AndBitWidth) {
14361           APInt Zeros, Ones;
14362           DAG.computeKnownBits(Op0, Zeros, Ones);
14363           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14364             return SDValue();
14365         }
14366         LHS = Op1;
14367         RHS = Op0.getOperand(1);
14368       }
14369   } else if (Op1.getOpcode() == ISD::Constant) {
14370     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14371     uint64_t AndRHSVal = AndRHS->getZExtValue();
14372     SDValue AndLHS = Op0;
14373
14374     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14375       LHS = AndLHS.getOperand(0);
14376       RHS = AndLHS.getOperand(1);
14377     }
14378
14379     // Use BT if the immediate can't be encoded in a TEST instruction.
14380     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14381       LHS = AndLHS;
14382       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14383     }
14384   }
14385
14386   if (LHS.getNode()) {
14387     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
14388     // instruction.  Since the shift amount is in-range-or-undefined, we know
14389     // that doing a bittest on the i32 value is ok.  We extend to i32 because
14390     // the encoding for the i16 version is larger than the i32 version.
14391     // Also promote i16 to i32 for performance / code size reason.
14392     if (LHS.getValueType() == MVT::i8 ||
14393         LHS.getValueType() == MVT::i16)
14394       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14395
14396     // If the operand types disagree, extend the shift amount to match.  Since
14397     // BT ignores high bits (like shifts) we can use anyextend.
14398     if (LHS.getValueType() != RHS.getValueType())
14399       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14400
14401     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14402     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14403     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14404                        DAG.getConstant(Cond, dl, MVT::i8), BT);
14405   }
14406
14407   return SDValue();
14408 }
14409
14410 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14411 /// mask CMPs.
14412 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14413                               SDValue &Op1) {
14414   unsigned SSECC;
14415   bool Swap = false;
14416
14417   // SSE Condition code mapping:
14418   //  0 - EQ
14419   //  1 - LT
14420   //  2 - LE
14421   //  3 - UNORD
14422   //  4 - NEQ
14423   //  5 - NLT
14424   //  6 - NLE
14425   //  7 - ORD
14426   switch (SetCCOpcode) {
14427   default: llvm_unreachable("Unexpected SETCC condition");
14428   case ISD::SETOEQ:
14429   case ISD::SETEQ:  SSECC = 0; break;
14430   case ISD::SETOGT:
14431   case ISD::SETGT:  Swap = true; // Fallthrough
14432   case ISD::SETLT:
14433   case ISD::SETOLT: SSECC = 1; break;
14434   case ISD::SETOGE:
14435   case ISD::SETGE:  Swap = true; // Fallthrough
14436   case ISD::SETLE:
14437   case ISD::SETOLE: SSECC = 2; break;
14438   case ISD::SETUO:  SSECC = 3; break;
14439   case ISD::SETUNE:
14440   case ISD::SETNE:  SSECC = 4; break;
14441   case ISD::SETULE: Swap = true; // Fallthrough
14442   case ISD::SETUGE: SSECC = 5; break;
14443   case ISD::SETULT: Swap = true; // Fallthrough
14444   case ISD::SETUGT: SSECC = 6; break;
14445   case ISD::SETO:   SSECC = 7; break;
14446   case ISD::SETUEQ:
14447   case ISD::SETONE: SSECC = 8; break;
14448   }
14449   if (Swap)
14450     std::swap(Op0, Op1);
14451
14452   return SSECC;
14453 }
14454
14455 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14456 // ones, and then concatenate the result back.
14457 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14458   MVT VT = Op.getSimpleValueType();
14459
14460   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14461          "Unsupported value type for operation");
14462
14463   unsigned NumElems = VT.getVectorNumElements();
14464   SDLoc dl(Op);
14465   SDValue CC = Op.getOperand(2);
14466
14467   // Extract the LHS vectors
14468   SDValue LHS = Op.getOperand(0);
14469   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14470   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14471
14472   // Extract the RHS vectors
14473   SDValue RHS = Op.getOperand(1);
14474   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14475   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14476
14477   // Issue the operation on the smaller types and concatenate the result back
14478   MVT EltVT = VT.getVectorElementType();
14479   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14480   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14481                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14482                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14483 }
14484
14485 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14486   SDValue Op0 = Op.getOperand(0);
14487   SDValue Op1 = Op.getOperand(1);
14488   SDValue CC = Op.getOperand(2);
14489   MVT VT = Op.getSimpleValueType();
14490   SDLoc dl(Op);
14491
14492   assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14493          "Unexpected type for boolean compare operation");
14494   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14495   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14496                                DAG.getConstant(-1, dl, VT));
14497   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14498                                DAG.getConstant(-1, dl, VT));
14499   switch (SetCCOpcode) {
14500   default: llvm_unreachable("Unexpected SETCC condition");
14501   case ISD::SETEQ:
14502     // (x == y) -> ~(x ^ y)
14503     return DAG.getNode(ISD::XOR, dl, VT,
14504                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14505                        DAG.getConstant(-1, dl, VT));
14506   case ISD::SETNE:
14507     // (x != y) -> (x ^ y)
14508     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14509   case ISD::SETUGT:
14510   case ISD::SETGT:
14511     // (x > y) -> (x & ~y)
14512     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14513   case ISD::SETULT:
14514   case ISD::SETLT:
14515     // (x < y) -> (~x & y)
14516     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14517   case ISD::SETULE:
14518   case ISD::SETLE:
14519     // (x <= y) -> (~x | y)
14520     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14521   case ISD::SETUGE:
14522   case ISD::SETGE:
14523     // (x >=y) -> (x | ~y)
14524     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14525   }
14526 }
14527
14528 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14529                                      const X86Subtarget *Subtarget) {
14530   SDValue Op0 = Op.getOperand(0);
14531   SDValue Op1 = Op.getOperand(1);
14532   SDValue CC = Op.getOperand(2);
14533   MVT VT = Op.getSimpleValueType();
14534   SDLoc dl(Op);
14535
14536   assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14537          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14538          "Cannot set masked compare for this operation");
14539
14540   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14541   unsigned  Opc = 0;
14542   bool Unsigned = false;
14543   bool Swap = false;
14544   unsigned SSECC;
14545   switch (SetCCOpcode) {
14546   default: llvm_unreachable("Unexpected SETCC condition");
14547   case ISD::SETNE:  SSECC = 4; break;
14548   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14549   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14550   case ISD::SETLT:  Swap = true; //fall-through
14551   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14552   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14553   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14554   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14555   case ISD::SETULE: Unsigned = true; //fall-through
14556   case ISD::SETLE:  SSECC = 2; break;
14557   }
14558
14559   if (Swap)
14560     std::swap(Op0, Op1);
14561   if (Opc)
14562     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14563   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14564   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14565                      DAG.getConstant(SSECC, dl, MVT::i8));
14566 }
14567
14568 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14569 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14570 /// return an empty value.
14571 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14572 {
14573   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14574   if (!BV)
14575     return SDValue();
14576
14577   MVT VT = Op1.getSimpleValueType();
14578   MVT EVT = VT.getVectorElementType();
14579   unsigned n = VT.getVectorNumElements();
14580   SmallVector<SDValue, 8> ULTOp1;
14581
14582   for (unsigned i = 0; i < n; ++i) {
14583     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14584     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14585       return SDValue();
14586
14587     // Avoid underflow.
14588     APInt Val = Elt->getAPIntValue();
14589     if (Val == 0)
14590       return SDValue();
14591
14592     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14593   }
14594
14595   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14596 }
14597
14598 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14599                            SelectionDAG &DAG) {
14600   SDValue Op0 = Op.getOperand(0);
14601   SDValue Op1 = Op.getOperand(1);
14602   SDValue CC = Op.getOperand(2);
14603   MVT VT = Op.getSimpleValueType();
14604   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14605   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14606   SDLoc dl(Op);
14607
14608   if (isFP) {
14609 #ifndef NDEBUG
14610     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14611     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14612 #endif
14613
14614     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14615     unsigned Opc = X86ISD::CMPP;
14616     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14617       assert(VT.getVectorNumElements() <= 16);
14618       Opc = X86ISD::CMPM;
14619     }
14620     // In the two special cases we can't handle, emit two comparisons.
14621     if (SSECC == 8) {
14622       unsigned CC0, CC1;
14623       unsigned CombineOpc;
14624       if (SetCCOpcode == ISD::SETUEQ) {
14625         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14626       } else {
14627         assert(SetCCOpcode == ISD::SETONE);
14628         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14629       }
14630
14631       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14632                                  DAG.getConstant(CC0, dl, MVT::i8));
14633       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14634                                  DAG.getConstant(CC1, dl, MVT::i8));
14635       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14636     }
14637     // Handle all other FP comparisons here.
14638     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14639                        DAG.getConstant(SSECC, dl, MVT::i8));
14640   }
14641
14642   MVT VTOp0 = Op0.getSimpleValueType();
14643   assert(VTOp0 == Op1.getSimpleValueType() &&
14644          "Expected operands with same type!");
14645   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14646          "Invalid number of packed elements for source and destination!");
14647
14648   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14649     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14650     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14651     // legalizer firstly checks if the first operand in input to the setcc has
14652     // a legal type. If so, then it promotes the return type to that same type.
14653     // Otherwise, the return type is promoted to the 'next legal type' which,
14654     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14655     //
14656     // We reach this code only if the following two conditions are met:
14657     // 1. Both return type and operand type have been promoted to wider types
14658     //    by the type legalizer.
14659     // 2. The original operand type has been promoted to a 256-bit vector.
14660     //
14661     // Note that condition 2. only applies for AVX targets.
14662     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14663     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14664   }
14665
14666   // The non-AVX512 code below works under the assumption that source and
14667   // destination types are the same.
14668   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14669          "Value types for source and destination must be the same!");
14670
14671   // Break 256-bit integer vector compare into smaller ones.
14672   if (VT.is256BitVector() && !Subtarget->hasInt256())
14673     return Lower256IntVSETCC(Op, DAG);
14674
14675   MVT OpVT = Op1.getSimpleValueType();
14676   if (OpVT.getVectorElementType() == MVT::i1)
14677     return LowerBoolVSETCC_AVX512(Op, DAG);
14678
14679   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14680   if (Subtarget->hasAVX512()) {
14681     if (Op1.getSimpleValueType().is512BitVector() ||
14682         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14683         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14684       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14685
14686     // In AVX-512 architecture setcc returns mask with i1 elements,
14687     // But there is no compare instruction for i8 and i16 elements in KNL.
14688     // We are not talking about 512-bit operands in this case, these
14689     // types are illegal.
14690     if (MaskResult &&
14691         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14692          OpVT.getVectorElementType().getSizeInBits() >= 8))
14693       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14694                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14695   }
14696
14697   // Lower using XOP integer comparisons.
14698   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14699        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14700     // Translate compare code to XOP PCOM compare mode.
14701     unsigned CmpMode = 0;
14702     switch (SetCCOpcode) {
14703     default: llvm_unreachable("Unexpected SETCC condition");
14704     case ISD::SETULT:
14705     case ISD::SETLT: CmpMode = 0x00; break;
14706     case ISD::SETULE:
14707     case ISD::SETLE: CmpMode = 0x01; break;
14708     case ISD::SETUGT:
14709     case ISD::SETGT: CmpMode = 0x02; break;
14710     case ISD::SETUGE:
14711     case ISD::SETGE: CmpMode = 0x03; break;
14712     case ISD::SETEQ: CmpMode = 0x04; break;
14713     case ISD::SETNE: CmpMode = 0x05; break;
14714     }
14715
14716     // Are we comparing unsigned or signed integers?
14717     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14718       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14719
14720     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14721                        DAG.getConstant(CmpMode, dl, MVT::i8));
14722   }
14723
14724   // We are handling one of the integer comparisons here.  Since SSE only has
14725   // GT and EQ comparisons for integer, swapping operands and multiple
14726   // operations may be required for some comparisons.
14727   unsigned Opc;
14728   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14729   bool Subus = false;
14730
14731   switch (SetCCOpcode) {
14732   default: llvm_unreachable("Unexpected SETCC condition");
14733   case ISD::SETNE:  Invert = true;
14734   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14735   case ISD::SETLT:  Swap = true;
14736   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14737   case ISD::SETGE:  Swap = true;
14738   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14739                     Invert = true; break;
14740   case ISD::SETULT: Swap = true;
14741   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14742                     FlipSigns = true; break;
14743   case ISD::SETUGE: Swap = true;
14744   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14745                     FlipSigns = true; Invert = true; break;
14746   }
14747
14748   // Special case: Use min/max operations for SETULE/SETUGE
14749   MVT VET = VT.getVectorElementType();
14750   bool hasMinMax =
14751        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14752     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14753
14754   if (hasMinMax) {
14755     switch (SetCCOpcode) {
14756     default: break;
14757     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14758     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14759     }
14760
14761     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14762   }
14763
14764   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14765   if (!MinMax && hasSubus) {
14766     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14767     // Op0 u<= Op1:
14768     //   t = psubus Op0, Op1
14769     //   pcmpeq t, <0..0>
14770     switch (SetCCOpcode) {
14771     default: break;
14772     case ISD::SETULT: {
14773       // If the comparison is against a constant we can turn this into a
14774       // setule.  With psubus, setule does not require a swap.  This is
14775       // beneficial because the constant in the register is no longer
14776       // destructed as the destination so it can be hoisted out of a loop.
14777       // Only do this pre-AVX since vpcmp* is no longer destructive.
14778       if (Subtarget->hasAVX())
14779         break;
14780       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14781       if (ULEOp1.getNode()) {
14782         Op1 = ULEOp1;
14783         Subus = true; Invert = false; Swap = false;
14784       }
14785       break;
14786     }
14787     // Psubus is better than flip-sign because it requires no inversion.
14788     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14789     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14790     }
14791
14792     if (Subus) {
14793       Opc = X86ISD::SUBUS;
14794       FlipSigns = false;
14795     }
14796   }
14797
14798   if (Swap)
14799     std::swap(Op0, Op1);
14800
14801   // Check that the operation in question is available (most are plain SSE2,
14802   // but PCMPGTQ and PCMPEQQ have different requirements).
14803   if (VT == MVT::v2i64) {
14804     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14805       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14806
14807       // First cast everything to the right type.
14808       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14809       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14810
14811       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14812       // bits of the inputs before performing those operations. The lower
14813       // compare is always unsigned.
14814       SDValue SB;
14815       if (FlipSigns) {
14816         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14817       } else {
14818         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14819         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14820         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14821                          Sign, Zero, Sign, Zero);
14822       }
14823       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14824       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14825
14826       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14827       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14828       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14829
14830       // Create masks for only the low parts/high parts of the 64 bit integers.
14831       static const int MaskHi[] = { 1, 1, 3, 3 };
14832       static const int MaskLo[] = { 0, 0, 2, 2 };
14833       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14834       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14835       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14836
14837       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14838       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14839
14840       if (Invert)
14841         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14842
14843       return DAG.getBitcast(VT, Result);
14844     }
14845
14846     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14847       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14848       // pcmpeqd + pshufd + pand.
14849       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14850
14851       // First cast everything to the right type.
14852       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14853       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14854
14855       // Do the compare.
14856       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14857
14858       // Make sure the lower and upper halves are both all-ones.
14859       static const int Mask[] = { 1, 0, 3, 2 };
14860       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14861       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14862
14863       if (Invert)
14864         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14865
14866       return DAG.getBitcast(VT, Result);
14867     }
14868   }
14869
14870   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14871   // bits of the inputs before performing those operations.
14872   if (FlipSigns) {
14873     MVT EltVT = VT.getVectorElementType();
14874     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14875                                  VT);
14876     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14877     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14878   }
14879
14880   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14881
14882   // If the logical-not of the result is required, perform that now.
14883   if (Invert)
14884     Result = DAG.getNOT(dl, Result, VT);
14885
14886   if (MinMax)
14887     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14888
14889   if (Subus)
14890     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14891                          getZeroVector(VT, Subtarget, DAG, dl));
14892
14893   return Result;
14894 }
14895
14896 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14897
14898   MVT VT = Op.getSimpleValueType();
14899
14900   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14901
14902   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14903          && "SetCC type must be 8-bit or 1-bit integer");
14904   SDValue Op0 = Op.getOperand(0);
14905   SDValue Op1 = Op.getOperand(1);
14906   SDLoc dl(Op);
14907   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14908
14909   // Optimize to BT if possible.
14910   // Lower (X & (1 << N)) == 0 to BT(X, N).
14911   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14912   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14913   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14914       isNullConstant(Op1) &&
14915       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14916     if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14917       if (VT == MVT::i1)
14918         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14919       return NewSetCC;
14920     }
14921   }
14922
14923   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14924   // these.
14925   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14926       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14927
14928     // If the input is a setcc, then reuse the input setcc or use a new one with
14929     // the inverted condition.
14930     if (Op0.getOpcode() == X86ISD::SETCC) {
14931       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14932       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14933       if (!Invert)
14934         return Op0;
14935
14936       CCode = X86::GetOppositeBranchCondition(CCode);
14937       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14938                                   DAG.getConstant(CCode, dl, MVT::i8),
14939                                   Op0.getOperand(1));
14940       if (VT == MVT::i1)
14941         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14942       return SetCC;
14943     }
14944   }
14945   if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14946       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14947
14948     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14949     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14950   }
14951
14952   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14953   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14954   if (X86CC == X86::COND_INVALID)
14955     return SDValue();
14956
14957   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14958   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14959   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14960                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14961   if (VT == MVT::i1)
14962     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14963   return SetCC;
14964 }
14965
14966 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14967   SDValue LHS = Op.getOperand(0);
14968   SDValue RHS = Op.getOperand(1);
14969   SDValue Carry = Op.getOperand(2);
14970   SDValue Cond = Op.getOperand(3);
14971   SDLoc DL(Op);
14972
14973   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14974   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14975
14976   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14977   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14978   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14979   SDValue SetCC = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14980                               DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14981   if (Op.getSimpleValueType() == MVT::i1)
14982       return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
14983   return SetCC;
14984 }
14985
14986 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14987 static bool isX86LogicalCmp(SDValue Op) {
14988   unsigned Opc = Op.getNode()->getOpcode();
14989   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14990       Opc == X86ISD::SAHF)
14991     return true;
14992   if (Op.getResNo() == 1 &&
14993       (Opc == X86ISD::ADD ||
14994        Opc == X86ISD::SUB ||
14995        Opc == X86ISD::ADC ||
14996        Opc == X86ISD::SBB ||
14997        Opc == X86ISD::SMUL ||
14998        Opc == X86ISD::UMUL ||
14999        Opc == X86ISD::INC ||
15000        Opc == X86ISD::DEC ||
15001        Opc == X86ISD::OR ||
15002        Opc == X86ISD::XOR ||
15003        Opc == X86ISD::AND))
15004     return true;
15005
15006   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
15007     return true;
15008
15009   return false;
15010 }
15011
15012 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
15013   if (V.getOpcode() != ISD::TRUNCATE)
15014     return false;
15015
15016   SDValue VOp0 = V.getOperand(0);
15017   unsigned InBits = VOp0.getValueSizeInBits();
15018   unsigned Bits = V.getValueSizeInBits();
15019   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
15020 }
15021
15022 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
15023   bool addTest = true;
15024   SDValue Cond  = Op.getOperand(0);
15025   SDValue Op1 = Op.getOperand(1);
15026   SDValue Op2 = Op.getOperand(2);
15027   SDLoc DL(Op);
15028   MVT VT = Op1.getSimpleValueType();
15029   SDValue CC;
15030
15031   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
15032   // are available or VBLENDV if AVX is available.
15033   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
15034   if (Cond.getOpcode() == ISD::SETCC &&
15035       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15036        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
15037       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
15038     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15039     int SSECC = translateX86FSETCC(
15040         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15041
15042     if (SSECC != 8) {
15043       if (Subtarget->hasAVX512()) {
15044         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15045                                   DAG.getConstant(SSECC, DL, MVT::i8));
15046         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15047       }
15048
15049       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15050                                 DAG.getConstant(SSECC, DL, MVT::i8));
15051
15052       // If we have AVX, we can use a variable vector select (VBLENDV) instead
15053       // of 3 logic instructions for size savings and potentially speed.
15054       // Unfortunately, there is no scalar form of VBLENDV.
15055
15056       // If either operand is a constant, don't try this. We can expect to
15057       // optimize away at least one of the logic instructions later in that
15058       // case, so that sequence would be faster than a variable blend.
15059
15060       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
15061       // uses XMM0 as the selection register. That may need just as many
15062       // instructions as the AND/ANDN/OR sequence due to register moves, so
15063       // don't bother.
15064
15065       if (Subtarget->hasAVX() &&
15066           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
15067
15068         // Convert to vectors, do a VSELECT, and convert back to scalar.
15069         // All of the conversions should be optimized away.
15070
15071         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
15072         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
15073         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
15074         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
15075
15076         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
15077         VCmp = DAG.getBitcast(VCmpVT, VCmp);
15078
15079         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
15080
15081         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
15082                            VSel, DAG.getIntPtrConstant(0, DL));
15083       }
15084       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15085       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15086       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15087     }
15088   }
15089
15090   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
15091     SDValue Op1Scalar;
15092     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
15093       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
15094     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
15095       Op1Scalar = Op1.getOperand(0);
15096     SDValue Op2Scalar;
15097     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
15098       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
15099     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
15100       Op2Scalar = Op2.getOperand(0);
15101     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
15102       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
15103                                       Op1Scalar.getValueType(),
15104                                       Cond, Op1Scalar, Op2Scalar);
15105       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
15106         return DAG.getBitcast(VT, newSelect);
15107       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
15108       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
15109                          DAG.getIntPtrConstant(0, DL));
15110     }
15111   }
15112
15113   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
15114     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
15115     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15116                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
15117     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15118                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
15119     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
15120                                     Cond, Op1, Op2);
15121     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
15122   }
15123
15124   if (Cond.getOpcode() == ISD::SETCC) {
15125     SDValue NewCond = LowerSETCC(Cond, DAG);
15126     if (NewCond.getNode())
15127       Cond = NewCond;
15128   }
15129
15130   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15131   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15132   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15133   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15134   if (Cond.getOpcode() == X86ISD::SETCC &&
15135       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15136       isNullConstant(Cond.getOperand(1).getOperand(1))) {
15137     SDValue Cmp = Cond.getOperand(1);
15138
15139     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15140
15141     if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15142         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15143       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
15144
15145       SDValue CmpOp0 = Cmp.getOperand(0);
15146       // Apply further optimizations for special cases
15147       // (select (x != 0), -1, 0) -> neg & sbb
15148       // (select (x == 0), 0, -1) -> neg & sbb
15149       if (isNullConstant(Y) &&
15150             (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
15151           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15152           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15153                                     DAG.getConstant(0, DL,
15154                                                     CmpOp0.getValueType()),
15155                                     CmpOp0);
15156           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15157                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
15158                                     SDValue(Neg.getNode(), 1));
15159           return Res;
15160         }
15161
15162       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15163                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
15164       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15165
15166       SDValue Res =   // Res = 0 or -1.
15167         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15168                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
15169
15170       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
15171         Res = DAG.getNOT(DL, Res, Res.getValueType());
15172
15173       if (!isNullConstant(Op2))
15174         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15175       return Res;
15176     }
15177   }
15178
15179   // Look past (and (setcc_carry (cmp ...)), 1).
15180   if (Cond.getOpcode() == ISD::AND &&
15181       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15182       isOneConstant(Cond.getOperand(1)))
15183     Cond = Cond.getOperand(0);
15184
15185   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15186   // setting operand in place of the X86ISD::SETCC.
15187   unsigned CondOpcode = Cond.getOpcode();
15188   if (CondOpcode == X86ISD::SETCC ||
15189       CondOpcode == X86ISD::SETCC_CARRY) {
15190     CC = Cond.getOperand(0);
15191
15192     SDValue Cmp = Cond.getOperand(1);
15193     unsigned Opc = Cmp.getOpcode();
15194     MVT VT = Op.getSimpleValueType();
15195
15196     bool IllegalFPCMov = false;
15197     if (VT.isFloatingPoint() && !VT.isVector() &&
15198         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15199       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15200
15201     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15202         Opc == X86ISD::BT) { // FIXME
15203       Cond = Cmp;
15204       addTest = false;
15205     }
15206   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15207              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15208              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15209               Cond.getOperand(0).getValueType() != MVT::i8)) {
15210     SDValue LHS = Cond.getOperand(0);
15211     SDValue RHS = Cond.getOperand(1);
15212     unsigned X86Opcode;
15213     unsigned X86Cond;
15214     SDVTList VTs;
15215     switch (CondOpcode) {
15216     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15217     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15218     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15219     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15220     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15221     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15222     default: llvm_unreachable("unexpected overflowing operator");
15223     }
15224     if (CondOpcode == ISD::UMULO)
15225       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15226                           MVT::i32);
15227     else
15228       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15229
15230     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15231
15232     if (CondOpcode == ISD::UMULO)
15233       Cond = X86Op.getValue(2);
15234     else
15235       Cond = X86Op.getValue(1);
15236
15237     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15238     addTest = false;
15239   }
15240
15241   if (addTest) {
15242     // Look past the truncate if the high bits are known zero.
15243     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15244       Cond = Cond.getOperand(0);
15245
15246     // We know the result of AND is compared against zero. Try to match
15247     // it to BT.
15248     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15249       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
15250         CC = NewSetCC.getOperand(0);
15251         Cond = NewSetCC.getOperand(1);
15252         addTest = false;
15253       }
15254     }
15255   }
15256
15257   if (addTest) {
15258     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
15259     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15260   }
15261
15262   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15263   // a <  b ?  0 : -1 -> RES = setcc_carry
15264   // a >= b ? -1 :  0 -> RES = setcc_carry
15265   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15266   if (Cond.getOpcode() == X86ISD::SUB) {
15267     Cond = ConvertCmpIfNecessary(Cond, DAG);
15268     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15269
15270     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15271         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15272         (isNullConstant(Op1) || isNullConstant(Op2))) {
15273       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15274                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15275                                 Cond);
15276       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15277         return DAG.getNOT(DL, Res, Res.getValueType());
15278       return Res;
15279     }
15280   }
15281
15282   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15283   // widen the cmov and push the truncate through. This avoids introducing a new
15284   // branch during isel and doesn't add any extensions.
15285   if (Op.getValueType() == MVT::i8 &&
15286       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15287     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15288     if (T1.getValueType() == T2.getValueType() &&
15289         // Blacklist CopyFromReg to avoid partial register stalls.
15290         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15291       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15292       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15293       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15294     }
15295   }
15296
15297   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15298   // condition is true.
15299   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15300   SDValue Ops[] = { Op2, Op1, CC, Cond };
15301   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15302 }
15303
15304 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15305                                        const X86Subtarget *Subtarget,
15306                                        SelectionDAG &DAG) {
15307   MVT VT = Op->getSimpleValueType(0);
15308   SDValue In = Op->getOperand(0);
15309   MVT InVT = In.getSimpleValueType();
15310   MVT VTElt = VT.getVectorElementType();
15311   MVT InVTElt = InVT.getVectorElementType();
15312   SDLoc dl(Op);
15313
15314   // SKX processor
15315   if ((InVTElt == MVT::i1) &&
15316       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15317         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15318
15319        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15320         VTElt.getSizeInBits() <= 16)) ||
15321
15322        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15323         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15324
15325        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15326         VTElt.getSizeInBits() >= 32))))
15327     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15328
15329   unsigned int NumElts = VT.getVectorNumElements();
15330
15331   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15332     return SDValue();
15333
15334   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15335     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15336       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15337     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15338   }
15339
15340   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15341   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15342   SDValue NegOne =
15343    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15344                    ExtVT);
15345   SDValue Zero =
15346    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15347
15348   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15349   if (VT.is512BitVector())
15350     return V;
15351   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15352 }
15353
15354 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15355                                              const X86Subtarget *Subtarget,
15356                                              SelectionDAG &DAG) {
15357   SDValue In = Op->getOperand(0);
15358   MVT VT = Op->getSimpleValueType(0);
15359   MVT InVT = In.getSimpleValueType();
15360   assert(VT.getSizeInBits() == InVT.getSizeInBits());
15361
15362   MVT InSVT = InVT.getVectorElementType();
15363   assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15364
15365   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15366     return SDValue();
15367   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15368     return SDValue();
15369
15370   SDLoc dl(Op);
15371
15372   // SSE41 targets can use the pmovsx* instructions directly.
15373   if (Subtarget->hasSSE41())
15374     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15375
15376   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15377   SDValue Curr = In;
15378   MVT CurrVT = InVT;
15379
15380   // As SRAI is only available on i16/i32 types, we expand only up to i32
15381   // and handle i64 separately.
15382   while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15383     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15384     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15385     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15386     Curr = DAG.getBitcast(CurrVT, Curr);
15387   }
15388
15389   SDValue SignExt = Curr;
15390   if (CurrVT != InVT) {
15391     unsigned SignExtShift =
15392         CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15393     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15394                           DAG.getConstant(SignExtShift, dl, MVT::i8));
15395   }
15396
15397   if (CurrVT == VT)
15398     return SignExt;
15399
15400   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15401     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15402                                DAG.getConstant(31, dl, MVT::i8));
15403     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15404     return DAG.getBitcast(VT, Ext);
15405   }
15406
15407   return SDValue();
15408 }
15409
15410 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15411                                 SelectionDAG &DAG) {
15412   MVT VT = Op->getSimpleValueType(0);
15413   SDValue In = Op->getOperand(0);
15414   MVT InVT = In.getSimpleValueType();
15415   SDLoc dl(Op);
15416
15417   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15418     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15419
15420   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15421       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15422       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15423     return SDValue();
15424
15425   if (Subtarget->hasInt256())
15426     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15427
15428   // Optimize vectors in AVX mode
15429   // Sign extend  v8i16 to v8i32 and
15430   //              v4i32 to v4i64
15431   //
15432   // Divide input vector into two parts
15433   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15434   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15435   // concat the vectors to original VT
15436
15437   unsigned NumElems = InVT.getVectorNumElements();
15438   SDValue Undef = DAG.getUNDEF(InVT);
15439
15440   SmallVector<int,8> ShufMask1(NumElems, -1);
15441   for (unsigned i = 0; i != NumElems/2; ++i)
15442     ShufMask1[i] = i;
15443
15444   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15445
15446   SmallVector<int,8> ShufMask2(NumElems, -1);
15447   for (unsigned i = 0; i != NumElems/2; ++i)
15448     ShufMask2[i] = i + NumElems/2;
15449
15450   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15451
15452   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15453                                 VT.getVectorNumElements()/2);
15454
15455   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15456   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15457
15458   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15459 }
15460
15461 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15462 // may emit an illegal shuffle but the expansion is still better than scalar
15463 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15464 // we'll emit a shuffle and a arithmetic shift.
15465 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15466 // TODO: It is possible to support ZExt by zeroing the undef values during
15467 // the shuffle phase or after the shuffle.
15468 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15469                                  SelectionDAG &DAG) {
15470   MVT RegVT = Op.getSimpleValueType();
15471   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15472   assert(RegVT.isInteger() &&
15473          "We only custom lower integer vector sext loads.");
15474
15475   // Nothing useful we can do without SSE2 shuffles.
15476   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15477
15478   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15479   SDLoc dl(Ld);
15480   EVT MemVT = Ld->getMemoryVT();
15481   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15482   unsigned RegSz = RegVT.getSizeInBits();
15483
15484   ISD::LoadExtType Ext = Ld->getExtensionType();
15485
15486   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15487          && "Only anyext and sext are currently implemented.");
15488   assert(MemVT != RegVT && "Cannot extend to the same type");
15489   assert(MemVT.isVector() && "Must load a vector from memory");
15490
15491   unsigned NumElems = RegVT.getVectorNumElements();
15492   unsigned MemSz = MemVT.getSizeInBits();
15493   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15494
15495   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15496     // The only way in which we have a legal 256-bit vector result but not the
15497     // integer 256-bit operations needed to directly lower a sextload is if we
15498     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15499     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15500     // correctly legalized. We do this late to allow the canonical form of
15501     // sextload to persist throughout the rest of the DAG combiner -- it wants
15502     // to fold together any extensions it can, and so will fuse a sign_extend
15503     // of an sextload into a sextload targeting a wider value.
15504     SDValue Load;
15505     if (MemSz == 128) {
15506       // Just switch this to a normal load.
15507       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15508                                        "it must be a legal 128-bit vector "
15509                                        "type!");
15510       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15511                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15512                   Ld->isInvariant(), Ld->getAlignment());
15513     } else {
15514       assert(MemSz < 128 &&
15515              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15516       // Do an sext load to a 128-bit vector type. We want to use the same
15517       // number of elements, but elements half as wide. This will end up being
15518       // recursively lowered by this routine, but will succeed as we definitely
15519       // have all the necessary features if we're using AVX1.
15520       EVT HalfEltVT =
15521           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15522       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15523       Load =
15524           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15525                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15526                          Ld->isNonTemporal(), Ld->isInvariant(),
15527                          Ld->getAlignment());
15528     }
15529
15530     // Replace chain users with the new chain.
15531     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15532     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15533
15534     // Finally, do a normal sign-extend to the desired register.
15535     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15536   }
15537
15538   // All sizes must be a power of two.
15539   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15540          "Non-power-of-two elements are not custom lowered!");
15541
15542   // Attempt to load the original value using scalar loads.
15543   // Find the largest scalar type that divides the total loaded size.
15544   MVT SclrLoadTy = MVT::i8;
15545   for (MVT Tp : MVT::integer_valuetypes()) {
15546     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15547       SclrLoadTy = Tp;
15548     }
15549   }
15550
15551   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15552   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15553       (64 <= MemSz))
15554     SclrLoadTy = MVT::f64;
15555
15556   // Calculate the number of scalar loads that we need to perform
15557   // in order to load our vector from memory.
15558   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15559
15560   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15561          "Can only lower sext loads with a single scalar load!");
15562
15563   unsigned loadRegZize = RegSz;
15564   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15565     loadRegZize = 128;
15566
15567   // Represent our vector as a sequence of elements which are the
15568   // largest scalar that we can load.
15569   EVT LoadUnitVecVT = EVT::getVectorVT(
15570       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15571
15572   // Represent the data using the same element type that is stored in
15573   // memory. In practice, we ''widen'' MemVT.
15574   EVT WideVecVT =
15575       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15576                        loadRegZize / MemVT.getScalarSizeInBits());
15577
15578   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15579          "Invalid vector type");
15580
15581   // We can't shuffle using an illegal type.
15582   assert(TLI.isTypeLegal(WideVecVT) &&
15583          "We only lower types that form legal widened vector types");
15584
15585   SmallVector<SDValue, 8> Chains;
15586   SDValue Ptr = Ld->getBasePtr();
15587   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15588                                       TLI.getPointerTy(DAG.getDataLayout()));
15589   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15590
15591   for (unsigned i = 0; i < NumLoads; ++i) {
15592     // Perform a single load.
15593     SDValue ScalarLoad =
15594         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15595                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15596                     Ld->getAlignment());
15597     Chains.push_back(ScalarLoad.getValue(1));
15598     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15599     // another round of DAGCombining.
15600     if (i == 0)
15601       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15602     else
15603       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15604                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15605
15606     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15607   }
15608
15609   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15610
15611   // Bitcast the loaded value to a vector of the original element type, in
15612   // the size of the target vector type.
15613   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15614   unsigned SizeRatio = RegSz / MemSz;
15615
15616   if (Ext == ISD::SEXTLOAD) {
15617     // If we have SSE4.1, we can directly emit a VSEXT node.
15618     if (Subtarget->hasSSE41()) {
15619       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15620       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15621       return Sext;
15622     }
15623
15624     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15625     // lanes.
15626     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15627            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15628
15629     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15630     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15631     return Shuff;
15632   }
15633
15634   // Redistribute the loaded elements into the different locations.
15635   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15636   for (unsigned i = 0; i != NumElems; ++i)
15637     ShuffleVec[i * SizeRatio] = i;
15638
15639   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15640                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15641
15642   // Bitcast to the requested type.
15643   Shuff = DAG.getBitcast(RegVT, Shuff);
15644   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15645   return Shuff;
15646 }
15647
15648 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15649 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15650 // from the AND / OR.
15651 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15652   Opc = Op.getOpcode();
15653   if (Opc != ISD::OR && Opc != ISD::AND)
15654     return false;
15655   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15656           Op.getOperand(0).hasOneUse() &&
15657           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15658           Op.getOperand(1).hasOneUse());
15659 }
15660
15661 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15662 // 1 and that the SETCC node has a single use.
15663 static bool isXor1OfSetCC(SDValue Op) {
15664   if (Op.getOpcode() != ISD::XOR)
15665     return false;
15666   if (isOneConstant(Op.getOperand(1)))
15667     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15668            Op.getOperand(0).hasOneUse();
15669   return false;
15670 }
15671
15672 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15673   bool addTest = true;
15674   SDValue Chain = Op.getOperand(0);
15675   SDValue Cond  = Op.getOperand(1);
15676   SDValue Dest  = Op.getOperand(2);
15677   SDLoc dl(Op);
15678   SDValue CC;
15679   bool Inverted = false;
15680
15681   if (Cond.getOpcode() == ISD::SETCC) {
15682     // Check for setcc([su]{add,sub,mul}o == 0).
15683     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15684         isNullConstant(Cond.getOperand(1)) &&
15685         Cond.getOperand(0).getResNo() == 1 &&
15686         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15687          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15688          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15689          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15690          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15691          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15692       Inverted = true;
15693       Cond = Cond.getOperand(0);
15694     } else {
15695       SDValue NewCond = LowerSETCC(Cond, DAG);
15696       if (NewCond.getNode())
15697         Cond = NewCond;
15698     }
15699   }
15700 #if 0
15701   // FIXME: LowerXALUO doesn't handle these!!
15702   else if (Cond.getOpcode() == X86ISD::ADD  ||
15703            Cond.getOpcode() == X86ISD::SUB  ||
15704            Cond.getOpcode() == X86ISD::SMUL ||
15705            Cond.getOpcode() == X86ISD::UMUL)
15706     Cond = LowerXALUO(Cond, DAG);
15707 #endif
15708
15709   // Look pass (and (setcc_carry (cmp ...)), 1).
15710   if (Cond.getOpcode() == ISD::AND &&
15711       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15712       isOneConstant(Cond.getOperand(1)))
15713     Cond = Cond.getOperand(0);
15714
15715   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15716   // setting operand in place of the X86ISD::SETCC.
15717   unsigned CondOpcode = Cond.getOpcode();
15718   if (CondOpcode == X86ISD::SETCC ||
15719       CondOpcode == X86ISD::SETCC_CARRY) {
15720     CC = Cond.getOperand(0);
15721
15722     SDValue Cmp = Cond.getOperand(1);
15723     unsigned Opc = Cmp.getOpcode();
15724     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15725     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15726       Cond = Cmp;
15727       addTest = false;
15728     } else {
15729       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15730       default: break;
15731       case X86::COND_O:
15732       case X86::COND_B:
15733         // These can only come from an arithmetic instruction with overflow,
15734         // e.g. SADDO, UADDO.
15735         Cond = Cond.getNode()->getOperand(1);
15736         addTest = false;
15737         break;
15738       }
15739     }
15740   }
15741   CondOpcode = Cond.getOpcode();
15742   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15743       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15744       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15745        Cond.getOperand(0).getValueType() != MVT::i8)) {
15746     SDValue LHS = Cond.getOperand(0);
15747     SDValue RHS = Cond.getOperand(1);
15748     unsigned X86Opcode;
15749     unsigned X86Cond;
15750     SDVTList VTs;
15751     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15752     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15753     // X86ISD::INC).
15754     switch (CondOpcode) {
15755     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15756     case ISD::SADDO:
15757       if (isOneConstant(RHS)) {
15758           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15759           break;
15760         }
15761       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15762     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15763     case ISD::SSUBO:
15764       if (isOneConstant(RHS)) {
15765           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15766           break;
15767         }
15768       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15769     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15770     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15771     default: llvm_unreachable("unexpected overflowing operator");
15772     }
15773     if (Inverted)
15774       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15775     if (CondOpcode == ISD::UMULO)
15776       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15777                           MVT::i32);
15778     else
15779       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15780
15781     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15782
15783     if (CondOpcode == ISD::UMULO)
15784       Cond = X86Op.getValue(2);
15785     else
15786       Cond = X86Op.getValue(1);
15787
15788     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15789     addTest = false;
15790   } else {
15791     unsigned CondOpc;
15792     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15793       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15794       if (CondOpc == ISD::OR) {
15795         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15796         // two branches instead of an explicit OR instruction with a
15797         // separate test.
15798         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15799             isX86LogicalCmp(Cmp)) {
15800           CC = Cond.getOperand(0).getOperand(0);
15801           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15802                               Chain, Dest, CC, Cmp);
15803           CC = Cond.getOperand(1).getOperand(0);
15804           Cond = Cmp;
15805           addTest = false;
15806         }
15807       } else { // ISD::AND
15808         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15809         // two branches instead of an explicit AND instruction with a
15810         // separate test. However, we only do this if this block doesn't
15811         // have a fall-through edge, because this requires an explicit
15812         // jmp when the condition is false.
15813         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15814             isX86LogicalCmp(Cmp) &&
15815             Op.getNode()->hasOneUse()) {
15816           X86::CondCode CCode =
15817             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15818           CCode = X86::GetOppositeBranchCondition(CCode);
15819           CC = DAG.getConstant(CCode, dl, MVT::i8);
15820           SDNode *User = *Op.getNode()->use_begin();
15821           // Look for an unconditional branch following this conditional branch.
15822           // We need this because we need to reverse the successors in order
15823           // to implement FCMP_OEQ.
15824           if (User->getOpcode() == ISD::BR) {
15825             SDValue FalseBB = User->getOperand(1);
15826             SDNode *NewBR =
15827               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15828             assert(NewBR == User);
15829             (void)NewBR;
15830             Dest = FalseBB;
15831
15832             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15833                                 Chain, Dest, CC, Cmp);
15834             X86::CondCode CCode =
15835               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15836             CCode = X86::GetOppositeBranchCondition(CCode);
15837             CC = DAG.getConstant(CCode, dl, MVT::i8);
15838             Cond = Cmp;
15839             addTest = false;
15840           }
15841         }
15842       }
15843     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15844       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15845       // It should be transformed during dag combiner except when the condition
15846       // is set by a arithmetics with overflow node.
15847       X86::CondCode CCode =
15848         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15849       CCode = X86::GetOppositeBranchCondition(CCode);
15850       CC = DAG.getConstant(CCode, dl, MVT::i8);
15851       Cond = Cond.getOperand(0).getOperand(1);
15852       addTest = false;
15853     } else if (Cond.getOpcode() == ISD::SETCC &&
15854                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15855       // For FCMP_OEQ, we can emit
15856       // two branches instead of an explicit AND instruction with a
15857       // separate test. However, we only do this if this block doesn't
15858       // have a fall-through edge, because this requires an explicit
15859       // jmp when the condition is false.
15860       if (Op.getNode()->hasOneUse()) {
15861         SDNode *User = *Op.getNode()->use_begin();
15862         // Look for an unconditional branch following this conditional branch.
15863         // We need this because we need to reverse the successors in order
15864         // to implement FCMP_OEQ.
15865         if (User->getOpcode() == ISD::BR) {
15866           SDValue FalseBB = User->getOperand(1);
15867           SDNode *NewBR =
15868             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15869           assert(NewBR == User);
15870           (void)NewBR;
15871           Dest = FalseBB;
15872
15873           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15874                                     Cond.getOperand(0), Cond.getOperand(1));
15875           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15876           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15877           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15878                               Chain, Dest, CC, Cmp);
15879           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15880           Cond = Cmp;
15881           addTest = false;
15882         }
15883       }
15884     } else if (Cond.getOpcode() == ISD::SETCC &&
15885                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15886       // For FCMP_UNE, we can emit
15887       // two branches instead of an explicit AND instruction with a
15888       // separate test. However, we only do this if this block doesn't
15889       // have a fall-through edge, because this requires an explicit
15890       // jmp when the condition is false.
15891       if (Op.getNode()->hasOneUse()) {
15892         SDNode *User = *Op.getNode()->use_begin();
15893         // Look for an unconditional branch following this conditional branch.
15894         // We need this because we need to reverse the successors in order
15895         // to implement FCMP_UNE.
15896         if (User->getOpcode() == ISD::BR) {
15897           SDValue FalseBB = User->getOperand(1);
15898           SDNode *NewBR =
15899             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15900           assert(NewBR == User);
15901           (void)NewBR;
15902
15903           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15904                                     Cond.getOperand(0), Cond.getOperand(1));
15905           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15906           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15907           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15908                               Chain, Dest, CC, Cmp);
15909           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15910           Cond = Cmp;
15911           addTest = false;
15912           Dest = FalseBB;
15913         }
15914       }
15915     }
15916   }
15917
15918   if (addTest) {
15919     // Look pass the truncate if the high bits are known zero.
15920     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15921         Cond = Cond.getOperand(0);
15922
15923     // We know the result of AND is compared against zero. Try to match
15924     // it to BT.
15925     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15926       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15927         CC = NewSetCC.getOperand(0);
15928         Cond = NewSetCC.getOperand(1);
15929         addTest = false;
15930       }
15931     }
15932   }
15933
15934   if (addTest) {
15935     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15936     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15937     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15938   }
15939   Cond = ConvertCmpIfNecessary(Cond, DAG);
15940   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15941                      Chain, Dest, CC, Cond);
15942 }
15943
15944 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15945 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15946 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15947 // that the guard pages used by the OS virtual memory manager are allocated in
15948 // correct sequence.
15949 SDValue
15950 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15951                                            SelectionDAG &DAG) const {
15952   MachineFunction &MF = DAG.getMachineFunction();
15953   bool SplitStack = MF.shouldSplitStack();
15954   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15955                SplitStack;
15956   SDLoc dl(Op);
15957
15958   // Get the inputs.
15959   SDNode *Node = Op.getNode();
15960   SDValue Chain = Op.getOperand(0);
15961   SDValue Size  = Op.getOperand(1);
15962   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15963   EVT VT = Node->getValueType(0);
15964
15965   // Chain the dynamic stack allocation so that it doesn't modify the stack
15966   // pointer when other instructions are using the stack.
15967   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15968
15969   bool Is64Bit = Subtarget->is64Bit();
15970   MVT SPTy = getPointerTy(DAG.getDataLayout());
15971
15972   SDValue Result;
15973   if (!Lower) {
15974     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15975     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15976     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15977                     " not tell us which reg is the stack pointer!");
15978     EVT VT = Node->getValueType(0);
15979     SDValue Tmp3 = Node->getOperand(2);
15980
15981     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15982     Chain = SP.getValue(1);
15983     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15984     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15985     unsigned StackAlign = TFI.getStackAlignment();
15986     Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15987     if (Align > StackAlign)
15988       Result = DAG.getNode(ISD::AND, dl, VT, Result,
15989                          DAG.getConstant(-(uint64_t)Align, dl, VT));
15990     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15991   } else if (SplitStack) {
15992     MachineRegisterInfo &MRI = MF.getRegInfo();
15993
15994     if (Is64Bit) {
15995       // The 64 bit implementation of segmented stacks needs to clobber both r10
15996       // r11. This makes it impossible to use it along with nested parameters.
15997       const Function *F = MF.getFunction();
15998
15999       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
16000            I != E; ++I)
16001         if (I->hasNestAttr())
16002           report_fatal_error("Cannot use segmented stacks with functions that "
16003                              "have nested arguments.");
16004     }
16005
16006     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
16007     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16008     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16009     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16010                                 DAG.getRegister(Vreg, SPTy));
16011   } else {
16012     SDValue Flag;
16013     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
16014
16015     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
16016     Flag = Chain.getValue(1);
16017     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16018
16019     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
16020
16021     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16022     unsigned SPReg = RegInfo->getStackRegister();
16023     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16024     Chain = SP.getValue(1);
16025
16026     if (Align) {
16027       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16028                        DAG.getConstant(-(uint64_t)Align, dl, VT));
16029       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16030     }
16031
16032     Result = SP;
16033   }
16034
16035   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
16036                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
16037
16038   SDValue Ops[2] = {Result, Chain};
16039   return DAG.getMergeValues(Ops, dl);
16040 }
16041
16042 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16043   MachineFunction &MF = DAG.getMachineFunction();
16044   auto PtrVT = getPointerTy(MF.getDataLayout());
16045   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16046
16047   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16048   SDLoc DL(Op);
16049
16050   if (!Subtarget->is64Bit() ||
16051       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
16052     // vastart just stores the address of the VarArgsFrameIndex slot into the
16053     // memory location argument.
16054     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16055     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16056                         MachinePointerInfo(SV), false, false, 0);
16057   }
16058
16059   // __va_list_tag:
16060   //   gp_offset         (0 - 6 * 8)
16061   //   fp_offset         (48 - 48 + 8 * 16)
16062   //   overflow_arg_area (point to parameters coming in memory).
16063   //   reg_save_area
16064   SmallVector<SDValue, 8> MemOps;
16065   SDValue FIN = Op.getOperand(1);
16066   // Store gp_offset
16067   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16068                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16069                                                DL, MVT::i32),
16070                                FIN, MachinePointerInfo(SV), false, false, 0);
16071   MemOps.push_back(Store);
16072
16073   // Store fp_offset
16074   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16075   Store = DAG.getStore(Op.getOperand(0), DL,
16076                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
16077                                        MVT::i32),
16078                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
16079   MemOps.push_back(Store);
16080
16081   // Store ptr to overflow_arg_area
16082   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16083   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16084   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16085                        MachinePointerInfo(SV, 8),
16086                        false, false, 0);
16087   MemOps.push_back(Store);
16088
16089   // Store ptr to reg_save_area.
16090   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
16091       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
16092   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
16093   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
16094       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
16095   MemOps.push_back(Store);
16096   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16097 }
16098
16099 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16100   assert(Subtarget->is64Bit() &&
16101          "LowerVAARG only handles 64-bit va_arg!");
16102   assert(Op.getNode()->getNumOperands() == 4);
16103
16104   MachineFunction &MF = DAG.getMachineFunction();
16105   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
16106     // The Win64 ABI uses char* instead of a structure.
16107     return DAG.expandVAArg(Op.getNode());
16108
16109   SDValue Chain = Op.getOperand(0);
16110   SDValue SrcPtr = Op.getOperand(1);
16111   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16112   unsigned Align = Op.getConstantOperandVal(3);
16113   SDLoc dl(Op);
16114
16115   EVT ArgVT = Op.getNode()->getValueType(0);
16116   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16117   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
16118   uint8_t ArgMode;
16119
16120   // Decide which area this value should be read from.
16121   // TODO: Implement the AMD64 ABI in its entirety. This simple
16122   // selection mechanism works only for the basic types.
16123   if (ArgVT == MVT::f80) {
16124     llvm_unreachable("va_arg for f80 not yet implemented");
16125   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16126     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16127   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16128     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16129   } else {
16130     llvm_unreachable("Unhandled argument type in LowerVAARG");
16131   }
16132
16133   if (ArgMode == 2) {
16134     // Sanity Check: Make sure using fp_offset makes sense.
16135     assert(!Subtarget->useSoftFloat() &&
16136            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
16137            Subtarget->hasSSE1());
16138   }
16139
16140   // Insert VAARG_64 node into the DAG
16141   // VAARG_64 returns two values: Variable Argument Address, Chain
16142   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
16143                        DAG.getConstant(ArgMode, dl, MVT::i8),
16144                        DAG.getConstant(Align, dl, MVT::i32)};
16145   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
16146   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16147                                           VTs, InstOps, MVT::i64,
16148                                           MachinePointerInfo(SV),
16149                                           /*Align=*/0,
16150                                           /*Volatile=*/false,
16151                                           /*ReadMem=*/true,
16152                                           /*WriteMem=*/true);
16153   Chain = VAARG.getValue(1);
16154
16155   // Load the next argument and return it
16156   return DAG.getLoad(ArgVT, dl,
16157                      Chain,
16158                      VAARG,
16159                      MachinePointerInfo(),
16160                      false, false, false, 0);
16161 }
16162
16163 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16164                            SelectionDAG &DAG) {
16165   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
16166   // where a va_list is still an i8*.
16167   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16168   if (Subtarget->isCallingConvWin64(
16169         DAG.getMachineFunction().getFunction()->getCallingConv()))
16170     // Probably a Win64 va_copy.
16171     return DAG.expandVACopy(Op.getNode());
16172
16173   SDValue Chain = Op.getOperand(0);
16174   SDValue DstPtr = Op.getOperand(1);
16175   SDValue SrcPtr = Op.getOperand(2);
16176   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16177   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16178   SDLoc DL(Op);
16179
16180   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16181                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
16182                        false, false,
16183                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16184 }
16185
16186 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16187 // amount is a constant. Takes immediate version of shift as input.
16188 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16189                                           SDValue SrcOp, uint64_t ShiftAmt,
16190                                           SelectionDAG &DAG) {
16191   MVT ElementType = VT.getVectorElementType();
16192
16193   // Fold this packed shift into its first operand if ShiftAmt is 0.
16194   if (ShiftAmt == 0)
16195     return SrcOp;
16196
16197   // Check for ShiftAmt >= element width
16198   if (ShiftAmt >= ElementType.getSizeInBits()) {
16199     if (Opc == X86ISD::VSRAI)
16200       ShiftAmt = ElementType.getSizeInBits() - 1;
16201     else
16202       return DAG.getConstant(0, dl, VT);
16203   }
16204
16205   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16206          && "Unknown target vector shift-by-constant node");
16207
16208   // Fold this packed vector shift into a build vector if SrcOp is a
16209   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16210   if (VT == SrcOp.getSimpleValueType() &&
16211       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16212     SmallVector<SDValue, 8> Elts;
16213     unsigned NumElts = SrcOp->getNumOperands();
16214     ConstantSDNode *ND;
16215
16216     switch(Opc) {
16217     default: llvm_unreachable(nullptr);
16218     case X86ISD::VSHLI:
16219       for (unsigned i=0; i!=NumElts; ++i) {
16220         SDValue CurrentOp = SrcOp->getOperand(i);
16221         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16222           Elts.push_back(CurrentOp);
16223           continue;
16224         }
16225         ND = cast<ConstantSDNode>(CurrentOp);
16226         const APInt &C = ND->getAPIntValue();
16227         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
16228       }
16229       break;
16230     case X86ISD::VSRLI:
16231       for (unsigned i=0; i!=NumElts; ++i) {
16232         SDValue CurrentOp = SrcOp->getOperand(i);
16233         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16234           Elts.push_back(CurrentOp);
16235           continue;
16236         }
16237         ND = cast<ConstantSDNode>(CurrentOp);
16238         const APInt &C = ND->getAPIntValue();
16239         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
16240       }
16241       break;
16242     case X86ISD::VSRAI:
16243       for (unsigned i=0; i!=NumElts; ++i) {
16244         SDValue CurrentOp = SrcOp->getOperand(i);
16245         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16246           Elts.push_back(CurrentOp);
16247           continue;
16248         }
16249         ND = cast<ConstantSDNode>(CurrentOp);
16250         const APInt &C = ND->getAPIntValue();
16251         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
16252       }
16253       break;
16254     }
16255
16256     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16257   }
16258
16259   return DAG.getNode(Opc, dl, VT, SrcOp,
16260                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
16261 }
16262
16263 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16264 // may or may not be a constant. Takes immediate version of shift as input.
16265 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16266                                    SDValue SrcOp, SDValue ShAmt,
16267                                    SelectionDAG &DAG) {
16268   MVT SVT = ShAmt.getSimpleValueType();
16269   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16270
16271   // Catch shift-by-constant.
16272   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16273     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16274                                       CShAmt->getZExtValue(), DAG);
16275
16276   // Change opcode to non-immediate version
16277   switch (Opc) {
16278     default: llvm_unreachable("Unknown target vector shift node");
16279     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16280     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16281     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16282   }
16283
16284   const X86Subtarget &Subtarget =
16285       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16286   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16287       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16288     // Let the shuffle legalizer expand this shift amount node.
16289     SDValue Op0 = ShAmt.getOperand(0);
16290     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16291     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16292   } else {
16293     // Need to build a vector containing shift amount.
16294     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16295     SmallVector<SDValue, 4> ShOps;
16296     ShOps.push_back(ShAmt);
16297     if (SVT == MVT::i32) {
16298       ShOps.push_back(DAG.getConstant(0, dl, SVT));
16299       ShOps.push_back(DAG.getUNDEF(SVT));
16300     }
16301     ShOps.push_back(DAG.getUNDEF(SVT));
16302
16303     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16304     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16305   }
16306
16307   // The return type has to be a 128-bit type with the same element
16308   // type as the input type.
16309   MVT EltVT = VT.getVectorElementType();
16310   MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16311
16312   ShAmt = DAG.getBitcast(ShVT, ShAmt);
16313   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16314 }
16315
16316 /// \brief Return Mask with the necessary casting or extending
16317 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16318 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16319                            const X86Subtarget *Subtarget,
16320                            SelectionDAG &DAG, SDLoc dl) {
16321
16322   if (isAllOnesConstant(Mask))
16323     return DAG.getTargetConstant(1, dl, MaskVT);
16324   if (X86::isZeroNode(Mask))
16325     return DAG.getTargetConstant(0, dl, MaskVT);
16326
16327   if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16328     // Mask should be extended
16329     Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16330                        MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16331   }
16332
16333   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16334     if (MaskVT == MVT::v64i1) {
16335       assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16336       // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16337       SDValue Lo, Hi;
16338       Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16339                           DAG.getConstant(0, dl, MVT::i32));
16340       Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16341                           DAG.getConstant(1, dl, MVT::i32));
16342
16343       Lo = DAG.getBitcast(MVT::v32i1, Lo);
16344       Hi = DAG.getBitcast(MVT::v32i1, Hi);
16345
16346       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16347     } else {
16348       // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16349       // and bitcast.
16350       MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16351       return DAG.getBitcast(MaskVT,
16352                             DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16353     }
16354
16355   } else {
16356     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16357                                      Mask.getSimpleValueType().getSizeInBits());
16358     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16359     // are extracted by EXTRACT_SUBVECTOR.
16360     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16361                        DAG.getBitcast(BitcastVT, Mask),
16362                        DAG.getIntPtrConstant(0, dl));
16363   }
16364 }
16365
16366 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16367 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16368 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16369 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16370                   SDValue PreservedSrc,
16371                   const X86Subtarget *Subtarget,
16372                   SelectionDAG &DAG) {
16373   MVT VT = Op.getSimpleValueType();
16374   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16375   unsigned OpcodeSelect = ISD::VSELECT;
16376   SDLoc dl(Op);
16377
16378   if (isAllOnesConstant(Mask))
16379     return Op;
16380
16381   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16382
16383   switch (Op.getOpcode()) {
16384   default: break;
16385   case X86ISD::PCMPEQM:
16386   case X86ISD::PCMPGTM:
16387   case X86ISD::CMPM:
16388   case X86ISD::CMPMU:
16389     return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16390   case X86ISD::VFPCLASS:
16391     case X86ISD::VFPCLASSS:
16392     return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16393   case X86ISD::VTRUNC:
16394   case X86ISD::VTRUNCS:
16395   case X86ISD::VTRUNCUS:
16396     // We can't use ISD::VSELECT here because it is not always "Legal"
16397     // for the destination type. For example vpmovqb require only AVX512
16398     // and vselect that can operate on byte element type require BWI
16399     OpcodeSelect = X86ISD::SELECT;
16400     break;
16401   }
16402   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16403     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16404   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16405 }
16406
16407 /// \brief Creates an SDNode for a predicated scalar operation.
16408 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16409 /// The mask is coming as MVT::i8 and it should be truncated
16410 /// to MVT::i1 while lowering masking intrinsics.
16411 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16412 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16413 /// for a scalar instruction.
16414 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16415                                     SDValue PreservedSrc,
16416                                     const X86Subtarget *Subtarget,
16417                                     SelectionDAG &DAG) {
16418   if (isAllOnesConstant(Mask))
16419     return Op;
16420
16421   MVT VT = Op.getSimpleValueType();
16422   SDLoc dl(Op);
16423   // The mask should be of type MVT::i1
16424   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16425
16426   if (Op.getOpcode() == X86ISD::FSETCC)
16427     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16428   if (Op.getOpcode() == X86ISD::VFPCLASS ||
16429       Op.getOpcode() == X86ISD::VFPCLASSS)
16430     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16431
16432   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16433     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16434   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16435 }
16436
16437 static int getSEHRegistrationNodeSize(const Function *Fn) {
16438   if (!Fn->hasPersonalityFn())
16439     report_fatal_error(
16440         "querying registration node size for function without personality");
16441   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16442   // WinEHStatePass for the full struct definition.
16443   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16444   case EHPersonality::MSVC_X86SEH: return 24;
16445   case EHPersonality::MSVC_CXX: return 16;
16446   default: break;
16447   }
16448   report_fatal_error(
16449       "can only recover FP for 32-bit MSVC EH personality functions");
16450 }
16451
16452 /// When the MSVC runtime transfers control to us, either to an outlined
16453 /// function or when returning to a parent frame after catching an exception, we
16454 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16455 /// Here's the math:
16456 ///   RegNodeBase = EntryEBP - RegNodeSize
16457 ///   ParentFP = RegNodeBase - ParentFrameOffset
16458 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16459 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16460 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16461                                    SDValue EntryEBP) {
16462   MachineFunction &MF = DAG.getMachineFunction();
16463   SDLoc dl;
16464
16465   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16466   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16467
16468   // It's possible that the parent function no longer has a personality function
16469   // if the exceptional code was optimized away, in which case we just return
16470   // the incoming EBP.
16471   if (!Fn->hasPersonalityFn())
16472     return EntryEBP;
16473
16474   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16475   // registration, or the .set_setframe offset.
16476   MCSymbol *OffsetSym =
16477       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16478           GlobalValue::getRealLinkageName(Fn->getName()));
16479   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16480   SDValue ParentFrameOffset =
16481       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16482
16483   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
16484   // prologue to RBP in the parent function.
16485   const X86Subtarget &Subtarget =
16486       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16487   if (Subtarget.is64Bit())
16488     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
16489
16490   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16491   // RegNodeBase = EntryEBP - RegNodeSize
16492   // ParentFP = RegNodeBase - ParentFrameOffset
16493   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16494                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16495   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
16496 }
16497
16498 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16499                                        SelectionDAG &DAG) {
16500   SDLoc dl(Op);
16501   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16502   MVT VT = Op.getSimpleValueType();
16503   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16504   if (IntrData) {
16505     switch(IntrData->Type) {
16506     case INTR_TYPE_1OP:
16507       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16508     case INTR_TYPE_2OP:
16509       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16510         Op.getOperand(2));
16511     case INTR_TYPE_2OP_IMM8:
16512       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16513                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16514     case INTR_TYPE_3OP:
16515       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16516         Op.getOperand(2), Op.getOperand(3));
16517     case INTR_TYPE_4OP:
16518       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16519         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16520     case INTR_TYPE_1OP_MASK_RM: {
16521       SDValue Src = Op.getOperand(1);
16522       SDValue PassThru = Op.getOperand(2);
16523       SDValue Mask = Op.getOperand(3);
16524       SDValue RoundingMode;
16525       // We allways add rounding mode to the Node.
16526       // If the rounding mode is not specified, we add the
16527       // "current direction" mode.
16528       if (Op.getNumOperands() == 4)
16529         RoundingMode =
16530           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16531       else
16532         RoundingMode = Op.getOperand(4);
16533       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16534       if (IntrWithRoundingModeOpcode != 0)
16535         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16536             X86::STATIC_ROUNDING::CUR_DIRECTION)
16537           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16538                                       dl, Op.getValueType(), Src, RoundingMode),
16539                                       Mask, PassThru, Subtarget, DAG);
16540       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16541                                               RoundingMode),
16542                                   Mask, PassThru, Subtarget, DAG);
16543     }
16544     case INTR_TYPE_1OP_MASK: {
16545       SDValue Src = Op.getOperand(1);
16546       SDValue PassThru = Op.getOperand(2);
16547       SDValue Mask = Op.getOperand(3);
16548       // We add rounding mode to the Node when
16549       //   - RM Opcode is specified and
16550       //   - RM is not "current direction".
16551       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16552       if (IntrWithRoundingModeOpcode != 0) {
16553         SDValue Rnd = Op.getOperand(4);
16554         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16555         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16556           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16557                                       dl, Op.getValueType(),
16558                                       Src, Rnd),
16559                                       Mask, PassThru, Subtarget, DAG);
16560         }
16561       }
16562       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16563                                   Mask, PassThru, Subtarget, DAG);
16564     }
16565     case INTR_TYPE_SCALAR_MASK: {
16566       SDValue Src1 = Op.getOperand(1);
16567       SDValue Src2 = Op.getOperand(2);
16568       SDValue passThru = Op.getOperand(3);
16569       SDValue Mask = Op.getOperand(4);
16570       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16571                                   Mask, passThru, Subtarget, DAG);
16572     }
16573     case INTR_TYPE_SCALAR_MASK_RM: {
16574       SDValue Src1 = Op.getOperand(1);
16575       SDValue Src2 = Op.getOperand(2);
16576       SDValue Src0 = Op.getOperand(3);
16577       SDValue Mask = Op.getOperand(4);
16578       // There are 2 kinds of intrinsics in this group:
16579       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16580       // (2) With rounding mode and sae - 7 operands.
16581       if (Op.getNumOperands() == 6) {
16582         SDValue Sae  = Op.getOperand(5);
16583         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16584         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16585                                                 Sae),
16586                                     Mask, Src0, Subtarget, DAG);
16587       }
16588       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16589       SDValue RoundingMode  = Op.getOperand(5);
16590       SDValue Sae  = Op.getOperand(6);
16591       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16592                                               RoundingMode, Sae),
16593                                   Mask, Src0, Subtarget, DAG);
16594     }
16595     case INTR_TYPE_2OP_MASK:
16596     case INTR_TYPE_2OP_IMM8_MASK: {
16597       SDValue Src1 = Op.getOperand(1);
16598       SDValue Src2 = Op.getOperand(2);
16599       SDValue PassThru = Op.getOperand(3);
16600       SDValue Mask = Op.getOperand(4);
16601
16602       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16603         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16604
16605       // We specify 2 possible opcodes for intrinsics with rounding modes.
16606       // First, we check if the intrinsic may have non-default rounding mode,
16607       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16608       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16609       if (IntrWithRoundingModeOpcode != 0) {
16610         SDValue Rnd = Op.getOperand(5);
16611         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16612         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16613           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16614                                       dl, Op.getValueType(),
16615                                       Src1, Src2, Rnd),
16616                                       Mask, PassThru, Subtarget, DAG);
16617         }
16618       }
16619       // TODO: Intrinsics should have fast-math-flags to propagate.
16620       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16621                                   Mask, PassThru, Subtarget, DAG);
16622     }
16623     case INTR_TYPE_2OP_MASK_RM: {
16624       SDValue Src1 = Op.getOperand(1);
16625       SDValue Src2 = Op.getOperand(2);
16626       SDValue PassThru = Op.getOperand(3);
16627       SDValue Mask = Op.getOperand(4);
16628       // We specify 2 possible modes for intrinsics, with/without rounding
16629       // modes.
16630       // First, we check if the intrinsic have rounding mode (6 operands),
16631       // if not, we set rounding mode to "current".
16632       SDValue Rnd;
16633       if (Op.getNumOperands() == 6)
16634         Rnd = Op.getOperand(5);
16635       else
16636         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16637       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16638                                               Src1, Src2, Rnd),
16639                                   Mask, PassThru, Subtarget, DAG);
16640     }
16641     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16642       SDValue Src1 = Op.getOperand(1);
16643       SDValue Src2 = Op.getOperand(2);
16644       SDValue Src3 = Op.getOperand(3);
16645       SDValue PassThru = Op.getOperand(4);
16646       SDValue Mask = Op.getOperand(5);
16647       SDValue Sae  = Op.getOperand(6);
16648
16649       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16650                                               Src2, Src3, Sae),
16651                                   Mask, PassThru, Subtarget, DAG);
16652     }
16653     case INTR_TYPE_3OP_MASK_RM: {
16654       SDValue Src1 = Op.getOperand(1);
16655       SDValue Src2 = Op.getOperand(2);
16656       SDValue Imm = Op.getOperand(3);
16657       SDValue PassThru = Op.getOperand(4);
16658       SDValue Mask = Op.getOperand(5);
16659       // We specify 2 possible modes for intrinsics, with/without rounding
16660       // modes.
16661       // First, we check if the intrinsic have rounding mode (7 operands),
16662       // if not, we set rounding mode to "current".
16663       SDValue Rnd;
16664       if (Op.getNumOperands() == 7)
16665         Rnd = Op.getOperand(6);
16666       else
16667         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16668       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16669         Src1, Src2, Imm, Rnd),
16670         Mask, PassThru, Subtarget, DAG);
16671     }
16672     case INTR_TYPE_3OP_IMM8_MASK:
16673     case INTR_TYPE_3OP_MASK:
16674     case INSERT_SUBVEC: {
16675       SDValue Src1 = Op.getOperand(1);
16676       SDValue Src2 = Op.getOperand(2);
16677       SDValue Src3 = Op.getOperand(3);
16678       SDValue PassThru = Op.getOperand(4);
16679       SDValue Mask = Op.getOperand(5);
16680
16681       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16682         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16683       else if (IntrData->Type == INSERT_SUBVEC) {
16684         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16685         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16686         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16687         Imm *= Src2.getSimpleValueType().getVectorNumElements();
16688         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16689       }
16690
16691       // We specify 2 possible opcodes for intrinsics with rounding modes.
16692       // First, we check if the intrinsic may have non-default rounding mode,
16693       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16694       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16695       if (IntrWithRoundingModeOpcode != 0) {
16696         SDValue Rnd = Op.getOperand(6);
16697         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16698         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16699           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16700                                       dl, Op.getValueType(),
16701                                       Src1, Src2, Src3, Rnd),
16702                                       Mask, PassThru, Subtarget, DAG);
16703         }
16704       }
16705       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16706                                               Src1, Src2, Src3),
16707                                   Mask, PassThru, Subtarget, DAG);
16708     }
16709     case VPERM_3OP_MASKZ:
16710     case VPERM_3OP_MASK:{
16711       // Src2 is the PassThru
16712       SDValue Src1 = Op.getOperand(1);
16713       SDValue Src2 = Op.getOperand(2);
16714       SDValue Src3 = Op.getOperand(3);
16715       SDValue Mask = Op.getOperand(4);
16716       MVT VT = Op.getSimpleValueType();
16717       SDValue PassThru = SDValue();
16718
16719       // set PassThru element
16720       if (IntrData->Type == VPERM_3OP_MASKZ)
16721         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16722       else
16723         PassThru = DAG.getBitcast(VT, Src2);
16724
16725       // Swap Src1 and Src2 in the node creation
16726       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16727                                               dl, Op.getValueType(),
16728                                               Src2, Src1, Src3),
16729                                   Mask, PassThru, Subtarget, DAG);
16730     }
16731     case FMA_OP_MASK3:
16732     case FMA_OP_MASKZ:
16733     case FMA_OP_MASK: {
16734       SDValue Src1 = Op.getOperand(1);
16735       SDValue Src2 = Op.getOperand(2);
16736       SDValue Src3 = Op.getOperand(3);
16737       SDValue Mask = Op.getOperand(4);
16738       MVT VT = Op.getSimpleValueType();
16739       SDValue PassThru = SDValue();
16740
16741       // set PassThru element
16742       if (IntrData->Type == FMA_OP_MASKZ)
16743         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16744       else if (IntrData->Type == FMA_OP_MASK3)
16745         PassThru = Src3;
16746       else
16747         PassThru = Src1;
16748
16749       // We specify 2 possible opcodes for intrinsics with rounding modes.
16750       // First, we check if the intrinsic may have non-default rounding mode,
16751       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16752       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16753       if (IntrWithRoundingModeOpcode != 0) {
16754         SDValue Rnd = Op.getOperand(5);
16755         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16756             X86::STATIC_ROUNDING::CUR_DIRECTION)
16757           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16758                                                   dl, Op.getValueType(),
16759                                                   Src1, Src2, Src3, Rnd),
16760                                       Mask, PassThru, Subtarget, DAG);
16761       }
16762       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16763                                               dl, Op.getValueType(),
16764                                               Src1, Src2, Src3),
16765                                   Mask, PassThru, Subtarget, DAG);
16766     }
16767     case TERLOG_OP_MASK:
16768     case TERLOG_OP_MASKZ: {
16769       SDValue Src1 = Op.getOperand(1);
16770       SDValue Src2 = Op.getOperand(2);
16771       SDValue Src3 = Op.getOperand(3);
16772       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16773       SDValue Mask = Op.getOperand(5);
16774       MVT VT = Op.getSimpleValueType();
16775       SDValue PassThru = Src1;
16776       // Set PassThru element.
16777       if (IntrData->Type == TERLOG_OP_MASKZ)
16778         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16779
16780       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16781                                               Src1, Src2, Src3, Src4),
16782                                   Mask, PassThru, Subtarget, DAG);
16783     }
16784     case FPCLASS: {
16785       // FPclass intrinsics with mask
16786        SDValue Src1 = Op.getOperand(1);
16787        MVT VT = Src1.getSimpleValueType();
16788        MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16789        SDValue Imm = Op.getOperand(2);
16790        SDValue Mask = Op.getOperand(3);
16791        MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16792                                      Mask.getSimpleValueType().getSizeInBits());
16793        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16794        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16795                                                  DAG.getTargetConstant(0, dl, MaskVT),
16796                                                  Subtarget, DAG);
16797        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16798                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16799                                  DAG.getIntPtrConstant(0, dl));
16800        return DAG.getBitcast(Op.getValueType(), Res);
16801     }
16802     case FPCLASSS: {
16803       SDValue Src1 = Op.getOperand(1);
16804       SDValue Imm = Op.getOperand(2);
16805       SDValue Mask = Op.getOperand(3);
16806       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16807       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16808         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16809       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16810     }
16811     case CMP_MASK:
16812     case CMP_MASK_CC: {
16813       // Comparison intrinsics with masks.
16814       // Example of transformation:
16815       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16816       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16817       // (i8 (bitcast
16818       //   (v8i1 (insert_subvector undef,
16819       //           (v2i1 (and (PCMPEQM %a, %b),
16820       //                      (extract_subvector
16821       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16822       MVT VT = Op.getOperand(1).getSimpleValueType();
16823       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16824       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16825       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16826                                        Mask.getSimpleValueType().getSizeInBits());
16827       SDValue Cmp;
16828       if (IntrData->Type == CMP_MASK_CC) {
16829         SDValue CC = Op.getOperand(3);
16830         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16831         // We specify 2 possible opcodes for intrinsics with rounding modes.
16832         // First, we check if the intrinsic may have non-default rounding mode,
16833         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16834         if (IntrData->Opc1 != 0) {
16835           SDValue Rnd = Op.getOperand(5);
16836           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16837               X86::STATIC_ROUNDING::CUR_DIRECTION)
16838             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16839                               Op.getOperand(2), CC, Rnd);
16840         }
16841         //default rounding mode
16842         if(!Cmp.getNode())
16843             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16844                               Op.getOperand(2), CC);
16845
16846       } else {
16847         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16848         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16849                           Op.getOperand(2));
16850       }
16851       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16852                                              DAG.getTargetConstant(0, dl,
16853                                                                    MaskVT),
16854                                              Subtarget, DAG);
16855       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16856                                 DAG.getUNDEF(BitcastVT), CmpMask,
16857                                 DAG.getIntPtrConstant(0, dl));
16858       return DAG.getBitcast(Op.getValueType(), Res);
16859     }
16860     case CMP_MASK_SCALAR_CC: {
16861       SDValue Src1 = Op.getOperand(1);
16862       SDValue Src2 = Op.getOperand(2);
16863       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16864       SDValue Mask = Op.getOperand(4);
16865
16866       SDValue Cmp;
16867       if (IntrData->Opc1 != 0) {
16868         SDValue Rnd = Op.getOperand(5);
16869         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16870             X86::STATIC_ROUNDING::CUR_DIRECTION)
16871           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16872       }
16873       //default rounding mode
16874       if(!Cmp.getNode())
16875         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16876
16877       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16878                                              DAG.getTargetConstant(0, dl,
16879                                                                    MVT::i1),
16880                                              Subtarget, DAG);
16881
16882       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16883                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16884                          DAG.getValueType(MVT::i1));
16885     }
16886     case COMI: { // Comparison intrinsics
16887       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16888       SDValue LHS = Op.getOperand(1);
16889       SDValue RHS = Op.getOperand(2);
16890       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16891       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16892       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16893       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16894                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16895       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16896     }
16897     case COMI_RM: { // Comparison intrinsics with Sae
16898       SDValue LHS = Op.getOperand(1);
16899       SDValue RHS = Op.getOperand(2);
16900       SDValue CC = Op.getOperand(3);
16901       SDValue Sae = Op.getOperand(4);
16902       auto ComiType = TranslateX86ConstCondToX86CC(CC);
16903       // choose between ordered and unordered (comi/ucomi)
16904       unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16905       SDValue Cond;
16906       if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16907                                            X86::STATIC_ROUNDING::CUR_DIRECTION)
16908         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16909       else
16910         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16911       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16912         DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16913       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16914     }
16915     case VSHIFT:
16916       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16917                                  Op.getOperand(1), Op.getOperand(2), DAG);
16918     case VSHIFT_MASK:
16919       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16920                                                       Op.getSimpleValueType(),
16921                                                       Op.getOperand(1),
16922                                                       Op.getOperand(2), DAG),
16923                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16924                                   DAG);
16925     case COMPRESS_EXPAND_IN_REG: {
16926       SDValue Mask = Op.getOperand(3);
16927       SDValue DataToCompress = Op.getOperand(1);
16928       SDValue PassThru = Op.getOperand(2);
16929       if (isAllOnesConstant(Mask)) // return data as is
16930         return Op.getOperand(1);
16931
16932       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16933                                               DataToCompress),
16934                                   Mask, PassThru, Subtarget, DAG);
16935     }
16936     case BROADCASTM: {
16937       SDValue Mask = Op.getOperand(1);
16938       MVT MaskVT = MVT::getVectorVT(MVT::i1,
16939                                     Mask.getSimpleValueType().getSizeInBits());
16940       Mask = DAG.getBitcast(MaskVT, Mask);
16941       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16942     }
16943     case BLEND: {
16944       SDValue Mask = Op.getOperand(3);
16945       MVT VT = Op.getSimpleValueType();
16946       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16947       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16948       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16949                          Op.getOperand(2));
16950     }
16951     case KUNPCK: {
16952       MVT VT = Op.getSimpleValueType();
16953       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16954
16955       SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16956       SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16957       // Arguments should be swapped.
16958       SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16959                                 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16960                                 Src2, Src1);
16961       return DAG.getBitcast(VT, Res);
16962     }
16963     case CONVERT_TO_MASK: {
16964       MVT SrcVT = Op.getOperand(1).getSimpleValueType();
16965       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
16966       MVT BitcastVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits());
16967
16968       SDValue CvtMask = DAG.getNode(IntrData->Opc0, dl, MaskVT,
16969                                     Op.getOperand(1));
16970       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16971                                 DAG.getUNDEF(BitcastVT), CvtMask,
16972                                 DAG.getIntPtrConstant(0, dl));
16973       return DAG.getBitcast(Op.getValueType(), Res);
16974     }
16975     case CONVERT_MASK_TO_VEC: {
16976       SDValue Mask = Op.getOperand(1);
16977       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16978       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16979       return DAG.getNode(IntrData->Opc0, dl, VT, VMask);
16980     }
16981     case BRCST_SUBVEC_TO_VEC: {
16982       SDValue Src = Op.getOperand(1);
16983       SDValue Passthru = Op.getOperand(2);
16984       SDValue Mask = Op.getOperand(3);
16985       EVT resVT = Passthru.getValueType();
16986       SDValue subVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, resVT,
16987                                        DAG.getUNDEF(resVT), Src,
16988                                        DAG.getIntPtrConstant(0, dl));
16989       SDValue immVal;
16990       if (Src.getSimpleValueType().is256BitVector() && resVT.is512BitVector())
16991         immVal = DAG.getConstant(0x44, dl, MVT::i8);
16992       else
16993         immVal = DAG.getConstant(0, dl, MVT::i8);
16994       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16995                                               subVec, subVec, immVal),
16996                                   Mask, Passthru, Subtarget, DAG);
16997     }
16998     default:
16999       break;
17000     }
17001   }
17002
17003   switch (IntNo) {
17004   default: return SDValue();    // Don't custom lower most intrinsics.
17005
17006   case Intrinsic::x86_avx2_permd:
17007   case Intrinsic::x86_avx2_permps:
17008     // Operands intentionally swapped. Mask is last operand to intrinsic,
17009     // but second operand for node/instruction.
17010     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
17011                        Op.getOperand(2), Op.getOperand(1));
17012
17013   // ptest and testp intrinsics. The intrinsic these come from are designed to
17014   // return an integer value, not just an instruction so lower it to the ptest
17015   // or testp pattern and a setcc for the result.
17016   case Intrinsic::x86_sse41_ptestz:
17017   case Intrinsic::x86_sse41_ptestc:
17018   case Intrinsic::x86_sse41_ptestnzc:
17019   case Intrinsic::x86_avx_ptestz_256:
17020   case Intrinsic::x86_avx_ptestc_256:
17021   case Intrinsic::x86_avx_ptestnzc_256:
17022   case Intrinsic::x86_avx_vtestz_ps:
17023   case Intrinsic::x86_avx_vtestc_ps:
17024   case Intrinsic::x86_avx_vtestnzc_ps:
17025   case Intrinsic::x86_avx_vtestz_pd:
17026   case Intrinsic::x86_avx_vtestc_pd:
17027   case Intrinsic::x86_avx_vtestnzc_pd:
17028   case Intrinsic::x86_avx_vtestz_ps_256:
17029   case Intrinsic::x86_avx_vtestc_ps_256:
17030   case Intrinsic::x86_avx_vtestnzc_ps_256:
17031   case Intrinsic::x86_avx_vtestz_pd_256:
17032   case Intrinsic::x86_avx_vtestc_pd_256:
17033   case Intrinsic::x86_avx_vtestnzc_pd_256: {
17034     bool IsTestPacked = false;
17035     unsigned X86CC;
17036     switch (IntNo) {
17037     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
17038     case Intrinsic::x86_avx_vtestz_ps:
17039     case Intrinsic::x86_avx_vtestz_pd:
17040     case Intrinsic::x86_avx_vtestz_ps_256:
17041     case Intrinsic::x86_avx_vtestz_pd_256:
17042       IsTestPacked = true; // Fallthrough
17043     case Intrinsic::x86_sse41_ptestz:
17044     case Intrinsic::x86_avx_ptestz_256:
17045       // ZF = 1
17046       X86CC = X86::COND_E;
17047       break;
17048     case Intrinsic::x86_avx_vtestc_ps:
17049     case Intrinsic::x86_avx_vtestc_pd:
17050     case Intrinsic::x86_avx_vtestc_ps_256:
17051     case Intrinsic::x86_avx_vtestc_pd_256:
17052       IsTestPacked = true; // Fallthrough
17053     case Intrinsic::x86_sse41_ptestc:
17054     case Intrinsic::x86_avx_ptestc_256:
17055       // CF = 1
17056       X86CC = X86::COND_B;
17057       break;
17058     case Intrinsic::x86_avx_vtestnzc_ps:
17059     case Intrinsic::x86_avx_vtestnzc_pd:
17060     case Intrinsic::x86_avx_vtestnzc_ps_256:
17061     case Intrinsic::x86_avx_vtestnzc_pd_256:
17062       IsTestPacked = true; // Fallthrough
17063     case Intrinsic::x86_sse41_ptestnzc:
17064     case Intrinsic::x86_avx_ptestnzc_256:
17065       // ZF and CF = 0
17066       X86CC = X86::COND_A;
17067       break;
17068     }
17069
17070     SDValue LHS = Op.getOperand(1);
17071     SDValue RHS = Op.getOperand(2);
17072     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17073     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17074     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17075     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17076     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17077   }
17078   case Intrinsic::x86_avx512_kortestz_w:
17079   case Intrinsic::x86_avx512_kortestc_w: {
17080     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17081     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
17082     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
17083     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17084     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17085     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17086     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17087   }
17088
17089   case Intrinsic::x86_sse42_pcmpistria128:
17090   case Intrinsic::x86_sse42_pcmpestria128:
17091   case Intrinsic::x86_sse42_pcmpistric128:
17092   case Intrinsic::x86_sse42_pcmpestric128:
17093   case Intrinsic::x86_sse42_pcmpistrio128:
17094   case Intrinsic::x86_sse42_pcmpestrio128:
17095   case Intrinsic::x86_sse42_pcmpistris128:
17096   case Intrinsic::x86_sse42_pcmpestris128:
17097   case Intrinsic::x86_sse42_pcmpistriz128:
17098   case Intrinsic::x86_sse42_pcmpestriz128: {
17099     unsigned Opcode;
17100     unsigned X86CC;
17101     switch (IntNo) {
17102     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17103     case Intrinsic::x86_sse42_pcmpistria128:
17104       Opcode = X86ISD::PCMPISTRI;
17105       X86CC = X86::COND_A;
17106       break;
17107     case Intrinsic::x86_sse42_pcmpestria128:
17108       Opcode = X86ISD::PCMPESTRI;
17109       X86CC = X86::COND_A;
17110       break;
17111     case Intrinsic::x86_sse42_pcmpistric128:
17112       Opcode = X86ISD::PCMPISTRI;
17113       X86CC = X86::COND_B;
17114       break;
17115     case Intrinsic::x86_sse42_pcmpestric128:
17116       Opcode = X86ISD::PCMPESTRI;
17117       X86CC = X86::COND_B;
17118       break;
17119     case Intrinsic::x86_sse42_pcmpistrio128:
17120       Opcode = X86ISD::PCMPISTRI;
17121       X86CC = X86::COND_O;
17122       break;
17123     case Intrinsic::x86_sse42_pcmpestrio128:
17124       Opcode = X86ISD::PCMPESTRI;
17125       X86CC = X86::COND_O;
17126       break;
17127     case Intrinsic::x86_sse42_pcmpistris128:
17128       Opcode = X86ISD::PCMPISTRI;
17129       X86CC = X86::COND_S;
17130       break;
17131     case Intrinsic::x86_sse42_pcmpestris128:
17132       Opcode = X86ISD::PCMPESTRI;
17133       X86CC = X86::COND_S;
17134       break;
17135     case Intrinsic::x86_sse42_pcmpistriz128:
17136       Opcode = X86ISD::PCMPISTRI;
17137       X86CC = X86::COND_E;
17138       break;
17139     case Intrinsic::x86_sse42_pcmpestriz128:
17140       Opcode = X86ISD::PCMPESTRI;
17141       X86CC = X86::COND_E;
17142       break;
17143     }
17144     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17145     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17146     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17147     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17148                                 DAG.getConstant(X86CC, dl, MVT::i8),
17149                                 SDValue(PCMP.getNode(), 1));
17150     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17151   }
17152
17153   case Intrinsic::x86_sse42_pcmpistri128:
17154   case Intrinsic::x86_sse42_pcmpestri128: {
17155     unsigned Opcode;
17156     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17157       Opcode = X86ISD::PCMPISTRI;
17158     else
17159       Opcode = X86ISD::PCMPESTRI;
17160
17161     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17162     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17163     return DAG.getNode(Opcode, dl, VTs, NewOps);
17164   }
17165
17166   case Intrinsic::x86_seh_lsda: {
17167     // Compute the symbol for the LSDA. We know it'll get emitted later.
17168     MachineFunction &MF = DAG.getMachineFunction();
17169     SDValue Op1 = Op.getOperand(1);
17170     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
17171     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
17172         GlobalValue::getRealLinkageName(Fn->getName()));
17173
17174     // Generate a simple absolute symbol reference. This intrinsic is only
17175     // supported on 32-bit Windows, which isn't PIC.
17176     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
17177     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
17178   }
17179
17180   case Intrinsic::x86_seh_recoverfp: {
17181     SDValue FnOp = Op.getOperand(1);
17182     SDValue IncomingFPOp = Op.getOperand(2);
17183     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
17184     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
17185     if (!Fn)
17186       report_fatal_error(
17187           "llvm.x86.seh.recoverfp must take a function as the first argument");
17188     return recoverFramePointer(DAG, Fn, IncomingFPOp);
17189   }
17190
17191   case Intrinsic::localaddress: {
17192     // Returns one of the stack, base, or frame pointer registers, depending on
17193     // which is used to reference local variables.
17194     MachineFunction &MF = DAG.getMachineFunction();
17195     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17196     unsigned Reg;
17197     if (RegInfo->hasBasePointer(MF))
17198       Reg = RegInfo->getBaseRegister();
17199     else // This function handles the SP or FP case.
17200       Reg = RegInfo->getPtrSizedFrameRegister(MF);
17201     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
17202   }
17203   }
17204 }
17205
17206 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17207                               SDValue Src, SDValue Mask, SDValue Base,
17208                               SDValue Index, SDValue ScaleOp, SDValue Chain,
17209                               const X86Subtarget * Subtarget) {
17210   SDLoc dl(Op);
17211   auto *C = cast<ConstantSDNode>(ScaleOp);
17212   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17213   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17214                              Index.getSimpleValueType().getVectorNumElements());
17215
17216   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
17217   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17218   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17219   SDValue Segment = DAG.getRegister(0, MVT::i32);
17220   if (Src.getOpcode() == ISD::UNDEF)
17221     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
17222   SDValue Ops[] = {Src, VMask, Base, Scale, Index, Disp, Segment, Chain};
17223   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17224   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17225   return DAG.getMergeValues(RetOps, dl);
17226 }
17227
17228 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17229                                SDValue Src, SDValue Mask, SDValue Base,
17230                                SDValue Index, SDValue ScaleOp, SDValue Chain,
17231                                const X86Subtarget &Subtarget) {
17232   SDLoc dl(Op);
17233   auto *C = cast<ConstantSDNode>(ScaleOp);
17234   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17235   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17236   SDValue Segment = DAG.getRegister(0, MVT::i32);
17237   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17238                              Index.getSimpleValueType().getVectorNumElements());
17239
17240   SDValue VMask = getMaskNode(Mask, MaskVT, &Subtarget, DAG, dl);
17241   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17242   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, VMask, Src, Chain};
17243   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17244   return SDValue(Res, 1);
17245 }
17246
17247 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17248                                SDValue Mask, SDValue Base, SDValue Index,
17249                                SDValue ScaleOp, SDValue Chain,
17250                                const X86Subtarget &Subtarget) {
17251   SDLoc dl(Op);
17252   auto *C = cast<ConstantSDNode>(ScaleOp);
17253   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17254   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17255   SDValue Segment = DAG.getRegister(0, MVT::i32);
17256   MVT MaskVT =
17257     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17258   SDValue VMask = getMaskNode(Mask, MaskVT, &Subtarget, DAG, dl);
17259   //SDVTList VTs = DAG.getVTList(MVT::Other);
17260   SDValue Ops[] = {VMask, Base, Scale, Index, Disp, Segment, Chain};
17261   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17262   return SDValue(Res, 0);
17263 }
17264
17265 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17266 // read performance monitor counters (x86_rdpmc).
17267 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17268                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17269                               SmallVectorImpl<SDValue> &Results) {
17270   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17271   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17272   SDValue LO, HI;
17273
17274   // The ECX register is used to select the index of the performance counter
17275   // to read.
17276   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17277                                    N->getOperand(2));
17278   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17279
17280   // Reads the content of a 64-bit performance counter and returns it in the
17281   // registers EDX:EAX.
17282   if (Subtarget->is64Bit()) {
17283     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17284     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17285                             LO.getValue(2));
17286   } else {
17287     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17288     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17289                             LO.getValue(2));
17290   }
17291   Chain = HI.getValue(1);
17292
17293   if (Subtarget->is64Bit()) {
17294     // The EAX register is loaded with the low-order 32 bits. The EDX register
17295     // is loaded with the supported high-order bits of the counter.
17296     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17297                               DAG.getConstant(32, DL, MVT::i8));
17298     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17299     Results.push_back(Chain);
17300     return;
17301   }
17302
17303   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17304   SDValue Ops[] = { LO, HI };
17305   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17306   Results.push_back(Pair);
17307   Results.push_back(Chain);
17308 }
17309
17310 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17311 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17312 // also used to custom lower READCYCLECOUNTER nodes.
17313 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17314                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17315                               SmallVectorImpl<SDValue> &Results) {
17316   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17317   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17318   SDValue LO, HI;
17319
17320   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17321   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17322   // and the EAX register is loaded with the low-order 32 bits.
17323   if (Subtarget->is64Bit()) {
17324     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17325     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17326                             LO.getValue(2));
17327   } else {
17328     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17329     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17330                             LO.getValue(2));
17331   }
17332   SDValue Chain = HI.getValue(1);
17333
17334   if (Opcode == X86ISD::RDTSCP_DAG) {
17335     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17336
17337     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17338     // the ECX register. Add 'ecx' explicitly to the chain.
17339     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17340                                      HI.getValue(2));
17341     // Explicitly store the content of ECX at the location passed in input
17342     // to the 'rdtscp' intrinsic.
17343     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17344                          MachinePointerInfo(), false, false, 0);
17345   }
17346
17347   if (Subtarget->is64Bit()) {
17348     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17349     // the EAX register is loaded with the low-order 32 bits.
17350     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17351                               DAG.getConstant(32, DL, MVT::i8));
17352     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17353     Results.push_back(Chain);
17354     return;
17355   }
17356
17357   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17358   SDValue Ops[] = { LO, HI };
17359   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17360   Results.push_back(Pair);
17361   Results.push_back(Chain);
17362 }
17363
17364 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17365                                      SelectionDAG &DAG) {
17366   SmallVector<SDValue, 2> Results;
17367   SDLoc DL(Op);
17368   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17369                           Results);
17370   return DAG.getMergeValues(Results, DL);
17371 }
17372
17373 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17374   MachineFunction &MF = DAG.getMachineFunction();
17375   SDValue Chain = Op.getOperand(0);
17376   SDValue RegNode = Op.getOperand(2);
17377   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17378   if (!EHInfo)
17379     report_fatal_error("EH registrations only live in functions using WinEH");
17380
17381   // Cast the operand to an alloca, and remember the frame index.
17382   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17383   if (!FINode)
17384     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17385   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17386
17387   // Return the chain operand without making any DAG nodes.
17388   return Chain;
17389 }
17390
17391 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17392 /// return truncate Store/MaskedStore Node
17393 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17394                                                SelectionDAG &DAG,
17395                                                MVT ElementType) {
17396   SDLoc dl(Op);
17397   SDValue Mask = Op.getOperand(4);
17398   SDValue DataToTruncate = Op.getOperand(3);
17399   SDValue Addr = Op.getOperand(2);
17400   SDValue Chain = Op.getOperand(0);
17401
17402   MVT VT  = DataToTruncate.getSimpleValueType();
17403   MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17404
17405   if (isAllOnesConstant(Mask)) // return just a truncate store
17406     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17407                              MachinePointerInfo(), SVT, false, false,
17408                              SVT.getScalarSizeInBits()/8);
17409
17410   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17411   MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17412                                    Mask.getSimpleValueType().getSizeInBits());
17413   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17414   // are extracted by EXTRACT_SUBVECTOR.
17415   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17416                               DAG.getBitcast(BitcastVT, Mask),
17417                               DAG.getIntPtrConstant(0, dl));
17418
17419   MachineMemOperand *MMO = DAG.getMachineFunction().
17420     getMachineMemOperand(MachinePointerInfo(),
17421                          MachineMemOperand::MOStore, SVT.getStoreSize(),
17422                          SVT.getScalarSizeInBits()/8);
17423
17424   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17425                             VMask, SVT, MMO, true);
17426 }
17427
17428 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17429                                       SelectionDAG &DAG) {
17430   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17431
17432   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17433   if (!IntrData) {
17434     if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17435       return MarkEHRegistrationNode(Op, DAG);
17436     if (IntNo == llvm::Intrinsic::x86_flags_read_u32 ||
17437         IntNo == llvm::Intrinsic::x86_flags_read_u64 ||
17438         IntNo == llvm::Intrinsic::x86_flags_write_u32 ||
17439         IntNo == llvm::Intrinsic::x86_flags_write_u64) {
17440       // We need a frame pointer because this will get lowered to a PUSH/POP
17441       // sequence.
17442       MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17443       MFI->setHasCopyImplyingStackAdjustment(true);
17444       // Don't do anything here, we will expand these intrinsics out later
17445       // during ExpandISelPseudos in EmitInstrWithCustomInserter.
17446       return SDValue();
17447     }
17448     return SDValue();
17449   }
17450
17451   SDLoc dl(Op);
17452   switch(IntrData->Type) {
17453   default: llvm_unreachable("Unknown Intrinsic Type");
17454   case RDSEED:
17455   case RDRAND: {
17456     // Emit the node with the right value type.
17457     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17458     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17459
17460     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17461     // Otherwise return the value from Rand, which is always 0, casted to i32.
17462     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17463                       DAG.getConstant(1, dl, Op->getValueType(1)),
17464                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
17465                       SDValue(Result.getNode(), 1) };
17466     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17467                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17468                                   Ops);
17469
17470     // Return { result, isValid, chain }.
17471     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17472                        SDValue(Result.getNode(), 2));
17473   }
17474   case GATHER: {
17475   //gather(v1, mask, index, base, scale);
17476     SDValue Chain = Op.getOperand(0);
17477     SDValue Src   = Op.getOperand(2);
17478     SDValue Base  = Op.getOperand(3);
17479     SDValue Index = Op.getOperand(4);
17480     SDValue Mask  = Op.getOperand(5);
17481     SDValue Scale = Op.getOperand(6);
17482     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17483                          Chain, Subtarget);
17484   }
17485   case SCATTER: {
17486   //scatter(base, mask, index, v1, scale);
17487     SDValue Chain = Op.getOperand(0);
17488     SDValue Base  = Op.getOperand(2);
17489     SDValue Mask  = Op.getOperand(3);
17490     SDValue Index = Op.getOperand(4);
17491     SDValue Src   = Op.getOperand(5);
17492     SDValue Scale = Op.getOperand(6);
17493     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17494                           Scale, Chain, *Subtarget);
17495   }
17496   case PREFETCH: {
17497     SDValue Hint = Op.getOperand(6);
17498     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17499     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17500     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17501     SDValue Chain = Op.getOperand(0);
17502     SDValue Mask  = Op.getOperand(2);
17503     SDValue Index = Op.getOperand(3);
17504     SDValue Base  = Op.getOperand(4);
17505     SDValue Scale = Op.getOperand(5);
17506     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain,
17507                            *Subtarget);
17508   }
17509   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17510   case RDTSC: {
17511     SmallVector<SDValue, 2> Results;
17512     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17513                             Results);
17514     return DAG.getMergeValues(Results, dl);
17515   }
17516   // Read Performance Monitoring Counters.
17517   case RDPMC: {
17518     SmallVector<SDValue, 2> Results;
17519     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17520     return DAG.getMergeValues(Results, dl);
17521   }
17522   // XTEST intrinsics.
17523   case XTEST: {
17524     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17525     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17526     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17527                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17528                                 InTrans);
17529     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17530     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17531                        Ret, SDValue(InTrans.getNode(), 1));
17532   }
17533   // ADC/ADCX/SBB
17534   case ADX: {
17535     SmallVector<SDValue, 2> Results;
17536     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17537     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17538     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17539                                 DAG.getConstant(-1, dl, MVT::i8));
17540     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17541                               Op.getOperand(4), GenCF.getValue(1));
17542     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17543                                  Op.getOperand(5), MachinePointerInfo(),
17544                                  false, false, 0);
17545     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17546                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17547                                 Res.getValue(1));
17548     Results.push_back(SetCC);
17549     Results.push_back(Store);
17550     return DAG.getMergeValues(Results, dl);
17551   }
17552   case COMPRESS_TO_MEM: {
17553     SDValue Mask = Op.getOperand(4);
17554     SDValue DataToCompress = Op.getOperand(3);
17555     SDValue Addr = Op.getOperand(2);
17556     SDValue Chain = Op.getOperand(0);
17557
17558     MVT VT = DataToCompress.getSimpleValueType();
17559     if (isAllOnesConstant(Mask)) // return just a store
17560       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17561                           MachinePointerInfo(), false, false,
17562                           VT.getScalarSizeInBits()/8);
17563
17564     SDValue Compressed =
17565       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17566                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17567     return DAG.getStore(Chain, dl, Compressed, Addr,
17568                         MachinePointerInfo(), false, false,
17569                         VT.getScalarSizeInBits()/8);
17570   }
17571   case TRUNCATE_TO_MEM_VI8:
17572     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17573   case TRUNCATE_TO_MEM_VI16:
17574     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17575   case TRUNCATE_TO_MEM_VI32:
17576     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17577   case EXPAND_FROM_MEM: {
17578     SDValue Mask = Op.getOperand(4);
17579     SDValue PassThru = Op.getOperand(3);
17580     SDValue Addr = Op.getOperand(2);
17581     SDValue Chain = Op.getOperand(0);
17582     MVT VT = Op.getSimpleValueType();
17583
17584     if (isAllOnesConstant(Mask)) // return just a load
17585       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17586                          false, VT.getScalarSizeInBits()/8);
17587
17588     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17589                                        false, false, false,
17590                                        VT.getScalarSizeInBits()/8);
17591
17592     SDValue Results[] = {
17593       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17594                            Mask, PassThru, Subtarget, DAG), Chain};
17595     return DAG.getMergeValues(Results, dl);
17596   }
17597   case LOADU:
17598   case LOADA: {
17599     SDValue Mask = Op.getOperand(4);
17600     SDValue PassThru = Op.getOperand(3);
17601     SDValue Addr = Op.getOperand(2);
17602     SDValue Chain = Op.getOperand(0);
17603     MVT VT = Op.getSimpleValueType();
17604
17605     MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
17606     assert(MemIntr && "Expected MemIntrinsicSDNode!");
17607
17608     if (isAllOnesConstant(Mask)) // return just a load
17609       return DAG.getLoad(VT, dl, Chain, Addr, MemIntr->getMemOperand());
17610
17611     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17612     SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
17613     return DAG.getMaskedLoad(VT, dl, Chain, Addr, VMask, PassThru, VT,
17614                              MemIntr->getMemOperand(), ISD::NON_EXTLOAD);
17615   }
17616   }
17617 }
17618
17619 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17620                                            SelectionDAG &DAG) const {
17621   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17622   MFI->setReturnAddressIsTaken(true);
17623
17624   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17625     return SDValue();
17626
17627   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17628   SDLoc dl(Op);
17629   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17630
17631   if (Depth > 0) {
17632     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17633     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17634     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17635     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17636                        DAG.getNode(ISD::ADD, dl, PtrVT,
17637                                    FrameAddr, Offset),
17638                        MachinePointerInfo(), false, false, false, 0);
17639   }
17640
17641   // Just load the return address.
17642   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17643   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17644                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17645 }
17646
17647 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17648   MachineFunction &MF = DAG.getMachineFunction();
17649   MachineFrameInfo *MFI = MF.getFrameInfo();
17650   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17651   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17652   EVT VT = Op.getValueType();
17653
17654   MFI->setFrameAddressIsTaken(true);
17655
17656   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17657     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17658     // is not possible to crawl up the stack without looking at the unwind codes
17659     // simultaneously.
17660     int FrameAddrIndex = FuncInfo->getFAIndex();
17661     if (!FrameAddrIndex) {
17662       // Set up a frame object for the return address.
17663       unsigned SlotSize = RegInfo->getSlotSize();
17664       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17665           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17666       FuncInfo->setFAIndex(FrameAddrIndex);
17667     }
17668     return DAG.getFrameIndex(FrameAddrIndex, VT);
17669   }
17670
17671   unsigned FrameReg =
17672       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17673   SDLoc dl(Op);  // FIXME probably not meaningful
17674   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17675   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17676           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17677          "Invalid Frame Register!");
17678   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17679   while (Depth--)
17680     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17681                             MachinePointerInfo(),
17682                             false, false, false, 0);
17683   return FrameAddr;
17684 }
17685
17686 // FIXME? Maybe this could be a TableGen attribute on some registers and
17687 // this table could be generated automatically from RegInfo.
17688 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17689                                               SelectionDAG &DAG) const {
17690   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17691   const MachineFunction &MF = DAG.getMachineFunction();
17692
17693   unsigned Reg = StringSwitch<unsigned>(RegName)
17694                        .Case("esp", X86::ESP)
17695                        .Case("rsp", X86::RSP)
17696                        .Case("ebp", X86::EBP)
17697                        .Case("rbp", X86::RBP)
17698                        .Default(0);
17699
17700   if (Reg == X86::EBP || Reg == X86::RBP) {
17701     if (!TFI.hasFP(MF))
17702       report_fatal_error("register " + StringRef(RegName) +
17703                          " is allocatable: function has no frame pointer");
17704 #ifndef NDEBUG
17705     else {
17706       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17707       unsigned FrameReg =
17708           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17709       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17710              "Invalid Frame Register!");
17711     }
17712 #endif
17713   }
17714
17715   if (Reg)
17716     return Reg;
17717
17718   report_fatal_error("Invalid register name global variable");
17719 }
17720
17721 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17722                                                      SelectionDAG &DAG) const {
17723   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17724   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17725 }
17726
17727 unsigned X86TargetLowering::getExceptionPointerRegister(
17728     const Constant *PersonalityFn) const {
17729   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17730     return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17731
17732   return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17733 }
17734
17735 unsigned X86TargetLowering::getExceptionSelectorRegister(
17736     const Constant *PersonalityFn) const {
17737   // Funclet personalities don't use selectors (the runtime does the selection).
17738   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17739   return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17740 }
17741
17742 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17743   SDValue Chain     = Op.getOperand(0);
17744   SDValue Offset    = Op.getOperand(1);
17745   SDValue Handler   = Op.getOperand(2);
17746   SDLoc dl      (Op);
17747
17748   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17749   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17750   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17751   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17752           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17753          "Invalid Frame Register!");
17754   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17755   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17756
17757   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17758                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17759                                                        dl));
17760   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17761   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17762                        false, false, 0);
17763   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17764
17765   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17766                      DAG.getRegister(StoreAddrReg, PtrVT));
17767 }
17768
17769 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17770                                                SelectionDAG &DAG) const {
17771   SDLoc DL(Op);
17772   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17773                      DAG.getVTList(MVT::i32, MVT::Other),
17774                      Op.getOperand(0), Op.getOperand(1));
17775 }
17776
17777 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17778                                                 SelectionDAG &DAG) const {
17779   SDLoc DL(Op);
17780   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17781                      Op.getOperand(0), Op.getOperand(1));
17782 }
17783
17784 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17785   return Op.getOperand(0);
17786 }
17787
17788 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17789                                                 SelectionDAG &DAG) const {
17790   SDValue Root = Op.getOperand(0);
17791   SDValue Trmp = Op.getOperand(1); // trampoline
17792   SDValue FPtr = Op.getOperand(2); // nested function
17793   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17794   SDLoc dl (Op);
17795
17796   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17797   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17798
17799   if (Subtarget->is64Bit()) {
17800     SDValue OutChains[6];
17801
17802     // Large code-model.
17803     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17804     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17805
17806     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17807     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17808
17809     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17810
17811     // Load the pointer to the nested function into R11.
17812     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17813     SDValue Addr = Trmp;
17814     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17815                                 Addr, MachinePointerInfo(TrmpAddr),
17816                                 false, false, 0);
17817
17818     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17819                        DAG.getConstant(2, dl, MVT::i64));
17820     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17821                                 MachinePointerInfo(TrmpAddr, 2),
17822                                 false, false, 2);
17823
17824     // Load the 'nest' parameter value into R10.
17825     // R10 is specified in X86CallingConv.td
17826     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17827     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17828                        DAG.getConstant(10, dl, MVT::i64));
17829     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17830                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17831                                 false, false, 0);
17832
17833     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17834                        DAG.getConstant(12, dl, MVT::i64));
17835     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17836                                 MachinePointerInfo(TrmpAddr, 12),
17837                                 false, false, 2);
17838
17839     // Jump to the nested function.
17840     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17841     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17842                        DAG.getConstant(20, dl, MVT::i64));
17843     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17844                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17845                                 false, false, 0);
17846
17847     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17848     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17849                        DAG.getConstant(22, dl, MVT::i64));
17850     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17851                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17852                                 false, false, 0);
17853
17854     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17855   } else {
17856     const Function *Func =
17857       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17858     CallingConv::ID CC = Func->getCallingConv();
17859     unsigned NestReg;
17860
17861     switch (CC) {
17862     default:
17863       llvm_unreachable("Unsupported calling convention");
17864     case CallingConv::C:
17865     case CallingConv::X86_StdCall: {
17866       // Pass 'nest' parameter in ECX.
17867       // Must be kept in sync with X86CallingConv.td
17868       NestReg = X86::ECX;
17869
17870       // Check that ECX wasn't needed by an 'inreg' parameter.
17871       FunctionType *FTy = Func->getFunctionType();
17872       const AttributeSet &Attrs = Func->getAttributes();
17873
17874       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17875         unsigned InRegCount = 0;
17876         unsigned Idx = 1;
17877
17878         for (FunctionType::param_iterator I = FTy->param_begin(),
17879              E = FTy->param_end(); I != E; ++I, ++Idx)
17880           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17881             auto &DL = DAG.getDataLayout();
17882             // FIXME: should only count parameters that are lowered to integers.
17883             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17884           }
17885
17886         if (InRegCount > 2) {
17887           report_fatal_error("Nest register in use - reduce number of inreg"
17888                              " parameters!");
17889         }
17890       }
17891       break;
17892     }
17893     case CallingConv::X86_FastCall:
17894     case CallingConv::X86_ThisCall:
17895     case CallingConv::Fast:
17896       // Pass 'nest' parameter in EAX.
17897       // Must be kept in sync with X86CallingConv.td
17898       NestReg = X86::EAX;
17899       break;
17900     }
17901
17902     SDValue OutChains[4];
17903     SDValue Addr, Disp;
17904
17905     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17906                        DAG.getConstant(10, dl, MVT::i32));
17907     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17908
17909     // This is storing the opcode for MOV32ri.
17910     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17911     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17912     OutChains[0] = DAG.getStore(Root, dl,
17913                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17914                                 Trmp, MachinePointerInfo(TrmpAddr),
17915                                 false, false, 0);
17916
17917     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17918                        DAG.getConstant(1, dl, MVT::i32));
17919     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17920                                 MachinePointerInfo(TrmpAddr, 1),
17921                                 false, false, 1);
17922
17923     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17924     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17925                        DAG.getConstant(5, dl, MVT::i32));
17926     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17927                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17928                                 false, false, 1);
17929
17930     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17931                        DAG.getConstant(6, dl, MVT::i32));
17932     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17933                                 MachinePointerInfo(TrmpAddr, 6),
17934                                 false, false, 1);
17935
17936     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17937   }
17938 }
17939
17940 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17941                                             SelectionDAG &DAG) const {
17942   /*
17943    The rounding mode is in bits 11:10 of FPSR, and has the following
17944    settings:
17945      00 Round to nearest
17946      01 Round to -inf
17947      10 Round to +inf
17948      11 Round to 0
17949
17950   FLT_ROUNDS, on the other hand, expects the following:
17951     -1 Undefined
17952      0 Round to 0
17953      1 Round to nearest
17954      2 Round to +inf
17955      3 Round to -inf
17956
17957   To perform the conversion, we do:
17958     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17959   */
17960
17961   MachineFunction &MF = DAG.getMachineFunction();
17962   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17963   unsigned StackAlignment = TFI.getStackAlignment();
17964   MVT VT = Op.getSimpleValueType();
17965   SDLoc DL(Op);
17966
17967   // Save FP Control Word to stack slot
17968   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17969   SDValue StackSlot =
17970       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17971
17972   MachineMemOperand *MMO =
17973       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17974                               MachineMemOperand::MOStore, 2, 2);
17975
17976   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17977   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17978                                           DAG.getVTList(MVT::Other),
17979                                           Ops, MVT::i16, MMO);
17980
17981   // Load FP Control Word from stack slot
17982   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17983                             MachinePointerInfo(), false, false, false, 0);
17984
17985   // Transform as necessary
17986   SDValue CWD1 =
17987     DAG.getNode(ISD::SRL, DL, MVT::i16,
17988                 DAG.getNode(ISD::AND, DL, MVT::i16,
17989                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17990                 DAG.getConstant(11, DL, MVT::i8));
17991   SDValue CWD2 =
17992     DAG.getNode(ISD::SRL, DL, MVT::i16,
17993                 DAG.getNode(ISD::AND, DL, MVT::i16,
17994                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17995                 DAG.getConstant(9, DL, MVT::i8));
17996
17997   SDValue RetVal =
17998     DAG.getNode(ISD::AND, DL, MVT::i16,
17999                 DAG.getNode(ISD::ADD, DL, MVT::i16,
18000                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
18001                             DAG.getConstant(1, DL, MVT::i16)),
18002                 DAG.getConstant(3, DL, MVT::i16));
18003
18004   return DAG.getNode((VT.getSizeInBits() < 16 ?
18005                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
18006 }
18007
18008 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
18009 //
18010 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
18011 //    to 512-bit vector.
18012 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
18013 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
18014 //    split the vector, perform operation on it's Lo a Hi part and
18015 //    concatenate the results.
18016 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
18017   SDLoc dl(Op);
18018   MVT VT = Op.getSimpleValueType();
18019   MVT EltVT = VT.getVectorElementType();
18020   unsigned NumElems = VT.getVectorNumElements();
18021
18022   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
18023     // Extend to 512 bit vector.
18024     assert((VT.is256BitVector() || VT.is128BitVector()) &&
18025               "Unsupported value type for operation");
18026
18027     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
18028     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
18029                                  DAG.getUNDEF(NewVT),
18030                                  Op.getOperand(0),
18031                                  DAG.getIntPtrConstant(0, dl));
18032     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
18033
18034     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
18035                        DAG.getIntPtrConstant(0, dl));
18036   }
18037
18038   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
18039           "Unsupported element type");
18040
18041   if (16 < NumElems) {
18042     // Split vector, it's Lo and Hi parts will be handled in next iteration.
18043     SDValue Lo, Hi;
18044     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
18045     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
18046
18047     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
18048     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
18049
18050     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
18051   }
18052
18053   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
18054
18055   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
18056           "Unsupported value type for operation");
18057
18058   // Use native supported vector instruction vplzcntd.
18059   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
18060   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
18061   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
18062   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
18063
18064   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
18065 }
18066
18067 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
18068                          SelectionDAG &DAG) {
18069   MVT VT = Op.getSimpleValueType();
18070   MVT OpVT = VT;
18071   unsigned NumBits = VT.getSizeInBits();
18072   SDLoc dl(Op);
18073
18074   if (VT.isVector() && Subtarget->hasAVX512())
18075     return LowerVectorCTLZ_AVX512(Op, DAG);
18076
18077   Op = Op.getOperand(0);
18078   if (VT == MVT::i8) {
18079     // Zero extend to i32 since there is not an i8 bsr.
18080     OpVT = MVT::i32;
18081     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18082   }
18083
18084   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
18085   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18086   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18087
18088   // If src is zero (i.e. bsr sets ZF), returns NumBits.
18089   SDValue Ops[] = {
18090     Op,
18091     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
18092     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18093     Op.getValue(1)
18094   };
18095   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
18096
18097   // Finally xor with NumBits-1.
18098   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18099                    DAG.getConstant(NumBits - 1, dl, OpVT));
18100
18101   if (VT == MVT::i8)
18102     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18103   return Op;
18104 }
18105
18106 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
18107                                     SelectionDAG &DAG) {
18108   MVT VT = Op.getSimpleValueType();
18109   EVT OpVT = VT;
18110   unsigned NumBits = VT.getSizeInBits();
18111   SDLoc dl(Op);
18112
18113   Op = Op.getOperand(0);
18114   if (VT == MVT::i8) {
18115     // Zero extend to i32 since there is not an i8 bsr.
18116     OpVT = MVT::i32;
18117     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18118   }
18119
18120   // Issue a bsr (scan bits in reverse).
18121   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18122   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18123
18124   // And xor with NumBits-1.
18125   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18126                    DAG.getConstant(NumBits - 1, dl, OpVT));
18127
18128   if (VT == MVT::i8)
18129     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18130   return Op;
18131 }
18132
18133 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18134   MVT VT = Op.getSimpleValueType();
18135   unsigned NumBits = VT.getScalarSizeInBits();
18136   SDLoc dl(Op);
18137
18138   if (VT.isVector()) {
18139     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18140
18141     SDValue N0 = Op.getOperand(0);
18142     SDValue Zero = DAG.getConstant(0, dl, VT);
18143
18144     // lsb(x) = (x & -x)
18145     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
18146                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
18147
18148     // cttz_undef(x) = (width - 1) - ctlz(lsb)
18149     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
18150         TLI.isOperationLegal(ISD::CTLZ, VT)) {
18151       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
18152       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
18153                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
18154     }
18155
18156     // cttz(x) = ctpop(lsb - 1)
18157     SDValue One = DAG.getConstant(1, dl, VT);
18158     return DAG.getNode(ISD::CTPOP, dl, VT,
18159                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
18160   }
18161
18162   assert(Op.getOpcode() == ISD::CTTZ &&
18163          "Only scalar CTTZ requires custom lowering");
18164
18165   // Issue a bsf (scan bits forward) which also sets EFLAGS.
18166   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18167   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
18168
18169   // If src is zero (i.e. bsf sets ZF), returns NumBits.
18170   SDValue Ops[] = {
18171     Op,
18172     DAG.getConstant(NumBits, dl, VT),
18173     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18174     Op.getValue(1)
18175   };
18176   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18177 }
18178
18179 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18180 // ones, and then concatenate the result back.
18181 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18182   MVT VT = Op.getSimpleValueType();
18183
18184   assert(VT.is256BitVector() && VT.isInteger() &&
18185          "Unsupported value type for operation");
18186
18187   unsigned NumElems = VT.getVectorNumElements();
18188   SDLoc dl(Op);
18189
18190   // Extract the LHS vectors
18191   SDValue LHS = Op.getOperand(0);
18192   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18193   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18194
18195   // Extract the RHS vectors
18196   SDValue RHS = Op.getOperand(1);
18197   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18198   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18199
18200   MVT EltVT = VT.getVectorElementType();
18201   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18202
18203   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18204                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18205                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18206 }
18207
18208 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18209   if (Op.getValueType() == MVT::i1)
18210     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18211                        Op.getOperand(0), Op.getOperand(1));
18212   assert(Op.getSimpleValueType().is256BitVector() &&
18213          Op.getSimpleValueType().isInteger() &&
18214          "Only handle AVX 256-bit vector integer operation");
18215   return Lower256IntArith(Op, DAG);
18216 }
18217
18218 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18219   if (Op.getValueType() == MVT::i1)
18220     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18221                        Op.getOperand(0), Op.getOperand(1));
18222   assert(Op.getSimpleValueType().is256BitVector() &&
18223          Op.getSimpleValueType().isInteger() &&
18224          "Only handle AVX 256-bit vector integer operation");
18225   return Lower256IntArith(Op, DAG);
18226 }
18227
18228 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
18229   assert(Op.getSimpleValueType().is256BitVector() &&
18230          Op.getSimpleValueType().isInteger() &&
18231          "Only handle AVX 256-bit vector integer operation");
18232   return Lower256IntArith(Op, DAG);
18233 }
18234
18235 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18236                         SelectionDAG &DAG) {
18237   SDLoc dl(Op);
18238   MVT VT = Op.getSimpleValueType();
18239
18240   if (VT == MVT::i1)
18241     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
18242
18243   // Decompose 256-bit ops into smaller 128-bit ops.
18244   if (VT.is256BitVector() && !Subtarget->hasInt256())
18245     return Lower256IntArith(Op, DAG);
18246
18247   SDValue A = Op.getOperand(0);
18248   SDValue B = Op.getOperand(1);
18249
18250   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
18251   // pairs, multiply and truncate.
18252   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
18253     if (Subtarget->hasInt256()) {
18254       if (VT == MVT::v32i8) {
18255         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
18256         SDValue Lo = DAG.getIntPtrConstant(0, dl);
18257         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
18258         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
18259         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
18260         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
18261         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18262         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18263                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18264                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18265       }
18266
18267       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18268       return DAG.getNode(
18269           ISD::TRUNCATE, dl, VT,
18270           DAG.getNode(ISD::MUL, dl, ExVT,
18271                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18272                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18273     }
18274
18275     assert(VT == MVT::v16i8 &&
18276            "Pre-AVX2 support only supports v16i8 multiplication");
18277     MVT ExVT = MVT::v8i16;
18278
18279     // Extract the lo parts and sign extend to i16
18280     SDValue ALo, BLo;
18281     if (Subtarget->hasSSE41()) {
18282       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18283       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18284     } else {
18285       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18286                               -1, 4, -1, 5, -1, 6, -1, 7};
18287       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18288       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18289       ALo = DAG.getBitcast(ExVT, ALo);
18290       BLo = DAG.getBitcast(ExVT, BLo);
18291       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18292       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18293     }
18294
18295     // Extract the hi parts and sign extend to i16
18296     SDValue AHi, BHi;
18297     if (Subtarget->hasSSE41()) {
18298       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
18299                               -1, -1, -1, -1, -1, -1, -1, -1};
18300       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18301       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18302       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18303       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18304     } else {
18305       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
18306                               -1, 12, -1, 13, -1, 14, -1, 15};
18307       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18308       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18309       AHi = DAG.getBitcast(ExVT, AHi);
18310       BHi = DAG.getBitcast(ExVT, BHi);
18311       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18312       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18313     }
18314
18315     // Multiply, mask the lower 8bits of the lo/hi results and pack
18316     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18317     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18318     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18319     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18320     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18321   }
18322
18323   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18324   if (VT == MVT::v4i32) {
18325     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18326            "Should not custom lower when pmuldq is available!");
18327
18328     // Extract the odd parts.
18329     static const int UnpackMask[] = { 1, -1, 3, -1 };
18330     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18331     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18332
18333     // Multiply the even parts.
18334     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18335     // Now multiply odd parts.
18336     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18337
18338     Evens = DAG.getBitcast(VT, Evens);
18339     Odds = DAG.getBitcast(VT, Odds);
18340
18341     // Merge the two vectors back together with a shuffle. This expands into 2
18342     // shuffles.
18343     static const int ShufMask[] = { 0, 4, 2, 6 };
18344     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18345   }
18346
18347   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18348          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18349
18350   //  Ahi = psrlqi(a, 32);
18351   //  Bhi = psrlqi(b, 32);
18352   //
18353   //  AloBlo = pmuludq(a, b);
18354   //  AloBhi = pmuludq(a, Bhi);
18355   //  AhiBlo = pmuludq(Ahi, b);
18356
18357   //  AloBhi = psllqi(AloBhi, 32);
18358   //  AhiBlo = psllqi(AhiBlo, 32);
18359   //  return AloBlo + AloBhi + AhiBlo;
18360
18361   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18362   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18363
18364   SDValue AhiBlo = Ahi;
18365   SDValue AloBhi = Bhi;
18366   // Bit cast to 32-bit vectors for MULUDQ
18367   MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18368                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18369   A = DAG.getBitcast(MulVT, A);
18370   B = DAG.getBitcast(MulVT, B);
18371   Ahi = DAG.getBitcast(MulVT, Ahi);
18372   Bhi = DAG.getBitcast(MulVT, Bhi);
18373
18374   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18375   // After shifting right const values the result may be all-zero.
18376   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18377     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18378     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18379   }
18380   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18381     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18382     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18383   }
18384
18385   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18386   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18387 }
18388
18389 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18390   assert(Subtarget->isTargetWin64() && "Unexpected target");
18391   EVT VT = Op.getValueType();
18392   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18393          "Unexpected return type for lowering");
18394
18395   RTLIB::Libcall LC;
18396   bool isSigned;
18397   switch (Op->getOpcode()) {
18398   default: llvm_unreachable("Unexpected request for libcall!");
18399   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18400   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18401   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18402   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18403   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18404   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18405   }
18406
18407   SDLoc dl(Op);
18408   SDValue InChain = DAG.getEntryNode();
18409
18410   TargetLowering::ArgListTy Args;
18411   TargetLowering::ArgListEntry Entry;
18412   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18413     EVT ArgVT = Op->getOperand(i).getValueType();
18414     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18415            "Unexpected argument type for lowering");
18416     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18417     Entry.Node = StackPtr;
18418     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18419                            false, false, 16);
18420     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18421     Entry.Ty = PointerType::get(ArgTy,0);
18422     Entry.isSExt = false;
18423     Entry.isZExt = false;
18424     Args.push_back(Entry);
18425   }
18426
18427   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18428                                          getPointerTy(DAG.getDataLayout()));
18429
18430   TargetLowering::CallLoweringInfo CLI(DAG);
18431   CLI.setDebugLoc(dl).setChain(InChain)
18432     .setCallee(getLibcallCallingConv(LC),
18433                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18434                Callee, std::move(Args), 0)
18435     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18436
18437   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18438   return DAG.getBitcast(VT, CallInfo.first);
18439 }
18440
18441 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18442                              SelectionDAG &DAG) {
18443   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18444   MVT VT = Op0.getSimpleValueType();
18445   SDLoc dl(Op);
18446
18447   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18448          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18449
18450   // PMULxD operations multiply each even value (starting at 0) of LHS with
18451   // the related value of RHS and produce a widen result.
18452   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18453   // => <2 x i64> <ae|cg>
18454   //
18455   // In other word, to have all the results, we need to perform two PMULxD:
18456   // 1. one with the even values.
18457   // 2. one with the odd values.
18458   // To achieve #2, with need to place the odd values at an even position.
18459   //
18460   // Place the odd value at an even position (basically, shift all values 1
18461   // step to the left):
18462   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18463   // <a|b|c|d> => <b|undef|d|undef>
18464   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18465   // <e|f|g|h> => <f|undef|h|undef>
18466   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18467
18468   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18469   // ints.
18470   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18471   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18472   unsigned Opcode =
18473       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18474   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18475   // => <2 x i64> <ae|cg>
18476   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18477   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18478   // => <2 x i64> <bf|dh>
18479   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18480
18481   // Shuffle it back into the right order.
18482   SDValue Highs, Lows;
18483   if (VT == MVT::v8i32) {
18484     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18485     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18486     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18487     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18488   } else {
18489     const int HighMask[] = {1, 5, 3, 7};
18490     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18491     const int LowMask[] = {0, 4, 2, 6};
18492     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18493   }
18494
18495   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18496   // unsigned multiply.
18497   if (IsSigned && !Subtarget->hasSSE41()) {
18498     SDValue ShAmt = DAG.getConstant(
18499         31, dl,
18500         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18501     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18502                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18503     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18504                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18505
18506     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18507     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18508   }
18509
18510   // The first result of MUL_LOHI is actually the low value, followed by the
18511   // high value.
18512   SDValue Ops[] = {Lows, Highs};
18513   return DAG.getMergeValues(Ops, dl);
18514 }
18515
18516 // Return true if the required (according to Opcode) shift-imm form is natively
18517 // supported by the Subtarget
18518 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18519                                         unsigned Opcode) {
18520   if (VT.getScalarSizeInBits() < 16)
18521     return false;
18522
18523   if (VT.is512BitVector() &&
18524       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18525     return true;
18526
18527   bool LShift = VT.is128BitVector() ||
18528     (VT.is256BitVector() && Subtarget->hasInt256());
18529
18530   bool AShift = LShift && (Subtarget->hasVLX() ||
18531     (VT != MVT::v2i64 && VT != MVT::v4i64));
18532   return (Opcode == ISD::SRA) ? AShift : LShift;
18533 }
18534
18535 // The shift amount is a variable, but it is the same for all vector lanes.
18536 // These instructions are defined together with shift-immediate.
18537 static
18538 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18539                                       unsigned Opcode) {
18540   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18541 }
18542
18543 // Return true if the required (according to Opcode) variable-shift form is
18544 // natively supported by the Subtarget
18545 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18546                                     unsigned Opcode) {
18547
18548   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18549     return false;
18550
18551   // vXi16 supported only on AVX-512, BWI
18552   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18553     return false;
18554
18555   if (VT.is512BitVector() || Subtarget->hasVLX())
18556     return true;
18557
18558   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18559   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18560   return (Opcode == ISD::SRA) ? AShift : LShift;
18561 }
18562
18563 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18564                                          const X86Subtarget *Subtarget) {
18565   MVT VT = Op.getSimpleValueType();
18566   SDLoc dl(Op);
18567   SDValue R = Op.getOperand(0);
18568   SDValue Amt = Op.getOperand(1);
18569
18570   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18571     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18572
18573   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18574     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18575     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18576     SDValue Ex = DAG.getBitcast(ExVT, R);
18577
18578     if (ShiftAmt >= 32) {
18579       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18580       SDValue Upper =
18581           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18582       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18583                                                  ShiftAmt - 32, DAG);
18584       if (VT == MVT::v2i64)
18585         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18586       if (VT == MVT::v4i64)
18587         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18588                                   {9, 1, 11, 3, 13, 5, 15, 7});
18589     } else {
18590       // SRA upper i32, SHL whole i64 and select lower i32.
18591       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18592                                                  ShiftAmt, DAG);
18593       SDValue Lower =
18594           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18595       Lower = DAG.getBitcast(ExVT, Lower);
18596       if (VT == MVT::v2i64)
18597         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18598       if (VT == MVT::v4i64)
18599         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18600                                   {8, 1, 10, 3, 12, 5, 14, 7});
18601     }
18602     return DAG.getBitcast(VT, Ex);
18603   };
18604
18605   // Optimize shl/srl/sra with constant shift amount.
18606   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18607     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18608       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18609
18610       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18611         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18612
18613       // i64 SRA needs to be performed as partial shifts.
18614       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18615           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18616         return ArithmeticShiftRight64(ShiftAmt);
18617
18618       if (VT == MVT::v16i8 ||
18619           (Subtarget->hasInt256() && VT == MVT::v32i8) ||
18620           VT == MVT::v64i8) {
18621         unsigned NumElts = VT.getVectorNumElements();
18622         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18623
18624         // Simple i8 add case
18625         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18626           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18627
18628         // ashr(R, 7)  === cmp_slt(R, 0)
18629         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18630           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18631           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18632         }
18633
18634         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18635         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18636           return SDValue();
18637
18638         if (Op.getOpcode() == ISD::SHL) {
18639           // Make a large shift.
18640           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18641                                                    R, ShiftAmt, DAG);
18642           SHL = DAG.getBitcast(VT, SHL);
18643           // Zero out the rightmost bits.
18644           return DAG.getNode(ISD::AND, dl, VT, SHL,
18645                              DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
18646         }
18647         if (Op.getOpcode() == ISD::SRL) {
18648           // Make a large shift.
18649           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18650                                                    R, ShiftAmt, DAG);
18651           SRL = DAG.getBitcast(VT, SRL);
18652           // Zero out the leftmost bits.
18653           return DAG.getNode(ISD::AND, dl, VT, SRL,
18654                              DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
18655         }
18656         if (Op.getOpcode() == ISD::SRA) {
18657           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18658           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18659
18660           SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
18661           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18662           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18663           return Res;
18664         }
18665         llvm_unreachable("Unknown shift opcode.");
18666       }
18667     }
18668   }
18669
18670   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18671   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18672       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18673
18674     // Peek through any splat that was introduced for i64 shift vectorization.
18675     int SplatIndex = -1;
18676     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18677       if (SVN->isSplat()) {
18678         SplatIndex = SVN->getSplatIndex();
18679         Amt = Amt.getOperand(0);
18680         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18681                "Splat shuffle referencing second operand");
18682       }
18683
18684     if (Amt.getOpcode() != ISD::BITCAST ||
18685         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18686       return SDValue();
18687
18688     Amt = Amt.getOperand(0);
18689     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18690                      VT.getVectorNumElements();
18691     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18692     uint64_t ShiftAmt = 0;
18693     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18694     for (unsigned i = 0; i != Ratio; ++i) {
18695       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18696       if (!C)
18697         return SDValue();
18698       // 6 == Log2(64)
18699       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18700     }
18701
18702     // Check remaining shift amounts (if not a splat).
18703     if (SplatIndex < 0) {
18704       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18705         uint64_t ShAmt = 0;
18706         for (unsigned j = 0; j != Ratio; ++j) {
18707           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18708           if (!C)
18709             return SDValue();
18710           // 6 == Log2(64)
18711           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18712         }
18713         if (ShAmt != ShiftAmt)
18714           return SDValue();
18715       }
18716     }
18717
18718     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18719       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18720
18721     if (Op.getOpcode() == ISD::SRA)
18722       return ArithmeticShiftRight64(ShiftAmt);
18723   }
18724
18725   return SDValue();
18726 }
18727
18728 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18729                                         const X86Subtarget* Subtarget) {
18730   MVT VT = Op.getSimpleValueType();
18731   SDLoc dl(Op);
18732   SDValue R = Op.getOperand(0);
18733   SDValue Amt = Op.getOperand(1);
18734
18735   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18736     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18737
18738   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18739     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18740
18741   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18742     SDValue BaseShAmt;
18743     MVT EltVT = VT.getVectorElementType();
18744
18745     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18746       // Check if this build_vector node is doing a splat.
18747       // If so, then set BaseShAmt equal to the splat value.
18748       BaseShAmt = BV->getSplatValue();
18749       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18750         BaseShAmt = SDValue();
18751     } else {
18752       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18753         Amt = Amt.getOperand(0);
18754
18755       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18756       if (SVN && SVN->isSplat()) {
18757         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18758         SDValue InVec = Amt.getOperand(0);
18759         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18760           assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18761                  "Unexpected shuffle index found!");
18762           BaseShAmt = InVec.getOperand(SplatIdx);
18763         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18764            if (ConstantSDNode *C =
18765                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18766              if (C->getZExtValue() == SplatIdx)
18767                BaseShAmt = InVec.getOperand(1);
18768            }
18769         }
18770
18771         if (!BaseShAmt)
18772           // Avoid introducing an extract element from a shuffle.
18773           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18774                                   DAG.getIntPtrConstant(SplatIdx, dl));
18775       }
18776     }
18777
18778     if (BaseShAmt.getNode()) {
18779       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18780       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18781         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18782       else if (EltVT.bitsLT(MVT::i32))
18783         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18784
18785       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18786     }
18787   }
18788
18789   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18790   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18791       Amt.getOpcode() == ISD::BITCAST &&
18792       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18793     Amt = Amt.getOperand(0);
18794     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18795                      VT.getVectorNumElements();
18796     std::vector<SDValue> Vals(Ratio);
18797     for (unsigned i = 0; i != Ratio; ++i)
18798       Vals[i] = Amt.getOperand(i);
18799     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18800       for (unsigned j = 0; j != Ratio; ++j)
18801         if (Vals[j] != Amt.getOperand(i + j))
18802           return SDValue();
18803     }
18804
18805     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18806       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18807   }
18808   return SDValue();
18809 }
18810
18811 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18812                           SelectionDAG &DAG) {
18813   MVT VT = Op.getSimpleValueType();
18814   SDLoc dl(Op);
18815   SDValue R = Op.getOperand(0);
18816   SDValue Amt = Op.getOperand(1);
18817
18818   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18819   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18820
18821   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18822     return V;
18823
18824   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18825     return V;
18826
18827   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18828     return Op;
18829
18830   // XOP has 128-bit variable logical/arithmetic shifts.
18831   // +ve/-ve Amt = shift left/right.
18832   if (Subtarget->hasXOP() &&
18833       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18834        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18835     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18836       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18837       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18838     }
18839     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18840       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18841     if (Op.getOpcode() == ISD::SRA)
18842       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18843   }
18844
18845   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18846   // shifts per-lane and then shuffle the partial results back together.
18847   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18848     // Splat the shift amounts so the scalar shifts above will catch it.
18849     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18850     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18851     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18852     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18853     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18854   }
18855
18856   // i64 vector arithmetic shift can be emulated with the transform:
18857   // M = lshr(SIGN_BIT, Amt)
18858   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18859   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18860       Op.getOpcode() == ISD::SRA) {
18861     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18862     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18863     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18864     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18865     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18866     return R;
18867   }
18868
18869   // If possible, lower this packed shift into a vector multiply instead of
18870   // expanding it into a sequence of scalar shifts.
18871   // Do this only if the vector shift count is a constant build_vector.
18872   if (Op.getOpcode() == ISD::SHL &&
18873       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18874        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18875       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18876     SmallVector<SDValue, 8> Elts;
18877     MVT SVT = VT.getVectorElementType();
18878     unsigned SVTBits = SVT.getSizeInBits();
18879     APInt One(SVTBits, 1);
18880     unsigned NumElems = VT.getVectorNumElements();
18881
18882     for (unsigned i=0; i !=NumElems; ++i) {
18883       SDValue Op = Amt->getOperand(i);
18884       if (Op->getOpcode() == ISD::UNDEF) {
18885         Elts.push_back(Op);
18886         continue;
18887       }
18888
18889       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18890       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18891       uint64_t ShAmt = C.getZExtValue();
18892       if (ShAmt >= SVTBits) {
18893         Elts.push_back(DAG.getUNDEF(SVT));
18894         continue;
18895       }
18896       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18897     }
18898     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18899     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18900   }
18901
18902   // Lower SHL with variable shift amount.
18903   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18904     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18905
18906     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18907                      DAG.getConstant(0x3f800000U, dl, VT));
18908     Op = DAG.getBitcast(MVT::v4f32, Op);
18909     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18910     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18911   }
18912
18913   // If possible, lower this shift as a sequence of two shifts by
18914   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18915   // Example:
18916   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18917   //
18918   // Could be rewritten as:
18919   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18920   //
18921   // The advantage is that the two shifts from the example would be
18922   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18923   // the vector shift into four scalar shifts plus four pairs of vector
18924   // insert/extract.
18925   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18926       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18927     unsigned TargetOpcode = X86ISD::MOVSS;
18928     bool CanBeSimplified;
18929     // The splat value for the first packed shift (the 'X' from the example).
18930     SDValue Amt1 = Amt->getOperand(0);
18931     // The splat value for the second packed shift (the 'Y' from the example).
18932     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18933                                         Amt->getOperand(2);
18934
18935     // See if it is possible to replace this node with a sequence of
18936     // two shifts followed by a MOVSS/MOVSD
18937     if (VT == MVT::v4i32) {
18938       // Check if it is legal to use a MOVSS.
18939       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18940                         Amt2 == Amt->getOperand(3);
18941       if (!CanBeSimplified) {
18942         // Otherwise, check if we can still simplify this node using a MOVSD.
18943         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18944                           Amt->getOperand(2) == Amt->getOperand(3);
18945         TargetOpcode = X86ISD::MOVSD;
18946         Amt2 = Amt->getOperand(2);
18947       }
18948     } else {
18949       // Do similar checks for the case where the machine value type
18950       // is MVT::v8i16.
18951       CanBeSimplified = Amt1 == Amt->getOperand(1);
18952       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18953         CanBeSimplified = Amt2 == Amt->getOperand(i);
18954
18955       if (!CanBeSimplified) {
18956         TargetOpcode = X86ISD::MOVSD;
18957         CanBeSimplified = true;
18958         Amt2 = Amt->getOperand(4);
18959         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18960           CanBeSimplified = Amt1 == Amt->getOperand(i);
18961         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18962           CanBeSimplified = Amt2 == Amt->getOperand(j);
18963       }
18964     }
18965
18966     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18967         isa<ConstantSDNode>(Amt2)) {
18968       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18969       MVT CastVT = MVT::v4i32;
18970       SDValue Splat1 =
18971         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18972       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18973       SDValue Splat2 =
18974         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18975       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18976       if (TargetOpcode == X86ISD::MOVSD)
18977         CastVT = MVT::v2i64;
18978       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18979       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18980       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18981                                             BitCast1, DAG);
18982       return DAG.getBitcast(VT, Result);
18983     }
18984   }
18985
18986   // v4i32 Non Uniform Shifts.
18987   // If the shift amount is constant we can shift each lane using the SSE2
18988   // immediate shifts, else we need to zero-extend each lane to the lower i64
18989   // and shift using the SSE2 variable shifts.
18990   // The separate results can then be blended together.
18991   if (VT == MVT::v4i32) {
18992     unsigned Opc = Op.getOpcode();
18993     SDValue Amt0, Amt1, Amt2, Amt3;
18994     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18995       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18996       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18997       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18998       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18999     } else {
19000       // ISD::SHL is handled above but we include it here for completeness.
19001       switch (Opc) {
19002       default:
19003         llvm_unreachable("Unknown target vector shift node");
19004       case ISD::SHL:
19005         Opc = X86ISD::VSHL;
19006         break;
19007       case ISD::SRL:
19008         Opc = X86ISD::VSRL;
19009         break;
19010       case ISD::SRA:
19011         Opc = X86ISD::VSRA;
19012         break;
19013       }
19014       // The SSE2 shifts use the lower i64 as the same shift amount for
19015       // all lanes and the upper i64 is ignored. These shuffle masks
19016       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
19017       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19018       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
19019       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
19020       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
19021       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
19022     }
19023
19024     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
19025     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
19026     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
19027     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
19028     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
19029     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
19030     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
19031   }
19032
19033   if (VT == MVT::v16i8 ||
19034       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
19035     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
19036     unsigned ShiftOpcode = Op->getOpcode();
19037
19038     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
19039       // On SSE41 targets we make use of the fact that VSELECT lowers
19040       // to PBLENDVB which selects bytes based just on the sign bit.
19041       if (Subtarget->hasSSE41()) {
19042         V0 = DAG.getBitcast(VT, V0);
19043         V1 = DAG.getBitcast(VT, V1);
19044         Sel = DAG.getBitcast(VT, Sel);
19045         return DAG.getBitcast(SelVT,
19046                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
19047       }
19048       // On pre-SSE41 targets we test for the sign bit by comparing to
19049       // zero - a negative value will set all bits of the lanes to true
19050       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
19051       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
19052       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
19053       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
19054     };
19055
19056     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
19057     // We can safely do this using i16 shifts as we're only interested in
19058     // the 3 lower bits of each byte.
19059     Amt = DAG.getBitcast(ExtVT, Amt);
19060     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
19061     Amt = DAG.getBitcast(VT, Amt);
19062
19063     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
19064       // r = VSELECT(r, shift(r, 4), a);
19065       SDValue M =
19066           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19067       R = SignBitSelect(VT, Amt, M, R);
19068
19069       // a += a
19070       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19071
19072       // r = VSELECT(r, shift(r, 2), a);
19073       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19074       R = SignBitSelect(VT, Amt, M, R);
19075
19076       // a += a
19077       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19078
19079       // return VSELECT(r, shift(r, 1), a);
19080       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19081       R = SignBitSelect(VT, Amt, M, R);
19082       return R;
19083     }
19084
19085     if (Op->getOpcode() == ISD::SRA) {
19086       // For SRA we need to unpack each byte to the higher byte of a i16 vector
19087       // so we can correctly sign extend. We don't care what happens to the
19088       // lower byte.
19089       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
19090       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
19091       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
19092       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
19093       ALo = DAG.getBitcast(ExtVT, ALo);
19094       AHi = DAG.getBitcast(ExtVT, AHi);
19095       RLo = DAG.getBitcast(ExtVT, RLo);
19096       RHi = DAG.getBitcast(ExtVT, RHi);
19097
19098       // r = VSELECT(r, shift(r, 4), a);
19099       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19100                                 DAG.getConstant(4, dl, ExtVT));
19101       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19102                                 DAG.getConstant(4, dl, ExtVT));
19103       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19104       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19105
19106       // a += a
19107       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19108       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19109
19110       // r = VSELECT(r, shift(r, 2), a);
19111       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19112                         DAG.getConstant(2, dl, ExtVT));
19113       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19114                         DAG.getConstant(2, dl, ExtVT));
19115       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19116       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19117
19118       // a += a
19119       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19120       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19121
19122       // r = VSELECT(r, shift(r, 1), a);
19123       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19124                         DAG.getConstant(1, dl, ExtVT));
19125       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19126                         DAG.getConstant(1, dl, ExtVT));
19127       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19128       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19129
19130       // Logical shift the result back to the lower byte, leaving a zero upper
19131       // byte
19132       // meaning that we can safely pack with PACKUSWB.
19133       RLo =
19134           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
19135       RHi =
19136           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
19137       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
19138     }
19139   }
19140
19141   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
19142   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
19143   // solution better.
19144   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
19145     MVT ExtVT = MVT::v8i32;
19146     unsigned ExtOpc =
19147         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19148     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
19149     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
19150     return DAG.getNode(ISD::TRUNCATE, dl, VT,
19151                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
19152   }
19153
19154   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
19155     MVT ExtVT = MVT::v8i32;
19156     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19157     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
19158     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
19159     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
19160     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
19161     ALo = DAG.getBitcast(ExtVT, ALo);
19162     AHi = DAG.getBitcast(ExtVT, AHi);
19163     RLo = DAG.getBitcast(ExtVT, RLo);
19164     RHi = DAG.getBitcast(ExtVT, RHi);
19165     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
19166     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
19167     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
19168     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
19169     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
19170   }
19171
19172   if (VT == MVT::v8i16) {
19173     unsigned ShiftOpcode = Op->getOpcode();
19174
19175     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
19176       // On SSE41 targets we make use of the fact that VSELECT lowers
19177       // to PBLENDVB which selects bytes based just on the sign bit.
19178       if (Subtarget->hasSSE41()) {
19179         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
19180         V0 = DAG.getBitcast(ExtVT, V0);
19181         V1 = DAG.getBitcast(ExtVT, V1);
19182         Sel = DAG.getBitcast(ExtVT, Sel);
19183         return DAG.getBitcast(
19184             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
19185       }
19186       // On pre-SSE41 targets we splat the sign bit - a negative value will
19187       // set all bits of the lanes to true and VSELECT uses that in
19188       // its OR(AND(V0,C),AND(V1,~C)) lowering.
19189       SDValue C =
19190           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
19191       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
19192     };
19193
19194     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
19195     if (Subtarget->hasSSE41()) {
19196       // On SSE41 targets we need to replicate the shift mask in both
19197       // bytes for PBLENDVB.
19198       Amt = DAG.getNode(
19199           ISD::OR, dl, VT,
19200           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
19201           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
19202     } else {
19203       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
19204     }
19205
19206     // r = VSELECT(r, shift(r, 8), a);
19207     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
19208     R = SignBitSelect(Amt, M, R);
19209
19210     // a += a
19211     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19212
19213     // r = VSELECT(r, shift(r, 4), a);
19214     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19215     R = SignBitSelect(Amt, M, R);
19216
19217     // a += a
19218     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19219
19220     // r = VSELECT(r, shift(r, 2), a);
19221     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19222     R = SignBitSelect(Amt, M, R);
19223
19224     // a += a
19225     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19226
19227     // return VSELECT(r, shift(r, 1), a);
19228     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19229     R = SignBitSelect(Amt, M, R);
19230     return R;
19231   }
19232
19233   // Decompose 256-bit shifts into smaller 128-bit shifts.
19234   if (VT.is256BitVector()) {
19235     unsigned NumElems = VT.getVectorNumElements();
19236     MVT EltVT = VT.getVectorElementType();
19237     MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19238
19239     // Extract the two vectors
19240     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
19241     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
19242
19243     // Recreate the shift amount vectors
19244     SDValue Amt1, Amt2;
19245     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
19246       // Constant shift amount
19247       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
19248       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
19249       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
19250
19251       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
19252       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
19253     } else {
19254       // Variable shift amount
19255       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19256       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19257     }
19258
19259     // Issue new vector shifts for the smaller types
19260     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19261     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19262
19263     // Concatenate the result back
19264     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19265   }
19266
19267   return SDValue();
19268 }
19269
19270 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19271                            SelectionDAG &DAG) {
19272   MVT VT = Op.getSimpleValueType();
19273   SDLoc DL(Op);
19274   SDValue R = Op.getOperand(0);
19275   SDValue Amt = Op.getOperand(1);
19276
19277   assert(VT.isVector() && "Custom lowering only for vector rotates!");
19278   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19279   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19280
19281   // XOP has 128-bit vector variable + immediate rotates.
19282   // +ve/-ve Amt = rotate left/right.
19283
19284   // Split 256-bit integers.
19285   if (VT.is256BitVector())
19286     return Lower256IntArith(Op, DAG);
19287
19288   assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19289
19290   // Attempt to rotate by immediate.
19291   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19292     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19293       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19294       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19295       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19296                          DAG.getConstant(RotateAmt, DL, MVT::i8));
19297     }
19298   }
19299
19300   // Use general rotate by variable (per-element).
19301   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19302 }
19303
19304 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19305   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19306   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19307   // looks for this combo and may remove the "setcc" instruction if the "setcc"
19308   // has only one use.
19309   SDNode *N = Op.getNode();
19310   SDValue LHS = N->getOperand(0);
19311   SDValue RHS = N->getOperand(1);
19312   unsigned BaseOp = 0;
19313   unsigned Cond = 0;
19314   SDLoc DL(Op);
19315   switch (Op.getOpcode()) {
19316   default: llvm_unreachable("Unknown ovf instruction!");
19317   case ISD::SADDO:
19318     // A subtract of one will be selected as a INC. Note that INC doesn't
19319     // set CF, so we can't do this for UADDO.
19320     if (isOneConstant(RHS)) {
19321         BaseOp = X86ISD::INC;
19322         Cond = X86::COND_O;
19323         break;
19324       }
19325     BaseOp = X86ISD::ADD;
19326     Cond = X86::COND_O;
19327     break;
19328   case ISD::UADDO:
19329     BaseOp = X86ISD::ADD;
19330     Cond = X86::COND_B;
19331     break;
19332   case ISD::SSUBO:
19333     // A subtract of one will be selected as a DEC. Note that DEC doesn't
19334     // set CF, so we can't do this for USUBO.
19335     if (isOneConstant(RHS)) {
19336         BaseOp = X86ISD::DEC;
19337         Cond = X86::COND_O;
19338         break;
19339       }
19340     BaseOp = X86ISD::SUB;
19341     Cond = X86::COND_O;
19342     break;
19343   case ISD::USUBO:
19344     BaseOp = X86ISD::SUB;
19345     Cond = X86::COND_B;
19346     break;
19347   case ISD::SMULO:
19348     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19349     Cond = X86::COND_O;
19350     break;
19351   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19352     if (N->getValueType(0) == MVT::i8) {
19353       BaseOp = X86ISD::UMUL8;
19354       Cond = X86::COND_O;
19355       break;
19356     }
19357     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19358                                  MVT::i32);
19359     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19360
19361     SDValue SetCC =
19362       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19363                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
19364                   SDValue(Sum.getNode(), 2));
19365
19366     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19367   }
19368   }
19369
19370   // Also sets EFLAGS.
19371   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19372   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19373
19374   SDValue SetCC =
19375     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19376                 DAG.getConstant(Cond, DL, MVT::i32),
19377                 SDValue(Sum.getNode(), 1));
19378
19379   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19380 }
19381
19382 /// Returns true if the operand type is exactly twice the native width, and
19383 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19384 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19385 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19386 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19387   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19388
19389   if (OpWidth == 64)
19390     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19391   else if (OpWidth == 128)
19392     return Subtarget->hasCmpxchg16b();
19393   else
19394     return false;
19395 }
19396
19397 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19398   return needsCmpXchgNb(SI->getValueOperand()->getType());
19399 }
19400
19401 // Note: this turns large loads into lock cmpxchg8b/16b.
19402 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19403 TargetLowering::AtomicExpansionKind
19404 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19405   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19406   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19407                                                : AtomicExpansionKind::None;
19408 }
19409
19410 TargetLowering::AtomicExpansionKind
19411 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19412   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19413   Type *MemType = AI->getType();
19414
19415   // If the operand is too big, we must see if cmpxchg8/16b is available
19416   // and default to library calls otherwise.
19417   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19418     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19419                                    : AtomicExpansionKind::None;
19420   }
19421
19422   AtomicRMWInst::BinOp Op = AI->getOperation();
19423   switch (Op) {
19424   default:
19425     llvm_unreachable("Unknown atomic operation");
19426   case AtomicRMWInst::Xchg:
19427   case AtomicRMWInst::Add:
19428   case AtomicRMWInst::Sub:
19429     // It's better to use xadd, xsub or xchg for these in all cases.
19430     return AtomicExpansionKind::None;
19431   case AtomicRMWInst::Or:
19432   case AtomicRMWInst::And:
19433   case AtomicRMWInst::Xor:
19434     // If the atomicrmw's result isn't actually used, we can just add a "lock"
19435     // prefix to a normal instruction for these operations.
19436     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19437                             : AtomicExpansionKind::None;
19438   case AtomicRMWInst::Nand:
19439   case AtomicRMWInst::Max:
19440   case AtomicRMWInst::Min:
19441   case AtomicRMWInst::UMax:
19442   case AtomicRMWInst::UMin:
19443     // These always require a non-trivial set of data operations on x86. We must
19444     // use a cmpxchg loop.
19445     return AtomicExpansionKind::CmpXChg;
19446   }
19447 }
19448
19449 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19450   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19451   // no-sse2). There isn't any reason to disable it if the target processor
19452   // supports it.
19453   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19454 }
19455
19456 LoadInst *
19457 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19458   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19459   Type *MemType = AI->getType();
19460   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19461   // there is no benefit in turning such RMWs into loads, and it is actually
19462   // harmful as it introduces a mfence.
19463   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19464     return nullptr;
19465
19466   auto Builder = IRBuilder<>(AI);
19467   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19468   auto SynchScope = AI->getSynchScope();
19469   // We must restrict the ordering to avoid generating loads with Release or
19470   // ReleaseAcquire orderings.
19471   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19472   auto Ptr = AI->getPointerOperand();
19473
19474   // Before the load we need a fence. Here is an example lifted from
19475   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19476   // is required:
19477   // Thread 0:
19478   //   x.store(1, relaxed);
19479   //   r1 = y.fetch_add(0, release);
19480   // Thread 1:
19481   //   y.fetch_add(42, acquire);
19482   //   r2 = x.load(relaxed);
19483   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19484   // lowered to just a load without a fence. A mfence flushes the store buffer,
19485   // making the optimization clearly correct.
19486   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19487   // otherwise, we might be able to be more aggressive on relaxed idempotent
19488   // rmw. In practice, they do not look useful, so we don't try to be
19489   // especially clever.
19490   if (SynchScope == SingleThread)
19491     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19492     // the IR level, so we must wrap it in an intrinsic.
19493     return nullptr;
19494
19495   if (!hasMFENCE(*Subtarget))
19496     // FIXME: it might make sense to use a locked operation here but on a
19497     // different cache-line to prevent cache-line bouncing. In practice it
19498     // is probably a small win, and x86 processors without mfence are rare
19499     // enough that we do not bother.
19500     return nullptr;
19501
19502   Function *MFence =
19503       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19504   Builder.CreateCall(MFence, {});
19505
19506   // Finally we can emit the atomic load.
19507   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19508           AI->getType()->getPrimitiveSizeInBits());
19509   Loaded->setAtomic(Order, SynchScope);
19510   AI->replaceAllUsesWith(Loaded);
19511   AI->eraseFromParent();
19512   return Loaded;
19513 }
19514
19515 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19516                                  SelectionDAG &DAG) {
19517   SDLoc dl(Op);
19518   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19519     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19520   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19521     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19522
19523   // The only fence that needs an instruction is a sequentially-consistent
19524   // cross-thread fence.
19525   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19526     if (hasMFENCE(*Subtarget))
19527       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19528
19529     SDValue Chain = Op.getOperand(0);
19530     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19531     SDValue Ops[] = {
19532       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19533       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19534       DAG.getRegister(0, MVT::i32),            // Index
19535       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19536       DAG.getRegister(0, MVT::i32),            // Segment.
19537       Zero,
19538       Chain
19539     };
19540     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19541     return SDValue(Res, 0);
19542   }
19543
19544   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19545   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19546 }
19547
19548 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19549                              SelectionDAG &DAG) {
19550   MVT T = Op.getSimpleValueType();
19551   SDLoc DL(Op);
19552   unsigned Reg = 0;
19553   unsigned size = 0;
19554   switch(T.SimpleTy) {
19555   default: llvm_unreachable("Invalid value type!");
19556   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19557   case MVT::i16: Reg = X86::AX;  size = 2; break;
19558   case MVT::i32: Reg = X86::EAX; size = 4; break;
19559   case MVT::i64:
19560     assert(Subtarget->is64Bit() && "Node not type legal!");
19561     Reg = X86::RAX; size = 8;
19562     break;
19563   }
19564   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19565                                   Op.getOperand(2), SDValue());
19566   SDValue Ops[] = { cpIn.getValue(0),
19567                     Op.getOperand(1),
19568                     Op.getOperand(3),
19569                     DAG.getTargetConstant(size, DL, MVT::i8),
19570                     cpIn.getValue(1) };
19571   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19572   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19573   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19574                                            Ops, T, MMO);
19575
19576   SDValue cpOut =
19577     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19578   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19579                                       MVT::i32, cpOut.getValue(2));
19580   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19581                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19582                                 EFLAGS);
19583
19584   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19585   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19586   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19587   return SDValue();
19588 }
19589
19590 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19591                             SelectionDAG &DAG) {
19592   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19593   MVT DstVT = Op.getSimpleValueType();
19594
19595   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
19596       SrcVT == MVT::i64) {
19597     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19598     if (DstVT != MVT::f64)
19599       // This conversion needs to be expanded.
19600       return SDValue();
19601
19602     SDValue Op0 = Op->getOperand(0);
19603     SmallVector<SDValue, 16> Elts;
19604     SDLoc dl(Op);
19605     unsigned NumElts;
19606     MVT SVT;
19607     if (SrcVT.isVector()) {
19608       NumElts = SrcVT.getVectorNumElements();
19609       SVT = SrcVT.getVectorElementType();
19610
19611       // Widen the vector in input in the case of MVT::v2i32.
19612       // Example: from MVT::v2i32 to MVT::v4i32.
19613       for (unsigned i = 0, e = NumElts; i != e; ++i)
19614         Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, Op0,
19615                                    DAG.getIntPtrConstant(i, dl)));
19616     } else {
19617       assert(SrcVT == MVT::i64 && !Subtarget->is64Bit() &&
19618              "Unexpected source type in LowerBITCAST");
19619       Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
19620                                  DAG.getIntPtrConstant(0, dl)));
19621       Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
19622                                  DAG.getIntPtrConstant(1, dl)));
19623       NumElts = 2;
19624       SVT = MVT::i32;
19625     }
19626     // Explicitly mark the extra elements as Undef.
19627     Elts.append(NumElts, DAG.getUNDEF(SVT));
19628
19629     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19630     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19631     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19632     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19633                        DAG.getIntPtrConstant(0, dl));
19634   }
19635
19636   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19637          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19638   assert((DstVT == MVT::i64 ||
19639           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19640          "Unexpected custom BITCAST");
19641   // i64 <=> MMX conversions are Legal.
19642   if (SrcVT==MVT::i64 && DstVT.isVector())
19643     return Op;
19644   if (DstVT==MVT::i64 && SrcVT.isVector())
19645     return Op;
19646   // MMX <=> MMX conversions are Legal.
19647   if (SrcVT.isVector() && DstVT.isVector())
19648     return Op;
19649   // All other conversions need to be expanded.
19650   return SDValue();
19651 }
19652
19653 /// Compute the horizontal sum of bytes in V for the elements of VT.
19654 ///
19655 /// Requires V to be a byte vector and VT to be an integer vector type with
19656 /// wider elements than V's type. The width of the elements of VT determines
19657 /// how many bytes of V are summed horizontally to produce each element of the
19658 /// result.
19659 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19660                                       const X86Subtarget *Subtarget,
19661                                       SelectionDAG &DAG) {
19662   SDLoc DL(V);
19663   MVT ByteVecVT = V.getSimpleValueType();
19664   MVT EltVT = VT.getVectorElementType();
19665   int NumElts = VT.getVectorNumElements();
19666   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19667          "Expected value to have byte element type.");
19668   assert(EltVT != MVT::i8 &&
19669          "Horizontal byte sum only makes sense for wider elements!");
19670   unsigned VecSize = VT.getSizeInBits();
19671   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19672
19673   // PSADBW instruction horizontally add all bytes and leave the result in i64
19674   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19675   if (EltVT == MVT::i64) {
19676     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19677     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19678     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19679     return DAG.getBitcast(VT, V);
19680   }
19681
19682   if (EltVT == MVT::i32) {
19683     // We unpack the low half and high half into i32s interleaved with zeros so
19684     // that we can use PSADBW to horizontally sum them. The most useful part of
19685     // this is that it lines up the results of two PSADBW instructions to be
19686     // two v2i64 vectors which concatenated are the 4 population counts. We can
19687     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19688     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19689     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19690     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19691
19692     // Do the horizontal sums into two v2i64s.
19693     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19694     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19695     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19696                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19697     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19698                        DAG.getBitcast(ByteVecVT, High), Zeros);
19699
19700     // Merge them together.
19701     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19702     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19703                     DAG.getBitcast(ShortVecVT, Low),
19704                     DAG.getBitcast(ShortVecVT, High));
19705
19706     return DAG.getBitcast(VT, V);
19707   }
19708
19709   // The only element type left is i16.
19710   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19711
19712   // To obtain pop count for each i16 element starting from the pop count for
19713   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19714   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19715   // directly supported.
19716   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19717   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19718   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19719   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19720                   DAG.getBitcast(ByteVecVT, V));
19721   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19722 }
19723
19724 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19725                                         const X86Subtarget *Subtarget,
19726                                         SelectionDAG &DAG) {
19727   MVT VT = Op.getSimpleValueType();
19728   MVT EltVT = VT.getVectorElementType();
19729   unsigned VecSize = VT.getSizeInBits();
19730
19731   // Implement a lookup table in register by using an algorithm based on:
19732   // http://wm.ite.pl/articles/sse-popcount.html
19733   //
19734   // The general idea is that every lower byte nibble in the input vector is an
19735   // index into a in-register pre-computed pop count table. We then split up the
19736   // input vector in two new ones: (1) a vector with only the shifted-right
19737   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19738   // masked out higher ones) for each byte. PSHUB is used separately with both
19739   // to index the in-register table. Next, both are added and the result is a
19740   // i8 vector where each element contains the pop count for input byte.
19741   //
19742   // To obtain the pop count for elements != i8, we follow up with the same
19743   // approach and use additional tricks as described below.
19744   //
19745   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19746                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19747                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19748                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19749
19750   int NumByteElts = VecSize / 8;
19751   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19752   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19753   SmallVector<SDValue, 16> LUTVec;
19754   for (int i = 0; i < NumByteElts; ++i)
19755     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19756   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19757   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19758                                   DAG.getConstant(0x0F, DL, MVT::i8));
19759   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19760
19761   // High nibbles
19762   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19763   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19764   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19765
19766   // Low nibbles
19767   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19768
19769   // The input vector is used as the shuffle mask that index elements into the
19770   // LUT. After counting low and high nibbles, add the vector to obtain the
19771   // final pop count per i8 element.
19772   SDValue HighPopCnt =
19773       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19774   SDValue LowPopCnt =
19775       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19776   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19777
19778   if (EltVT == MVT::i8)
19779     return PopCnt;
19780
19781   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19782 }
19783
19784 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19785                                        const X86Subtarget *Subtarget,
19786                                        SelectionDAG &DAG) {
19787   MVT VT = Op.getSimpleValueType();
19788   assert(VT.is128BitVector() &&
19789          "Only 128-bit vector bitmath lowering supported.");
19790
19791   int VecSize = VT.getSizeInBits();
19792   MVT EltVT = VT.getVectorElementType();
19793   int Len = EltVT.getSizeInBits();
19794
19795   // This is the vectorized version of the "best" algorithm from
19796   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19797   // with a minor tweak to use a series of adds + shifts instead of vector
19798   // multiplications. Implemented for all integer vector types. We only use
19799   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19800   // much faster, even faster than using native popcnt instructions.
19801
19802   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19803     MVT VT = V.getSimpleValueType();
19804     SmallVector<SDValue, 32> Shifters(
19805         VT.getVectorNumElements(),
19806         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19807     return DAG.getNode(OpCode, DL, VT, V,
19808                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19809   };
19810   auto GetMask = [&](SDValue V, APInt Mask) {
19811     MVT VT = V.getSimpleValueType();
19812     SmallVector<SDValue, 32> Masks(
19813         VT.getVectorNumElements(),
19814         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19815     return DAG.getNode(ISD::AND, DL, VT, V,
19816                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19817   };
19818
19819   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19820   // x86, so set the SRL type to have elements at least i16 wide. This is
19821   // correct because all of our SRLs are followed immediately by a mask anyways
19822   // that handles any bits that sneak into the high bits of the byte elements.
19823   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19824
19825   SDValue V = Op;
19826
19827   // v = v - ((v >> 1) & 0x55555555...)
19828   SDValue Srl =
19829       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19830   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19831   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19832
19833   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19834   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19835   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19836   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19837   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19838
19839   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19840   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19841   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19842   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19843
19844   // At this point, V contains the byte-wise population count, and we are
19845   // merely doing a horizontal sum if necessary to get the wider element
19846   // counts.
19847   if (EltVT == MVT::i8)
19848     return V;
19849
19850   return LowerHorizontalByteSum(
19851       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19852       DAG);
19853 }
19854
19855 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19856                                 SelectionDAG &DAG) {
19857   MVT VT = Op.getSimpleValueType();
19858   // FIXME: Need to add AVX-512 support here!
19859   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19860          "Unknown CTPOP type to handle");
19861   SDLoc DL(Op.getNode());
19862   SDValue Op0 = Op.getOperand(0);
19863
19864   if (!Subtarget->hasSSSE3()) {
19865     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19866     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19867     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19868   }
19869
19870   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19871     unsigned NumElems = VT.getVectorNumElements();
19872
19873     // Extract each 128-bit vector, compute pop count and concat the result.
19874     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19875     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19876
19877     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19878                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19879                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19880   }
19881
19882   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19883 }
19884
19885 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19886                           SelectionDAG &DAG) {
19887   assert(Op.getSimpleValueType().isVector() &&
19888          "We only do custom lowering for vector population count.");
19889   return LowerVectorCTPOP(Op, Subtarget, DAG);
19890 }
19891
19892 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19893   SDNode *Node = Op.getNode();
19894   SDLoc dl(Node);
19895   EVT T = Node->getValueType(0);
19896   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19897                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19898   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19899                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19900                        Node->getOperand(0),
19901                        Node->getOperand(1), negOp,
19902                        cast<AtomicSDNode>(Node)->getMemOperand(),
19903                        cast<AtomicSDNode>(Node)->getOrdering(),
19904                        cast<AtomicSDNode>(Node)->getSynchScope());
19905 }
19906
19907 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19908   SDNode *Node = Op.getNode();
19909   SDLoc dl(Node);
19910   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19911
19912   // Convert seq_cst store -> xchg
19913   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19914   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19915   //        (The only way to get a 16-byte store is cmpxchg16b)
19916   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19917   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19918       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19919     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19920                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19921                                  Node->getOperand(0),
19922                                  Node->getOperand(1), Node->getOperand(2),
19923                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19924                                  cast<AtomicSDNode>(Node)->getOrdering(),
19925                                  cast<AtomicSDNode>(Node)->getSynchScope());
19926     return Swap.getValue(1);
19927   }
19928   // Other atomic stores have a simple pattern.
19929   return Op;
19930 }
19931
19932 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19933   MVT VT = Op.getNode()->getSimpleValueType(0);
19934
19935   // Let legalize expand this if it isn't a legal type yet.
19936   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19937     return SDValue();
19938
19939   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19940
19941   unsigned Opc;
19942   bool ExtraOp = false;
19943   switch (Op.getOpcode()) {
19944   default: llvm_unreachable("Invalid code");
19945   case ISD::ADDC: Opc = X86ISD::ADD; break;
19946   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19947   case ISD::SUBC: Opc = X86ISD::SUB; break;
19948   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19949   }
19950
19951   if (!ExtraOp)
19952     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19953                        Op.getOperand(1));
19954   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19955                      Op.getOperand(1), Op.getOperand(2));
19956 }
19957
19958 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19959                             SelectionDAG &DAG) {
19960   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19961
19962   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19963   // which returns the values as { float, float } (in XMM0) or
19964   // { double, double } (which is returned in XMM0, XMM1).
19965   SDLoc dl(Op);
19966   SDValue Arg = Op.getOperand(0);
19967   EVT ArgVT = Arg.getValueType();
19968   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19969
19970   TargetLowering::ArgListTy Args;
19971   TargetLowering::ArgListEntry Entry;
19972
19973   Entry.Node = Arg;
19974   Entry.Ty = ArgTy;
19975   Entry.isSExt = false;
19976   Entry.isZExt = false;
19977   Args.push_back(Entry);
19978
19979   bool isF64 = ArgVT == MVT::f64;
19980   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19981   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19982   // the results are returned via SRet in memory.
19983   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19985   SDValue Callee =
19986       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19987
19988   Type *RetTy = isF64
19989     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19990     : (Type*)VectorType::get(ArgTy, 4);
19991
19992   TargetLowering::CallLoweringInfo CLI(DAG);
19993   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19994     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19995
19996   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19997
19998   if (isF64)
19999     // Returned in xmm0 and xmm1.
20000     return CallResult.first;
20001
20002   // Returned in bits 0:31 and 32:64 xmm0.
20003   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
20004                                CallResult.first, DAG.getIntPtrConstant(0, dl));
20005   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
20006                                CallResult.first, DAG.getIntPtrConstant(1, dl));
20007   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
20008   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
20009 }
20010
20011 /// Widen a vector input to a vector of NVT.  The
20012 /// input vector must have the same element type as NVT.
20013 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
20014                             bool FillWithZeroes = false) {
20015   // Check if InOp already has the right width.
20016   MVT InVT = InOp.getSimpleValueType();
20017   if (InVT == NVT)
20018     return InOp;
20019
20020   if (InOp.isUndef())
20021     return DAG.getUNDEF(NVT);
20022
20023   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
20024          "input and widen element type must match");
20025
20026   unsigned InNumElts = InVT.getVectorNumElements();
20027   unsigned WidenNumElts = NVT.getVectorNumElements();
20028   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
20029          "Unexpected request for vector widening");
20030
20031   EVT EltVT = NVT.getVectorElementType();
20032
20033   SDLoc dl(InOp);
20034   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
20035       InOp.getNumOperands() == 2) {
20036     SDValue N1 = InOp.getOperand(1);
20037     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
20038         N1.isUndef()) {
20039       InOp = InOp.getOperand(0);
20040       InVT = InOp.getSimpleValueType();
20041       InNumElts = InVT.getVectorNumElements();
20042     }
20043   }
20044   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
20045       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
20046     SmallVector<SDValue, 16> Ops;
20047     for (unsigned i = 0; i < InNumElts; ++i)
20048       Ops.push_back(InOp.getOperand(i));
20049
20050     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
20051       DAG.getUNDEF(EltVT);
20052     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
20053       Ops.push_back(FillVal);
20054     return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
20055   }
20056   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
20057     DAG.getUNDEF(NVT);
20058   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
20059                      InOp, DAG.getIntPtrConstant(0, dl));
20060 }
20061
20062 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
20063                              SelectionDAG &DAG) {
20064   assert(Subtarget->hasAVX512() &&
20065          "MGATHER/MSCATTER are supported on AVX-512 arch only");
20066
20067   // X86 scatter kills mask register, so its type should be added to
20068   // the list of return values.
20069   // If the "scatter" has 2 return values, it is already handled.
20070   if (Op.getNode()->getNumValues() == 2)
20071     return Op;
20072
20073   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
20074   SDValue Src = N->getValue();
20075   MVT VT = Src.getSimpleValueType();
20076   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
20077   SDLoc dl(Op);
20078
20079   SDValue NewScatter;
20080   SDValue Index = N->getIndex();
20081   SDValue Mask = N->getMask();
20082   SDValue Chain = N->getChain();
20083   SDValue BasePtr = N->getBasePtr();
20084   MVT MemVT = N->getMemoryVT().getSimpleVT();
20085   MVT IndexVT = Index.getSimpleValueType();
20086   MVT MaskVT = Mask.getSimpleValueType();
20087
20088   if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
20089     // The v2i32 value was promoted to v2i64.
20090     // Now we "redo" the type legalizer's work and widen the original
20091     // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
20092     // with a shuffle.
20093     assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
20094            "Unexpected memory type");
20095     int ShuffleMask[] = {0, 2, -1, -1};
20096     Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
20097                                DAG.getUNDEF(MVT::v4i32), ShuffleMask);
20098     // Now we have 4 elements instead of 2.
20099     // Expand the index.
20100     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
20101     Index = ExtendToType(Index, NewIndexVT, DAG);
20102
20103     // Expand the mask with zeroes
20104     // Mask may be <2 x i64> or <2 x i1> at this moment
20105     assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
20106            "Unexpected mask type");
20107     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
20108     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20109     VT = MVT::v4i32;
20110   }
20111
20112   unsigned NumElts = VT.getVectorNumElements();
20113   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20114       !Index.getSimpleValueType().is512BitVector()) {
20115     // AVX512F supports only 512-bit vectors. Or data or index should
20116     // be 512 bit wide. If now the both index and data are 256-bit, but
20117     // the vector contains 8 elements, we just sign-extend the index
20118     if (IndexVT == MVT::v8i32)
20119       // Just extend index
20120       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20121     else {
20122       // The minimal number of elts in scatter is 8
20123       NumElts = 8;
20124       // Index
20125       MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20126       // Use original index here, do not modify the index twice
20127       Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
20128       if (IndexVT.getScalarType() == MVT::i32)
20129         Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20130
20131       // Mask
20132       // At this point we have promoted mask operand
20133       assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20134       MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20135       // Use the original mask here, do not modify the mask twice
20136       Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true);
20137
20138       // The value that should be stored
20139       MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20140       Src = ExtendToType(Src, NewVT, DAG);
20141     }
20142   }
20143   // If the mask is "wide" at this point - truncate it to i1 vector
20144   MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
20145   Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
20146
20147   // The mask is killed by scatter, add it to the values
20148   SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
20149   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
20150   NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
20151                                     N->getMemOperand());
20152   DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
20153   return SDValue(NewScatter.getNode(), 0);
20154 }
20155
20156 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
20157                           SelectionDAG &DAG) {
20158
20159   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
20160   MVT VT = Op.getSimpleValueType();
20161   SDValue Mask = N->getMask();
20162   SDLoc dl(Op);
20163
20164   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20165       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20166     // This operation is legal for targets with VLX, but without
20167     // VLX the vector should be widened to 512 bit
20168     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20169     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20170     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20171     SDValue Src0 = N->getSrc0();
20172     Src0 = ExtendToType(Src0, WideDataVT, DAG);
20173     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20174     SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
20175                                         N->getBasePtr(), Mask, Src0,
20176                                         N->getMemoryVT(), N->getMemOperand(),
20177                                         N->getExtensionType());
20178
20179     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20180                                  NewLoad.getValue(0),
20181                                  DAG.getIntPtrConstant(0, dl));
20182     SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
20183     return DAG.getMergeValues(RetOps, dl);
20184   }
20185   return Op;
20186 }
20187
20188 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
20189                            SelectionDAG &DAG) {
20190   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
20191   SDValue DataToStore = N->getValue();
20192   MVT VT = DataToStore.getSimpleValueType();
20193   SDValue Mask = N->getMask();
20194   SDLoc dl(Op);
20195
20196   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20197       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20198     // This operation is legal for targets with VLX, but without
20199     // VLX the vector should be widened to 512 bit
20200     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20201     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20202     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20203     DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
20204     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20205     return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
20206                               Mask, N->getMemoryVT(), N->getMemOperand(),
20207                               N->isTruncatingStore());
20208   }
20209   return Op;
20210 }
20211
20212 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
20213                             SelectionDAG &DAG) {
20214   assert(Subtarget->hasAVX512() &&
20215          "MGATHER/MSCATTER are supported on AVX-512 arch only");
20216
20217   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
20218   SDLoc dl(Op);
20219   MVT VT = Op.getSimpleValueType();
20220   SDValue Index = N->getIndex();
20221   SDValue Mask = N->getMask();
20222   SDValue Src0 = N->getValue();
20223   MVT IndexVT = Index.getSimpleValueType();
20224   MVT MaskVT = Mask.getSimpleValueType();
20225
20226   unsigned NumElts = VT.getVectorNumElements();
20227   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
20228
20229   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20230       !Index.getSimpleValueType().is512BitVector()) {
20231     // AVX512F supports only 512-bit vectors. Or data or index should
20232     // be 512 bit wide. If now the both index and data are 256-bit, but
20233     // the vector contains 8 elements, we just sign-extend the index
20234     if (NumElts == 8) {
20235       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20236       SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
20237                         N->getOperand(3), Index };
20238       DAG.UpdateNodeOperands(N, Ops);
20239       return Op;
20240     }
20241
20242     // Minimal number of elements in Gather
20243     NumElts = 8;
20244     // Index
20245     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20246     Index = ExtendToType(Index, NewIndexVT, DAG);
20247     if (IndexVT.getScalarType() == MVT::i32)
20248       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20249
20250     // Mask
20251     MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
20252     // At this point we have promoted mask operand
20253     assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20254     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20255     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20256     Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
20257
20258     // The pass-thru value
20259     MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20260     Src0 = ExtendToType(Src0, NewVT, DAG);
20261
20262     SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
20263     SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
20264                                             N->getMemoryVT(), dl, Ops,
20265                                             N->getMemOperand());
20266     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20267                                  NewGather.getValue(0),
20268                                  DAG.getIntPtrConstant(0, dl));
20269     SDValue RetOps[] = {Exract, NewGather.getValue(1)};
20270     return DAG.getMergeValues(RetOps, dl);
20271   }
20272   return Op;
20273 }
20274
20275 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
20276                                                     SelectionDAG &DAG) const {
20277   // TODO: Eventually, the lowering of these nodes should be informed by or
20278   // deferred to the GC strategy for the function in which they appear. For
20279   // now, however, they must be lowered to something. Since they are logically
20280   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20281   // require special handling for these nodes), lower them as literal NOOPs for
20282   // the time being.
20283   SmallVector<SDValue, 2> Ops;
20284
20285   Ops.push_back(Op.getOperand(0));
20286   if (Op->getGluedNode())
20287     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20288
20289   SDLoc OpDL(Op);
20290   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20291   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20292
20293   return NOOP;
20294 }
20295
20296 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
20297                                                   SelectionDAG &DAG) const {
20298   // TODO: Eventually, the lowering of these nodes should be informed by or
20299   // deferred to the GC strategy for the function in which they appear. For
20300   // now, however, they must be lowered to something. Since they are logically
20301   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20302   // require special handling for these nodes), lower them as literal NOOPs for
20303   // the time being.
20304   SmallVector<SDValue, 2> Ops;
20305
20306   Ops.push_back(Op.getOperand(0));
20307   if (Op->getGluedNode())
20308     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20309
20310   SDLoc OpDL(Op);
20311   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20312   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20313
20314   return NOOP;
20315 }
20316
20317 /// LowerOperation - Provide custom lowering hooks for some operations.
20318 ///
20319 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
20320   switch (Op.getOpcode()) {
20321   default: llvm_unreachable("Should not custom lower this!");
20322   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
20323   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
20324     return LowerCMP_SWAP(Op, Subtarget, DAG);
20325   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
20326   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
20327   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
20328   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
20329   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
20330   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
20331   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
20332   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
20333   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
20334   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
20335   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
20336   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
20337   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
20338   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
20339   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
20340   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
20341   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
20342   case ISD::SHL_PARTS:
20343   case ISD::SRA_PARTS:
20344   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
20345   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
20346   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
20347   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
20348   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
20349   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
20350   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
20351   case ISD::SIGN_EXTEND_VECTOR_INREG:
20352     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
20353   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
20354   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
20355   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
20356   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
20357   case ISD::FABS:
20358   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
20359   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
20360   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
20361   case ISD::SETCC:              return LowerSETCC(Op, DAG);
20362   case ISD::SETCCE:             return LowerSETCCE(Op, DAG);
20363   case ISD::SELECT:             return LowerSELECT(Op, DAG);
20364   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
20365   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
20366   case ISD::VASTART:            return LowerVASTART(Op, DAG);
20367   case ISD::VAARG:              return LowerVAARG(Op, DAG);
20368   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
20369   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
20370   case ISD::INTRINSIC_VOID:
20371   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
20372   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
20373   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
20374   case ISD::FRAME_TO_ARGS_OFFSET:
20375                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
20376   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
20377   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
20378   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
20379   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
20380   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
20381   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
20382   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
20383   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
20384   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
20385   case ISD::CTTZ:
20386   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
20387   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
20388   case ISD::UMUL_LOHI:
20389   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
20390   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
20391   case ISD::SRA:
20392   case ISD::SRL:
20393   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
20394   case ISD::SADDO:
20395   case ISD::UADDO:
20396   case ISD::SSUBO:
20397   case ISD::USUBO:
20398   case ISD::SMULO:
20399   case ISD::UMULO:              return LowerXALUO(Op, DAG);
20400   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20401   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
20402   case ISD::ADDC:
20403   case ISD::ADDE:
20404   case ISD::SUBC:
20405   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20406   case ISD::ADD:                return LowerADD(Op, DAG);
20407   case ISD::SUB:                return LowerSUB(Op, DAG);
20408   case ISD::SMAX:
20409   case ISD::SMIN:
20410   case ISD::UMAX:
20411   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
20412   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
20413   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
20414   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
20415   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
20416   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
20417   case ISD::GC_TRANSITION_START:
20418                                 return LowerGC_TRANSITION_START(Op, DAG);
20419   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
20420   }
20421 }
20422
20423 /// ReplaceNodeResults - Replace a node with an illegal result type
20424 /// with a new node built out of custom code.
20425 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20426                                            SmallVectorImpl<SDValue>&Results,
20427                                            SelectionDAG &DAG) const {
20428   SDLoc dl(N);
20429   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20430   switch (N->getOpcode()) {
20431   default:
20432     llvm_unreachable("Do not know how to custom type legalize this operation!");
20433   case X86ISD::AVG: {
20434     // Legalize types for X86ISD::AVG by expanding vectors.
20435     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20436
20437     auto InVT = N->getValueType(0);
20438     auto InVTSize = InVT.getSizeInBits();
20439     const unsigned RegSize =
20440         (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20441     assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20442            "512-bit vector requires AVX512");
20443     assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20444            "256-bit vector requires AVX2");
20445
20446     auto ElemVT = InVT.getVectorElementType();
20447     auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20448                                   RegSize / ElemVT.getSizeInBits());
20449     assert(RegSize % InVT.getSizeInBits() == 0);
20450     unsigned NumConcat = RegSize / InVT.getSizeInBits();
20451
20452     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20453     Ops[0] = N->getOperand(0);
20454     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20455     Ops[0] = N->getOperand(1);
20456     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20457
20458     SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20459     Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20460                                   DAG.getIntPtrConstant(0, dl)));
20461     return;
20462   }
20463   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20464   case X86ISD::FMINC:
20465   case X86ISD::FMIN:
20466   case X86ISD::FMAXC:
20467   case X86ISD::FMAX: {
20468     EVT VT = N->getValueType(0);
20469     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20470     SDValue UNDEF = DAG.getUNDEF(VT);
20471     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20472                               N->getOperand(0), UNDEF);
20473     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20474                               N->getOperand(1), UNDEF);
20475     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20476     return;
20477   }
20478   case ISD::SIGN_EXTEND_INREG:
20479   case ISD::ADDC:
20480   case ISD::ADDE:
20481   case ISD::SUBC:
20482   case ISD::SUBE:
20483     // We don't want to expand or promote these.
20484     return;
20485   case ISD::SDIV:
20486   case ISD::UDIV:
20487   case ISD::SREM:
20488   case ISD::UREM:
20489   case ISD::SDIVREM:
20490   case ISD::UDIVREM: {
20491     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20492     Results.push_back(V);
20493     return;
20494   }
20495   case ISD::FP_TO_SINT:
20496   case ISD::FP_TO_UINT: {
20497     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20498
20499     std::pair<SDValue,SDValue> Vals =
20500         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20501     SDValue FIST = Vals.first, StackSlot = Vals.second;
20502     if (FIST.getNode()) {
20503       EVT VT = N->getValueType(0);
20504       // Return a load from the stack slot.
20505       if (StackSlot.getNode())
20506         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20507                                       MachinePointerInfo(),
20508                                       false, false, false, 0));
20509       else
20510         Results.push_back(FIST);
20511     }
20512     return;
20513   }
20514   case ISD::UINT_TO_FP: {
20515     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20516     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20517         N->getValueType(0) != MVT::v2f32)
20518       return;
20519     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20520                                  N->getOperand(0));
20521     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20522                                      MVT::f64);
20523     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20524     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20525                              DAG.getBitcast(MVT::v2i64, VBias));
20526     Or = DAG.getBitcast(MVT::v2f64, Or);
20527     // TODO: Are there any fast-math-flags to propagate here?
20528     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20529     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20530     return;
20531   }
20532   case ISD::FP_ROUND: {
20533     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20534         return;
20535     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20536     Results.push_back(V);
20537     return;
20538   }
20539   case ISD::FP_EXTEND: {
20540     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20541     // No other ValueType for FP_EXTEND should reach this point.
20542     assert(N->getValueType(0) == MVT::v2f32 &&
20543            "Do not know how to legalize this Node");
20544     return;
20545   }
20546   case ISD::INTRINSIC_W_CHAIN: {
20547     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20548     switch (IntNo) {
20549     default : llvm_unreachable("Do not know how to custom type "
20550                                "legalize this intrinsic operation!");
20551     case Intrinsic::x86_rdtsc:
20552       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20553                                      Results);
20554     case Intrinsic::x86_rdtscp:
20555       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20556                                      Results);
20557     case Intrinsic::x86_rdpmc:
20558       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20559     }
20560   }
20561   case ISD::INTRINSIC_WO_CHAIN: {
20562     if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20563       Results.push_back(V);
20564     return;
20565   }
20566   case ISD::READCYCLECOUNTER: {
20567     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20568                                    Results);
20569   }
20570   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20571     EVT T = N->getValueType(0);
20572     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20573     bool Regs64bit = T == MVT::i128;
20574     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20575     SDValue cpInL, cpInH;
20576     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20577                         DAG.getConstant(0, dl, HalfT));
20578     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20579                         DAG.getConstant(1, dl, HalfT));
20580     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20581                              Regs64bit ? X86::RAX : X86::EAX,
20582                              cpInL, SDValue());
20583     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20584                              Regs64bit ? X86::RDX : X86::EDX,
20585                              cpInH, cpInL.getValue(1));
20586     SDValue swapInL, swapInH;
20587     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20588                           DAG.getConstant(0, dl, HalfT));
20589     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20590                           DAG.getConstant(1, dl, HalfT));
20591     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20592                                Regs64bit ? X86::RBX : X86::EBX,
20593                                swapInL, cpInH.getValue(1));
20594     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20595                                Regs64bit ? X86::RCX : X86::ECX,
20596                                swapInH, swapInL.getValue(1));
20597     SDValue Ops[] = { swapInH.getValue(0),
20598                       N->getOperand(1),
20599                       swapInH.getValue(1) };
20600     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20601     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20602     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20603                                   X86ISD::LCMPXCHG8_DAG;
20604     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20605     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20606                                         Regs64bit ? X86::RAX : X86::EAX,
20607                                         HalfT, Result.getValue(1));
20608     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20609                                         Regs64bit ? X86::RDX : X86::EDX,
20610                                         HalfT, cpOutL.getValue(2));
20611     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20612
20613     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20614                                         MVT::i32, cpOutH.getValue(2));
20615     SDValue Success =
20616         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20617                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20618     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20619
20620     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20621     Results.push_back(Success);
20622     Results.push_back(EFLAGS.getValue(1));
20623     return;
20624   }
20625   case ISD::ATOMIC_SWAP:
20626   case ISD::ATOMIC_LOAD_ADD:
20627   case ISD::ATOMIC_LOAD_SUB:
20628   case ISD::ATOMIC_LOAD_AND:
20629   case ISD::ATOMIC_LOAD_OR:
20630   case ISD::ATOMIC_LOAD_XOR:
20631   case ISD::ATOMIC_LOAD_NAND:
20632   case ISD::ATOMIC_LOAD_MIN:
20633   case ISD::ATOMIC_LOAD_MAX:
20634   case ISD::ATOMIC_LOAD_UMIN:
20635   case ISD::ATOMIC_LOAD_UMAX:
20636   case ISD::ATOMIC_LOAD: {
20637     // Delegate to generic TypeLegalization. Situations we can really handle
20638     // should have already been dealt with by AtomicExpandPass.cpp.
20639     break;
20640   }
20641   case ISD::BITCAST: {
20642     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20643     EVT DstVT = N->getValueType(0);
20644     EVT SrcVT = N->getOperand(0)->getValueType(0);
20645
20646     if (SrcVT != MVT::f64 ||
20647         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20648       return;
20649
20650     unsigned NumElts = DstVT.getVectorNumElements();
20651     EVT SVT = DstVT.getVectorElementType();
20652     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20653     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20654                                    MVT::v2f64, N->getOperand(0));
20655     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20656
20657     if (ExperimentalVectorWideningLegalization) {
20658       // If we are legalizing vectors by widening, we already have the desired
20659       // legal vector type, just return it.
20660       Results.push_back(ToVecInt);
20661       return;
20662     }
20663
20664     SmallVector<SDValue, 8> Elts;
20665     for (unsigned i = 0, e = NumElts; i != e; ++i)
20666       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20667                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
20668
20669     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20670   }
20671   }
20672 }
20673
20674 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20675   switch ((X86ISD::NodeType)Opcode) {
20676   case X86ISD::FIRST_NUMBER:       break;
20677   case X86ISD::BSF:                return "X86ISD::BSF";
20678   case X86ISD::BSR:                return "X86ISD::BSR";
20679   case X86ISD::SHLD:               return "X86ISD::SHLD";
20680   case X86ISD::SHRD:               return "X86ISD::SHRD";
20681   case X86ISD::FAND:               return "X86ISD::FAND";
20682   case X86ISD::FANDN:              return "X86ISD::FANDN";
20683   case X86ISD::FOR:                return "X86ISD::FOR";
20684   case X86ISD::FXOR:               return "X86ISD::FXOR";
20685   case X86ISD::FILD:               return "X86ISD::FILD";
20686   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
20687   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20688   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20689   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20690   case X86ISD::FLD:                return "X86ISD::FLD";
20691   case X86ISD::FST:                return "X86ISD::FST";
20692   case X86ISD::CALL:               return "X86ISD::CALL";
20693   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
20694   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
20695   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
20696   case X86ISD::BT:                 return "X86ISD::BT";
20697   case X86ISD::CMP:                return "X86ISD::CMP";
20698   case X86ISD::COMI:               return "X86ISD::COMI";
20699   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
20700   case X86ISD::CMPM:               return "X86ISD::CMPM";
20701   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
20702   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
20703   case X86ISD::SETCC:              return "X86ISD::SETCC";
20704   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
20705   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
20706   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
20707   case X86ISD::CMOV:               return "X86ISD::CMOV";
20708   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
20709   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
20710   case X86ISD::IRET:               return "X86ISD::IRET";
20711   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
20712   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
20713   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
20714   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
20715   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
20716   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
20717   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
20718   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
20719   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
20720   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
20721   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
20722   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
20723   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
20724   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
20725   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
20726   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
20727   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
20728   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
20729   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
20730   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
20731   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
20732   case X86ISD::HADD:               return "X86ISD::HADD";
20733   case X86ISD::HSUB:               return "X86ISD::HSUB";
20734   case X86ISD::FHADD:              return "X86ISD::FHADD";
20735   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
20736   case X86ISD::ABS:                return "X86ISD::ABS";
20737   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
20738   case X86ISD::FMAX:               return "X86ISD::FMAX";
20739   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
20740   case X86ISD::FMIN:               return "X86ISD::FMIN";
20741   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
20742   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20743   case X86ISD::FMINC:              return "X86ISD::FMINC";
20744   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20745   case X86ISD::FRCP:               return "X86ISD::FRCP";
20746   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
20747   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
20748   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20749   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20750   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20751   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20752   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20753   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20754   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20755   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20756   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20757   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20758   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20759   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20760   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20761   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20762   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20763   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20764   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20765   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20766   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20767   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20768   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20769   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20770   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20771   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20772   case X86ISD::CVT2MASK:           return "X86ISD::CVT2MASK";
20773   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20774   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20775   case X86ISD::VSHL:               return "X86ISD::VSHL";
20776   case X86ISD::VSRL:               return "X86ISD::VSRL";
20777   case X86ISD::VSRA:               return "X86ISD::VSRA";
20778   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20779   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20780   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20781   case X86ISD::VROTLI:             return "X86ISD::VROTLI";
20782   case X86ISD::VROTRI:             return "X86ISD::VROTRI";
20783   case X86ISD::CMPP:               return "X86ISD::CMPP";
20784   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20785   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20786   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20787   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20788   case X86ISD::ADD:                return "X86ISD::ADD";
20789   case X86ISD::SUB:                return "X86ISD::SUB";
20790   case X86ISD::ADC:                return "X86ISD::ADC";
20791   case X86ISD::SBB:                return "X86ISD::SBB";
20792   case X86ISD::SMUL:               return "X86ISD::SMUL";
20793   case X86ISD::UMUL:               return "X86ISD::UMUL";
20794   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20795   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20796   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20797   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20798   case X86ISD::INC:                return "X86ISD::INC";
20799   case X86ISD::DEC:                return "X86ISD::DEC";
20800   case X86ISD::OR:                 return "X86ISD::OR";
20801   case X86ISD::XOR:                return "X86ISD::XOR";
20802   case X86ISD::AND:                return "X86ISD::AND";
20803   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20804   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20805   case X86ISD::PTEST:              return "X86ISD::PTEST";
20806   case X86ISD::TESTP:              return "X86ISD::TESTP";
20807   case X86ISD::TESTM:              return "X86ISD::TESTM";
20808   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20809   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20810   case X86ISD::KTEST:              return "X86ISD::KTEST";
20811   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20812   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20813   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20814   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20815   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20816   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20817   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20818   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20819   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20820   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20821   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20822   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20823   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20824   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20825   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20826   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20827   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20828   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20829   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20830   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20831   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20832   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20833   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
20834   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20835   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20836   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20837   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20838   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20839   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20840   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20841   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20842   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20843   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20844   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20845   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20846   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20847   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20848   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20849   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20850   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20851   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20852   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20853   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20854   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20855   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20856   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20857   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20858   case X86ISD::SAHF:               return "X86ISD::SAHF";
20859   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20860   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20861   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20862   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20863   case X86ISD::VPROT:              return "X86ISD::VPROT";
20864   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20865   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20866   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20867   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20868   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20869   case X86ISD::FMADD:              return "X86ISD::FMADD";
20870   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20871   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20872   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20873   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20874   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20875   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20876   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20877   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20878   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20879   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20880   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20881   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20882   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20883   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20884   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20885   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20886   case X86ISD::XTEST:              return "X86ISD::XTEST";
20887   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20888   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20889   case X86ISD::SELECT:             return "X86ISD::SELECT";
20890   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20891   case X86ISD::RCP28:              return "X86ISD::RCP28";
20892   case X86ISD::EXP2:               return "X86ISD::EXP2";
20893   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20894   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20895   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20896   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20897   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20898   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20899   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20900   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20901   case X86ISD::ADDS:               return "X86ISD::ADDS";
20902   case X86ISD::SUBS:               return "X86ISD::SUBS";
20903   case X86ISD::AVG:                return "X86ISD::AVG";
20904   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20905   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20906   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20907   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20908   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20909   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20910   case X86ISD::VFPCLASSS:          return "X86ISD::VFPCLASSS";
20911   }
20912   return nullptr;
20913 }
20914
20915 // isLegalAddressingMode - Return true if the addressing mode represented
20916 // by AM is legal for this target, for a load/store of the specified type.
20917 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20918                                               const AddrMode &AM, Type *Ty,
20919                                               unsigned AS) const {
20920   // X86 supports extremely general addressing modes.
20921   CodeModel::Model M = getTargetMachine().getCodeModel();
20922   Reloc::Model R = getTargetMachine().getRelocationModel();
20923
20924   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20925   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20926     return false;
20927
20928   if (AM.BaseGV) {
20929     unsigned GVFlags =
20930       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20931
20932     // If a reference to this global requires an extra load, we can't fold it.
20933     if (isGlobalStubReference(GVFlags))
20934       return false;
20935
20936     // If BaseGV requires a register for the PIC base, we cannot also have a
20937     // BaseReg specified.
20938     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20939       return false;
20940
20941     // If lower 4G is not available, then we must use rip-relative addressing.
20942     if ((M != CodeModel::Small || R != Reloc::Static) &&
20943         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20944       return false;
20945   }
20946
20947   switch (AM.Scale) {
20948   case 0:
20949   case 1:
20950   case 2:
20951   case 4:
20952   case 8:
20953     // These scales always work.
20954     break;
20955   case 3:
20956   case 5:
20957   case 9:
20958     // These scales are formed with basereg+scalereg.  Only accept if there is
20959     // no basereg yet.
20960     if (AM.HasBaseReg)
20961       return false;
20962     break;
20963   default:  // Other stuff never works.
20964     return false;
20965   }
20966
20967   return true;
20968 }
20969
20970 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20971   unsigned Bits = Ty->getScalarSizeInBits();
20972
20973   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20974   // particularly cheaper than those without.
20975   if (Bits == 8)
20976     return false;
20977
20978   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20979   // variable shifts just as cheap as scalar ones.
20980   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20981     return false;
20982
20983   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20984   // fully general vector.
20985   return true;
20986 }
20987
20988 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20989   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20990     return false;
20991   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20992   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20993   return NumBits1 > NumBits2;
20994 }
20995
20996 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20997   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20998     return false;
20999
21000   if (!isTypeLegal(EVT::getEVT(Ty1)))
21001     return false;
21002
21003   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
21004
21005   // Assuming the caller doesn't have a zeroext or signext return parameter,
21006   // truncation all the way down to i1 is valid.
21007   return true;
21008 }
21009
21010 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
21011   return isInt<32>(Imm);
21012 }
21013
21014 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
21015   // Can also use sub to handle negated immediates.
21016   return isInt<32>(Imm);
21017 }
21018
21019 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
21020   if (!VT1.isInteger() || !VT2.isInteger())
21021     return false;
21022   unsigned NumBits1 = VT1.getSizeInBits();
21023   unsigned NumBits2 = VT2.getSizeInBits();
21024   return NumBits1 > NumBits2;
21025 }
21026
21027 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
21028   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
21029   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
21030 }
21031
21032 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
21033   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
21034   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
21035 }
21036
21037 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
21038   EVT VT1 = Val.getValueType();
21039   if (isZExtFree(VT1, VT2))
21040     return true;
21041
21042   if (Val.getOpcode() != ISD::LOAD)
21043     return false;
21044
21045   if (!VT1.isSimple() || !VT1.isInteger() ||
21046       !VT2.isSimple() || !VT2.isInteger())
21047     return false;
21048
21049   switch (VT1.getSimpleVT().SimpleTy) {
21050   default: break;
21051   case MVT::i8:
21052   case MVT::i16:
21053   case MVT::i32:
21054     // X86 has 8, 16, and 32-bit zero-extending loads.
21055     return true;
21056   }
21057
21058   return false;
21059 }
21060
21061 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
21062
21063 bool
21064 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
21065   if (!Subtarget->hasAnyFMA())
21066     return false;
21067
21068   VT = VT.getScalarType();
21069
21070   if (!VT.isSimple())
21071     return false;
21072
21073   switch (VT.getSimpleVT().SimpleTy) {
21074   case MVT::f32:
21075   case MVT::f64:
21076     return true;
21077   default:
21078     break;
21079   }
21080
21081   return false;
21082 }
21083
21084 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
21085   // i16 instructions are longer (0x66 prefix) and potentially slower.
21086   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
21087 }
21088
21089 /// isShuffleMaskLegal - Targets can use this to indicate that they only
21090 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
21091 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
21092 /// are assumed to be legal.
21093 bool
21094 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
21095                                       EVT VT) const {
21096   if (!VT.isSimple())
21097     return false;
21098
21099   // Not for i1 vectors
21100   if (VT.getSimpleVT().getScalarType() == MVT::i1)
21101     return false;
21102
21103   // Very little shuffling can be done for 64-bit vectors right now.
21104   if (VT.getSimpleVT().getSizeInBits() == 64)
21105     return false;
21106
21107   // We only care that the types being shuffled are legal. The lowering can
21108   // handle any possible shuffle mask that results.
21109   return isTypeLegal(VT.getSimpleVT());
21110 }
21111
21112 bool
21113 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
21114                                           EVT VT) const {
21115   // Just delegate to the generic legality, clear masks aren't special.
21116   return isShuffleMaskLegal(Mask, VT);
21117 }
21118
21119 //===----------------------------------------------------------------------===//
21120 //                           X86 Scheduler Hooks
21121 //===----------------------------------------------------------------------===//
21122
21123 /// Utility function to emit xbegin specifying the start of an RTM region.
21124 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
21125                                      const TargetInstrInfo *TII) {
21126   DebugLoc DL = MI->getDebugLoc();
21127
21128   const BasicBlock *BB = MBB->getBasicBlock();
21129   MachineFunction::iterator I = ++MBB->getIterator();
21130
21131   // For the v = xbegin(), we generate
21132   //
21133   // thisMBB:
21134   //  xbegin sinkMBB
21135   //
21136   // mainMBB:
21137   //  eax = -1
21138   //
21139   // sinkMBB:
21140   //  v = eax
21141
21142   MachineBasicBlock *thisMBB = MBB;
21143   MachineFunction *MF = MBB->getParent();
21144   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21145   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21146   MF->insert(I, mainMBB);
21147   MF->insert(I, sinkMBB);
21148
21149   // Transfer the remainder of BB and its successor edges to sinkMBB.
21150   sinkMBB->splice(sinkMBB->begin(), MBB,
21151                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21152   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21153
21154   // thisMBB:
21155   //  xbegin sinkMBB
21156   //  # fallthrough to mainMBB
21157   //  # abortion to sinkMBB
21158   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
21159   thisMBB->addSuccessor(mainMBB);
21160   thisMBB->addSuccessor(sinkMBB);
21161
21162   // mainMBB:
21163   //  EAX = -1
21164   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
21165   mainMBB->addSuccessor(sinkMBB);
21166
21167   // sinkMBB:
21168   // EAX is live into the sinkMBB
21169   sinkMBB->addLiveIn(X86::EAX);
21170   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21171           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21172     .addReg(X86::EAX);
21173
21174   MI->eraseFromParent();
21175   return sinkMBB;
21176 }
21177
21178 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
21179 // or XMM0_V32I8 in AVX all of this code can be replaced with that
21180 // in the .td file.
21181 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
21182                                        const TargetInstrInfo *TII) {
21183   unsigned Opc;
21184   switch (MI->getOpcode()) {
21185   default: llvm_unreachable("illegal opcode!");
21186   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
21187   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
21188   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
21189   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
21190   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
21191   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
21192   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
21193   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
21194   }
21195
21196   DebugLoc dl = MI->getDebugLoc();
21197   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21198
21199   unsigned NumArgs = MI->getNumOperands();
21200   for (unsigned i = 1; i < NumArgs; ++i) {
21201     MachineOperand &Op = MI->getOperand(i);
21202     if (!(Op.isReg() && Op.isImplicit()))
21203       MIB.addOperand(Op);
21204   }
21205   if (MI->hasOneMemOperand())
21206     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21207
21208   BuildMI(*BB, MI, dl,
21209     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21210     .addReg(X86::XMM0);
21211
21212   MI->eraseFromParent();
21213   return BB;
21214 }
21215
21216 // FIXME: Custom handling because TableGen doesn't support multiple implicit
21217 // defs in an instruction pattern
21218 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
21219                                        const TargetInstrInfo *TII) {
21220   unsigned Opc;
21221   switch (MI->getOpcode()) {
21222   default: llvm_unreachable("illegal opcode!");
21223   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
21224   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
21225   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
21226   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
21227   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
21228   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
21229   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
21230   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
21231   }
21232
21233   DebugLoc dl = MI->getDebugLoc();
21234   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21235
21236   unsigned NumArgs = MI->getNumOperands(); // remove the results
21237   for (unsigned i = 1; i < NumArgs; ++i) {
21238     MachineOperand &Op = MI->getOperand(i);
21239     if (!(Op.isReg() && Op.isImplicit()))
21240       MIB.addOperand(Op);
21241   }
21242   if (MI->hasOneMemOperand())
21243     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21244
21245   BuildMI(*BB, MI, dl,
21246     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21247     .addReg(X86::ECX);
21248
21249   MI->eraseFromParent();
21250   return BB;
21251 }
21252
21253 static MachineBasicBlock *EmitWRPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21254                                      const X86Subtarget *Subtarget) {
21255   DebugLoc dl = MI->getDebugLoc();
21256   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21257
21258   // insert input VAL into EAX
21259   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
21260                            .addReg(MI->getOperand(0).getReg());
21261   // insert zero to ECX
21262   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21263                            .addReg(X86::ECX)
21264                            .addReg(X86::ECX);
21265   // insert zero to EDX
21266   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::EDX)
21267                            .addReg(X86::EDX)
21268                            .addReg(X86::EDX);
21269   // insert WRPKRU instruction
21270   BuildMI(*BB, MI, dl, TII->get(X86::WRPKRUr));
21271
21272   MI->eraseFromParent(); // The pseudo is gone now.
21273   return BB;
21274 }
21275
21276 static MachineBasicBlock *EmitRDPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21277                                      const X86Subtarget *Subtarget) {
21278   DebugLoc dl = MI->getDebugLoc();
21279   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21280
21281   // insert zero to ECX
21282   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21283                            .addReg(X86::ECX)
21284                            .addReg(X86::ECX);
21285   // insert RDPKRU instruction
21286   BuildMI(*BB, MI, dl, TII->get(X86::RDPKRUr));
21287   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21288                            .addReg(X86::EAX);
21289
21290   MI->eraseFromParent(); // The pseudo is gone now.
21291   return BB;
21292 }
21293
21294 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
21295                                       const X86Subtarget *Subtarget) {
21296   DebugLoc dl = MI->getDebugLoc();
21297   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21298   // Address into RAX/EAX, other two args into ECX, EDX.
21299   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
21300   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
21301   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
21302   for (int i = 0; i < X86::AddrNumOperands; ++i)
21303     MIB.addOperand(MI->getOperand(i));
21304
21305   unsigned ValOps = X86::AddrNumOperands;
21306   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
21307     .addReg(MI->getOperand(ValOps).getReg());
21308   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
21309     .addReg(MI->getOperand(ValOps+1).getReg());
21310
21311   // The instruction doesn't actually take any operands though.
21312   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
21313
21314   MI->eraseFromParent(); // The pseudo is gone now.
21315   return BB;
21316 }
21317
21318 MachineBasicBlock *
21319 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
21320                                                  MachineBasicBlock *MBB) const {
21321   // Emit va_arg instruction on X86-64.
21322
21323   // Operands to this pseudo-instruction:
21324   // 0  ) Output        : destination address (reg)
21325   // 1-5) Input         : va_list address (addr, i64mem)
21326   // 6  ) ArgSize       : Size (in bytes) of vararg type
21327   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
21328   // 8  ) Align         : Alignment of type
21329   // 9  ) EFLAGS (implicit-def)
21330
21331   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
21332   static_assert(X86::AddrNumOperands == 5,
21333                 "VAARG_64 assumes 5 address operands");
21334
21335   unsigned DestReg = MI->getOperand(0).getReg();
21336   MachineOperand &Base = MI->getOperand(1);
21337   MachineOperand &Scale = MI->getOperand(2);
21338   MachineOperand &Index = MI->getOperand(3);
21339   MachineOperand &Disp = MI->getOperand(4);
21340   MachineOperand &Segment = MI->getOperand(5);
21341   unsigned ArgSize = MI->getOperand(6).getImm();
21342   unsigned ArgMode = MI->getOperand(7).getImm();
21343   unsigned Align = MI->getOperand(8).getImm();
21344
21345   // Memory Reference
21346   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
21347   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21348   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21349
21350   // Machine Information
21351   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21352   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
21353   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
21354   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
21355   DebugLoc DL = MI->getDebugLoc();
21356
21357   // struct va_list {
21358   //   i32   gp_offset
21359   //   i32   fp_offset
21360   //   i64   overflow_area (address)
21361   //   i64   reg_save_area (address)
21362   // }
21363   // sizeof(va_list) = 24
21364   // alignment(va_list) = 8
21365
21366   unsigned TotalNumIntRegs = 6;
21367   unsigned TotalNumXMMRegs = 8;
21368   bool UseGPOffset = (ArgMode == 1);
21369   bool UseFPOffset = (ArgMode == 2);
21370   unsigned MaxOffset = TotalNumIntRegs * 8 +
21371                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
21372
21373   /* Align ArgSize to a multiple of 8 */
21374   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
21375   bool NeedsAlign = (Align > 8);
21376
21377   MachineBasicBlock *thisMBB = MBB;
21378   MachineBasicBlock *overflowMBB;
21379   MachineBasicBlock *offsetMBB;
21380   MachineBasicBlock *endMBB;
21381
21382   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
21383   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
21384   unsigned OffsetReg = 0;
21385
21386   if (!UseGPOffset && !UseFPOffset) {
21387     // If we only pull from the overflow region, we don't create a branch.
21388     // We don't need to alter control flow.
21389     OffsetDestReg = 0; // unused
21390     OverflowDestReg = DestReg;
21391
21392     offsetMBB = nullptr;
21393     overflowMBB = thisMBB;
21394     endMBB = thisMBB;
21395   } else {
21396     // First emit code to check if gp_offset (or fp_offset) is below the bound.
21397     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
21398     // If not, pull from overflow_area. (branch to overflowMBB)
21399     //
21400     //       thisMBB
21401     //         |     .
21402     //         |        .
21403     //     offsetMBB   overflowMBB
21404     //         |        .
21405     //         |     .
21406     //        endMBB
21407
21408     // Registers for the PHI in endMBB
21409     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
21410     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
21411
21412     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21413     MachineFunction *MF = MBB->getParent();
21414     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21415     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21416     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21417
21418     MachineFunction::iterator MBBIter = ++MBB->getIterator();
21419
21420     // Insert the new basic blocks
21421     MF->insert(MBBIter, offsetMBB);
21422     MF->insert(MBBIter, overflowMBB);
21423     MF->insert(MBBIter, endMBB);
21424
21425     // Transfer the remainder of MBB and its successor edges to endMBB.
21426     endMBB->splice(endMBB->begin(), thisMBB,
21427                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
21428     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
21429
21430     // Make offsetMBB and overflowMBB successors of thisMBB
21431     thisMBB->addSuccessor(offsetMBB);
21432     thisMBB->addSuccessor(overflowMBB);
21433
21434     // endMBB is a successor of both offsetMBB and overflowMBB
21435     offsetMBB->addSuccessor(endMBB);
21436     overflowMBB->addSuccessor(endMBB);
21437
21438     // Load the offset value into a register
21439     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21440     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21441       .addOperand(Base)
21442       .addOperand(Scale)
21443       .addOperand(Index)
21444       .addDisp(Disp, UseFPOffset ? 4 : 0)
21445       .addOperand(Segment)
21446       .setMemRefs(MMOBegin, MMOEnd);
21447
21448     // Check if there is enough room left to pull this argument.
21449     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21450       .addReg(OffsetReg)
21451       .addImm(MaxOffset + 8 - ArgSizeA8);
21452
21453     // Branch to "overflowMBB" if offset >= max
21454     // Fall through to "offsetMBB" otherwise
21455     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21456       .addMBB(overflowMBB);
21457   }
21458
21459   // In offsetMBB, emit code to use the reg_save_area.
21460   if (offsetMBB) {
21461     assert(OffsetReg != 0);
21462
21463     // Read the reg_save_area address.
21464     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21465     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21466       .addOperand(Base)
21467       .addOperand(Scale)
21468       .addOperand(Index)
21469       .addDisp(Disp, 16)
21470       .addOperand(Segment)
21471       .setMemRefs(MMOBegin, MMOEnd);
21472
21473     // Zero-extend the offset
21474     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21475       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21476         .addImm(0)
21477         .addReg(OffsetReg)
21478         .addImm(X86::sub_32bit);
21479
21480     // Add the offset to the reg_save_area to get the final address.
21481     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21482       .addReg(OffsetReg64)
21483       .addReg(RegSaveReg);
21484
21485     // Compute the offset for the next argument
21486     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21487     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21488       .addReg(OffsetReg)
21489       .addImm(UseFPOffset ? 16 : 8);
21490
21491     // Store it back into the va_list.
21492     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21493       .addOperand(Base)
21494       .addOperand(Scale)
21495       .addOperand(Index)
21496       .addDisp(Disp, UseFPOffset ? 4 : 0)
21497       .addOperand(Segment)
21498       .addReg(NextOffsetReg)
21499       .setMemRefs(MMOBegin, MMOEnd);
21500
21501     // Jump to endMBB
21502     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21503       .addMBB(endMBB);
21504   }
21505
21506   //
21507   // Emit code to use overflow area
21508   //
21509
21510   // Load the overflow_area address into a register.
21511   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21512   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21513     .addOperand(Base)
21514     .addOperand(Scale)
21515     .addOperand(Index)
21516     .addDisp(Disp, 8)
21517     .addOperand(Segment)
21518     .setMemRefs(MMOBegin, MMOEnd);
21519
21520   // If we need to align it, do so. Otherwise, just copy the address
21521   // to OverflowDestReg.
21522   if (NeedsAlign) {
21523     // Align the overflow address
21524     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21525     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21526
21527     // aligned_addr = (addr + (align-1)) & ~(align-1)
21528     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21529       .addReg(OverflowAddrReg)
21530       .addImm(Align-1);
21531
21532     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21533       .addReg(TmpReg)
21534       .addImm(~(uint64_t)(Align-1));
21535   } else {
21536     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21537       .addReg(OverflowAddrReg);
21538   }
21539
21540   // Compute the next overflow address after this argument.
21541   // (the overflow address should be kept 8-byte aligned)
21542   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21543   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21544     .addReg(OverflowDestReg)
21545     .addImm(ArgSizeA8);
21546
21547   // Store the new overflow address.
21548   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21549     .addOperand(Base)
21550     .addOperand(Scale)
21551     .addOperand(Index)
21552     .addDisp(Disp, 8)
21553     .addOperand(Segment)
21554     .addReg(NextAddrReg)
21555     .setMemRefs(MMOBegin, MMOEnd);
21556
21557   // If we branched, emit the PHI to the front of endMBB.
21558   if (offsetMBB) {
21559     BuildMI(*endMBB, endMBB->begin(), DL,
21560             TII->get(X86::PHI), DestReg)
21561       .addReg(OffsetDestReg).addMBB(offsetMBB)
21562       .addReg(OverflowDestReg).addMBB(overflowMBB);
21563   }
21564
21565   // Erase the pseudo instruction
21566   MI->eraseFromParent();
21567
21568   return endMBB;
21569 }
21570
21571 MachineBasicBlock *
21572 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21573                                                  MachineInstr *MI,
21574                                                  MachineBasicBlock *MBB) const {
21575   // Emit code to save XMM registers to the stack. The ABI says that the
21576   // number of registers to save is given in %al, so it's theoretically
21577   // possible to do an indirect jump trick to avoid saving all of them,
21578   // however this code takes a simpler approach and just executes all
21579   // of the stores if %al is non-zero. It's less code, and it's probably
21580   // easier on the hardware branch predictor, and stores aren't all that
21581   // expensive anyway.
21582
21583   // Create the new basic blocks. One block contains all the XMM stores,
21584   // and one block is the final destination regardless of whether any
21585   // stores were performed.
21586   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21587   MachineFunction *F = MBB->getParent();
21588   MachineFunction::iterator MBBIter = ++MBB->getIterator();
21589   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21590   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21591   F->insert(MBBIter, XMMSaveMBB);
21592   F->insert(MBBIter, EndMBB);
21593
21594   // Transfer the remainder of MBB and its successor edges to EndMBB.
21595   EndMBB->splice(EndMBB->begin(), MBB,
21596                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21597   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21598
21599   // The original block will now fall through to the XMM save block.
21600   MBB->addSuccessor(XMMSaveMBB);
21601   // The XMMSaveMBB will fall through to the end block.
21602   XMMSaveMBB->addSuccessor(EndMBB);
21603
21604   // Now add the instructions.
21605   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21606   DebugLoc DL = MI->getDebugLoc();
21607
21608   unsigned CountReg = MI->getOperand(0).getReg();
21609   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21610   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21611
21612   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21613     // If %al is 0, branch around the XMM save block.
21614     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21615     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21616     MBB->addSuccessor(EndMBB);
21617   }
21618
21619   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21620   // that was just emitted, but clearly shouldn't be "saved".
21621   assert((MI->getNumOperands() <= 3 ||
21622           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21623           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21624          && "Expected last argument to be EFLAGS");
21625   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21626   // In the XMM save block, save all the XMM argument registers.
21627   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21628     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21629     MachineMemOperand *MMO = F->getMachineMemOperand(
21630         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21631         MachineMemOperand::MOStore,
21632         /*Size=*/16, /*Align=*/16);
21633     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21634       .addFrameIndex(RegSaveFrameIndex)
21635       .addImm(/*Scale=*/1)
21636       .addReg(/*IndexReg=*/0)
21637       .addImm(/*Disp=*/Offset)
21638       .addReg(/*Segment=*/0)
21639       .addReg(MI->getOperand(i).getReg())
21640       .addMemOperand(MMO);
21641   }
21642
21643   MI->eraseFromParent();   // The pseudo instruction is gone now.
21644
21645   return EndMBB;
21646 }
21647
21648 // The EFLAGS operand of SelectItr might be missing a kill marker
21649 // because there were multiple uses of EFLAGS, and ISel didn't know
21650 // which to mark. Figure out whether SelectItr should have had a
21651 // kill marker, and set it if it should. Returns the correct kill
21652 // marker value.
21653 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21654                                      MachineBasicBlock* BB,
21655                                      const TargetRegisterInfo* TRI) {
21656   // Scan forward through BB for a use/def of EFLAGS.
21657   MachineBasicBlock::iterator miI(std::next(SelectItr));
21658   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21659     const MachineInstr& mi = *miI;
21660     if (mi.readsRegister(X86::EFLAGS))
21661       return false;
21662     if (mi.definesRegister(X86::EFLAGS))
21663       break; // Should have kill-flag - update below.
21664   }
21665
21666   // If we hit the end of the block, check whether EFLAGS is live into a
21667   // successor.
21668   if (miI == BB->end()) {
21669     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21670                                           sEnd = BB->succ_end();
21671          sItr != sEnd; ++sItr) {
21672       MachineBasicBlock* succ = *sItr;
21673       if (succ->isLiveIn(X86::EFLAGS))
21674         return false;
21675     }
21676   }
21677
21678   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21679   // out. SelectMI should have a kill flag on EFLAGS.
21680   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21681   return true;
21682 }
21683
21684 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21685 // together with other CMOV pseudo-opcodes into a single basic-block with
21686 // conditional jump around it.
21687 static bool isCMOVPseudo(MachineInstr *MI) {
21688   switch (MI->getOpcode()) {
21689   case X86::CMOV_FR32:
21690   case X86::CMOV_FR64:
21691   case X86::CMOV_GR8:
21692   case X86::CMOV_GR16:
21693   case X86::CMOV_GR32:
21694   case X86::CMOV_RFP32:
21695   case X86::CMOV_RFP64:
21696   case X86::CMOV_RFP80:
21697   case X86::CMOV_V2F64:
21698   case X86::CMOV_V2I64:
21699   case X86::CMOV_V4F32:
21700   case X86::CMOV_V4F64:
21701   case X86::CMOV_V4I64:
21702   case X86::CMOV_V16F32:
21703   case X86::CMOV_V8F32:
21704   case X86::CMOV_V8F64:
21705   case X86::CMOV_V8I64:
21706   case X86::CMOV_V8I1:
21707   case X86::CMOV_V16I1:
21708   case X86::CMOV_V32I1:
21709   case X86::CMOV_V64I1:
21710     return true;
21711
21712   default:
21713     return false;
21714   }
21715 }
21716
21717 MachineBasicBlock *
21718 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21719                                      MachineBasicBlock *BB) const {
21720   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21721   DebugLoc DL = MI->getDebugLoc();
21722
21723   // To "insert" a SELECT_CC instruction, we actually have to insert the
21724   // diamond control-flow pattern.  The incoming instruction knows the
21725   // destination vreg to set, the condition code register to branch on, the
21726   // true/false values to select between, and a branch opcode to use.
21727   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21728   MachineFunction::iterator It = ++BB->getIterator();
21729
21730   //  thisMBB:
21731   //  ...
21732   //   TrueVal = ...
21733   //   cmpTY ccX, r1, r2
21734   //   bCC copy1MBB
21735   //   fallthrough --> copy0MBB
21736   MachineBasicBlock *thisMBB = BB;
21737   MachineFunction *F = BB->getParent();
21738
21739   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21740   // as described above, by inserting a BB, and then making a PHI at the join
21741   // point to select the true and false operands of the CMOV in the PHI.
21742   //
21743   // The code also handles two different cases of multiple CMOV opcodes
21744   // in a row.
21745   //
21746   // Case 1:
21747   // In this case, there are multiple CMOVs in a row, all which are based on
21748   // the same condition setting (or the exact opposite condition setting).
21749   // In this case we can lower all the CMOVs using a single inserted BB, and
21750   // then make a number of PHIs at the join point to model the CMOVs. The only
21751   // trickiness here, is that in a case like:
21752   //
21753   // t2 = CMOV cond1 t1, f1
21754   // t3 = CMOV cond1 t2, f2
21755   //
21756   // when rewriting this into PHIs, we have to perform some renaming on the
21757   // temps since you cannot have a PHI operand refer to a PHI result earlier
21758   // in the same block.  The "simple" but wrong lowering would be:
21759   //
21760   // t2 = PHI t1(BB1), f1(BB2)
21761   // t3 = PHI t2(BB1), f2(BB2)
21762   //
21763   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21764   // renaming is to note that on the path through BB1, t2 is really just a
21765   // copy of t1, and do that renaming, properly generating:
21766   //
21767   // t2 = PHI t1(BB1), f1(BB2)
21768   // t3 = PHI t1(BB1), f2(BB2)
21769   //
21770   // Case 2, we lower cascaded CMOVs such as
21771   //
21772   //   (CMOV (CMOV F, T, cc1), T, cc2)
21773   //
21774   // to two successives branches.  For that, we look for another CMOV as the
21775   // following instruction.
21776   //
21777   // Without this, we would add a PHI between the two jumps, which ends up
21778   // creating a few copies all around. For instance, for
21779   //
21780   //    (sitofp (zext (fcmp une)))
21781   //
21782   // we would generate:
21783   //
21784   //         ucomiss %xmm1, %xmm0
21785   //         movss  <1.0f>, %xmm0
21786   //         movaps  %xmm0, %xmm1
21787   //         jne     .LBB5_2
21788   //         xorps   %xmm1, %xmm1
21789   // .LBB5_2:
21790   //         jp      .LBB5_4
21791   //         movaps  %xmm1, %xmm0
21792   // .LBB5_4:
21793   //         retq
21794   //
21795   // because this custom-inserter would have generated:
21796   //
21797   //   A
21798   //   | \
21799   //   |  B
21800   //   | /
21801   //   C
21802   //   | \
21803   //   |  D
21804   //   | /
21805   //   E
21806   //
21807   // A: X = ...; Y = ...
21808   // B: empty
21809   // C: Z = PHI [X, A], [Y, B]
21810   // D: empty
21811   // E: PHI [X, C], [Z, D]
21812   //
21813   // If we lower both CMOVs in a single step, we can instead generate:
21814   //
21815   //   A
21816   //   | \
21817   //   |  C
21818   //   | /|
21819   //   |/ |
21820   //   |  |
21821   //   |  D
21822   //   | /
21823   //   E
21824   //
21825   // A: X = ...; Y = ...
21826   // D: empty
21827   // E: PHI [X, A], [X, C], [Y, D]
21828   //
21829   // Which, in our sitofp/fcmp example, gives us something like:
21830   //
21831   //         ucomiss %xmm1, %xmm0
21832   //         movss  <1.0f>, %xmm0
21833   //         jne     .LBB5_4
21834   //         jp      .LBB5_4
21835   //         xorps   %xmm0, %xmm0
21836   // .LBB5_4:
21837   //         retq
21838   //
21839   MachineInstr *CascadedCMOV = nullptr;
21840   MachineInstr *LastCMOV = MI;
21841   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21842   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21843   MachineBasicBlock::iterator NextMIIt =
21844       std::next(MachineBasicBlock::iterator(MI));
21845
21846   // Check for case 1, where there are multiple CMOVs with the same condition
21847   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21848   // number of jumps the most.
21849
21850   if (isCMOVPseudo(MI)) {
21851     // See if we have a string of CMOVS with the same condition.
21852     while (NextMIIt != BB->end() &&
21853            isCMOVPseudo(NextMIIt) &&
21854            (NextMIIt->getOperand(3).getImm() == CC ||
21855             NextMIIt->getOperand(3).getImm() == OppCC)) {
21856       LastCMOV = &*NextMIIt;
21857       ++NextMIIt;
21858     }
21859   }
21860
21861   // This checks for case 2, but only do this if we didn't already find
21862   // case 1, as indicated by LastCMOV == MI.
21863   if (LastCMOV == MI &&
21864       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21865       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21866       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg() &&
21867       NextMIIt->getOperand(1).isKill()) {
21868     CascadedCMOV = &*NextMIIt;
21869   }
21870
21871   MachineBasicBlock *jcc1MBB = nullptr;
21872
21873   // If we have a cascaded CMOV, we lower it to two successive branches to
21874   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21875   if (CascadedCMOV) {
21876     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21877     F->insert(It, jcc1MBB);
21878     jcc1MBB->addLiveIn(X86::EFLAGS);
21879   }
21880
21881   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21882   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21883   F->insert(It, copy0MBB);
21884   F->insert(It, sinkMBB);
21885
21886   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21887   // live into the sink and copy blocks.
21888   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21889
21890   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21891   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21892       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21893     copy0MBB->addLiveIn(X86::EFLAGS);
21894     sinkMBB->addLiveIn(X86::EFLAGS);
21895   }
21896
21897   // Transfer the remainder of BB and its successor edges to sinkMBB.
21898   sinkMBB->splice(sinkMBB->begin(), BB,
21899                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21900   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21901
21902   // Add the true and fallthrough blocks as its successors.
21903   if (CascadedCMOV) {
21904     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21905     BB->addSuccessor(jcc1MBB);
21906
21907     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21908     // jump to the sinkMBB.
21909     jcc1MBB->addSuccessor(copy0MBB);
21910     jcc1MBB->addSuccessor(sinkMBB);
21911   } else {
21912     BB->addSuccessor(copy0MBB);
21913   }
21914
21915   // The true block target of the first (or only) branch is always sinkMBB.
21916   BB->addSuccessor(sinkMBB);
21917
21918   // Create the conditional branch instruction.
21919   unsigned Opc = X86::GetCondBranchFromCond(CC);
21920   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21921
21922   if (CascadedCMOV) {
21923     unsigned Opc2 = X86::GetCondBranchFromCond(
21924         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21925     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21926   }
21927
21928   //  copy0MBB:
21929   //   %FalseValue = ...
21930   //   # fallthrough to sinkMBB
21931   copy0MBB->addSuccessor(sinkMBB);
21932
21933   //  sinkMBB:
21934   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21935   //  ...
21936   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21937   MachineBasicBlock::iterator MIItEnd =
21938     std::next(MachineBasicBlock::iterator(LastCMOV));
21939   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21940   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21941   MachineInstrBuilder MIB;
21942
21943   // As we are creating the PHIs, we have to be careful if there is more than
21944   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21945   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21946   // That also means that PHI construction must work forward from earlier to
21947   // later, and that the code must maintain a mapping from earlier PHI's
21948   // destination registers, and the registers that went into the PHI.
21949
21950   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21951     unsigned DestReg = MIIt->getOperand(0).getReg();
21952     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21953     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21954
21955     // If this CMOV we are generating is the opposite condition from
21956     // the jump we generated, then we have to swap the operands for the
21957     // PHI that is going to be generated.
21958     if (MIIt->getOperand(3).getImm() == OppCC)
21959         std::swap(Op1Reg, Op2Reg);
21960
21961     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21962       Op1Reg = RegRewriteTable[Op1Reg].first;
21963
21964     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21965       Op2Reg = RegRewriteTable[Op2Reg].second;
21966
21967     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21968                   TII->get(X86::PHI), DestReg)
21969           .addReg(Op1Reg).addMBB(copy0MBB)
21970           .addReg(Op2Reg).addMBB(thisMBB);
21971
21972     // Add this PHI to the rewrite table.
21973     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21974   }
21975
21976   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21977   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21978   if (CascadedCMOV) {
21979     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21980     // Copy the PHI result to the register defined by the second CMOV.
21981     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21982             DL, TII->get(TargetOpcode::COPY),
21983             CascadedCMOV->getOperand(0).getReg())
21984         .addReg(MI->getOperand(0).getReg());
21985     CascadedCMOV->eraseFromParent();
21986   }
21987
21988   // Now remove the CMOV(s).
21989   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21990     (MIIt++)->eraseFromParent();
21991
21992   return sinkMBB;
21993 }
21994
21995 MachineBasicBlock *
21996 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21997                                        MachineBasicBlock *BB) const {
21998   // Combine the following atomic floating-point modification pattern:
21999   //   a.store(reg OP a.load(acquire), release)
22000   // Transform them into:
22001   //   OPss (%gpr), %xmm
22002   //   movss %xmm, (%gpr)
22003   // Or sd equivalent for 64-bit operations.
22004   unsigned MOp, FOp;
22005   switch (MI->getOpcode()) {
22006   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
22007   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
22008   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
22009   }
22010   const X86InstrInfo *TII = Subtarget->getInstrInfo();
22011   DebugLoc DL = MI->getDebugLoc();
22012   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
22013   MachineOperand MSrc = MI->getOperand(0);
22014   unsigned VSrc = MI->getOperand(5).getReg();
22015   const MachineOperand &Disp = MI->getOperand(3);
22016   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
22017   bool hasDisp = Disp.isGlobal() || Disp.isImm();
22018   if (hasDisp && MSrc.isReg())
22019     MSrc.setIsKill(false);
22020   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
22021                                 .addOperand(/*Base=*/MSrc)
22022                                 .addImm(/*Scale=*/1)
22023                                 .addReg(/*Index=*/0)
22024                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
22025                                 .addReg(0);
22026   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
22027                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
22028                           .addReg(VSrc)
22029                           .addOperand(/*Base=*/MSrc)
22030                           .addImm(/*Scale=*/1)
22031                           .addReg(/*Index=*/0)
22032                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
22033                           .addReg(/*Segment=*/0);
22034   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
22035   MI->eraseFromParent(); // The pseudo instruction is gone now.
22036   return BB;
22037 }
22038
22039 MachineBasicBlock *
22040 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
22041                                         MachineBasicBlock *BB) const {
22042   MachineFunction *MF = BB->getParent();
22043   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22044   DebugLoc DL = MI->getDebugLoc();
22045   const BasicBlock *LLVM_BB = BB->getBasicBlock();
22046
22047   assert(MF->shouldSplitStack());
22048
22049   const bool Is64Bit = Subtarget->is64Bit();
22050   const bool IsLP64 = Subtarget->isTarget64BitLP64();
22051
22052   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
22053   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
22054
22055   // BB:
22056   //  ... [Till the alloca]
22057   // If stacklet is not large enough, jump to mallocMBB
22058   //
22059   // bumpMBB:
22060   //  Allocate by subtracting from RSP
22061   //  Jump to continueMBB
22062   //
22063   // mallocMBB:
22064   //  Allocate by call to runtime
22065   //
22066   // continueMBB:
22067   //  ...
22068   //  [rest of original BB]
22069   //
22070
22071   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22072   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22073   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22074
22075   MachineRegisterInfo &MRI = MF->getRegInfo();
22076   const TargetRegisterClass *AddrRegClass =
22077       getRegClassFor(getPointerTy(MF->getDataLayout()));
22078
22079   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22080     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22081     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
22082     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
22083     sizeVReg = MI->getOperand(1).getReg(),
22084     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
22085
22086   MachineFunction::iterator MBBIter = ++BB->getIterator();
22087
22088   MF->insert(MBBIter, bumpMBB);
22089   MF->insert(MBBIter, mallocMBB);
22090   MF->insert(MBBIter, continueMBB);
22091
22092   continueMBB->splice(continueMBB->begin(), BB,
22093                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
22094   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
22095
22096   // Add code to the main basic block to check if the stack limit has been hit,
22097   // and if so, jump to mallocMBB otherwise to bumpMBB.
22098   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
22099   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
22100     .addReg(tmpSPVReg).addReg(sizeVReg);
22101   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
22102     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
22103     .addReg(SPLimitVReg);
22104   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
22105
22106   // bumpMBB simply decreases the stack pointer, since we know the current
22107   // stacklet has enough space.
22108   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
22109     .addReg(SPLimitVReg);
22110   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
22111     .addReg(SPLimitVReg);
22112   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22113
22114   // Calls into a routine in libgcc to allocate more space from the heap.
22115   const uint32_t *RegMask =
22116       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
22117   if (IsLP64) {
22118     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
22119       .addReg(sizeVReg);
22120     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22121       .addExternalSymbol("__morestack_allocate_stack_space")
22122       .addRegMask(RegMask)
22123       .addReg(X86::RDI, RegState::Implicit)
22124       .addReg(X86::RAX, RegState::ImplicitDefine);
22125   } else if (Is64Bit) {
22126     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
22127       .addReg(sizeVReg);
22128     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22129       .addExternalSymbol("__morestack_allocate_stack_space")
22130       .addRegMask(RegMask)
22131       .addReg(X86::EDI, RegState::Implicit)
22132       .addReg(X86::EAX, RegState::ImplicitDefine);
22133   } else {
22134     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
22135       .addImm(12);
22136     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
22137     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
22138       .addExternalSymbol("__morestack_allocate_stack_space")
22139       .addRegMask(RegMask)
22140       .addReg(X86::EAX, RegState::ImplicitDefine);
22141   }
22142
22143   if (!Is64Bit)
22144     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
22145       .addImm(16);
22146
22147   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
22148     .addReg(IsLP64 ? X86::RAX : X86::EAX);
22149   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22150
22151   // Set up the CFG correctly.
22152   BB->addSuccessor(bumpMBB);
22153   BB->addSuccessor(mallocMBB);
22154   mallocMBB->addSuccessor(continueMBB);
22155   bumpMBB->addSuccessor(continueMBB);
22156
22157   // Take care of the PHI nodes.
22158   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
22159           MI->getOperand(0).getReg())
22160     .addReg(mallocPtrVReg).addMBB(mallocMBB)
22161     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
22162
22163   // Delete the original pseudo instruction.
22164   MI->eraseFromParent();
22165
22166   // And we're done.
22167   return continueMBB;
22168 }
22169
22170 MachineBasicBlock *
22171 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
22172                                         MachineBasicBlock *BB) const {
22173   assert(!Subtarget->isTargetMachO());
22174   DebugLoc DL = MI->getDebugLoc();
22175   MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
22176       *BB->getParent(), *BB, MI, DL, false);
22177   MachineBasicBlock *ResumeBB = ResumeMI->getParent();
22178   MI->eraseFromParent(); // The pseudo instruction is gone now.
22179   return ResumeBB;
22180 }
22181
22182 MachineBasicBlock *
22183 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
22184                                        MachineBasicBlock *BB) const {
22185   MachineFunction *MF = BB->getParent();
22186   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22187   MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
22188   DebugLoc DL = MI->getDebugLoc();
22189
22190   assert(!isAsynchronousEHPersonality(
22191              classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
22192          "SEH does not use catchret!");
22193
22194   // Only 32-bit EH needs to worry about manually restoring stack pointers.
22195   if (!Subtarget->is32Bit())
22196     return BB;
22197
22198   // C++ EH creates a new target block to hold the restore code, and wires up
22199   // the new block to the return destination with a normal JMP_4.
22200   MachineBasicBlock *RestoreMBB =
22201       MF->CreateMachineBasicBlock(BB->getBasicBlock());
22202   assert(BB->succ_size() == 1);
22203   MF->insert(std::next(BB->getIterator()), RestoreMBB);
22204   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
22205   BB->addSuccessor(RestoreMBB);
22206   MI->getOperand(0).setMBB(RestoreMBB);
22207
22208   auto RestoreMBBI = RestoreMBB->begin();
22209   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
22210   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
22211   return BB;
22212 }
22213
22214 MachineBasicBlock *
22215 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
22216                                        MachineBasicBlock *BB) const {
22217   MachineFunction *MF = BB->getParent();
22218   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
22219   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
22220   // Only 32-bit SEH requires special handling for catchpad.
22221   if (IsSEH && Subtarget->is32Bit()) {
22222     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22223     DebugLoc DL = MI->getDebugLoc();
22224     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
22225   }
22226   MI->eraseFromParent();
22227   return BB;
22228 }
22229
22230 MachineBasicBlock *
22231 X86TargetLowering::EmitLoweredTLSAddr(MachineInstr *MI,
22232                                       MachineBasicBlock *BB) const {
22233   // So, here we replace TLSADDR with the sequence:
22234   // adjust_stackdown -> TLSADDR -> adjust_stackup.
22235   // We need this because TLSADDR is lowered into calls
22236   // inside MC, therefore without the two markers shrink-wrapping
22237   // may push the prologue/epilogue pass them.
22238   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22239   DebugLoc DL = MI->getDebugLoc();
22240   MachineFunction &MF = *BB->getParent();
22241
22242   // Emit CALLSEQ_START right before the instruction.
22243   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
22244   MachineInstrBuilder CallseqStart =
22245     BuildMI(MF, DL, TII.get(AdjStackDown)).addImm(0);
22246   BB->insert(MachineBasicBlock::iterator(MI), CallseqStart);
22247
22248   // Emit CALLSEQ_END right after the instruction.
22249   // We don't call erase from parent because we want to keep the
22250   // original instruction around.
22251   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
22252   MachineInstrBuilder CallseqEnd =
22253     BuildMI(MF, DL, TII.get(AdjStackUp)).addImm(0).addImm(0);
22254   BB->insertAfter(MachineBasicBlock::iterator(MI), CallseqEnd);
22255
22256   return BB;
22257 }
22258
22259 MachineBasicBlock *
22260 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
22261                                       MachineBasicBlock *BB) const {
22262   // This is pretty easy.  We're taking the value that we received from
22263   // our load from the relocation, sticking it in either RDI (x86-64)
22264   // or EAX and doing an indirect call.  The return value will then
22265   // be in the normal return register.
22266   MachineFunction *F = BB->getParent();
22267   const X86InstrInfo *TII = Subtarget->getInstrInfo();
22268   DebugLoc DL = MI->getDebugLoc();
22269
22270   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
22271   assert(MI->getOperand(3).isGlobal() && "This should be a global");
22272
22273   // Get a register mask for the lowered call.
22274   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
22275   // proper register mask.
22276   const uint32_t *RegMask =
22277       Subtarget->is64Bit() ?
22278       Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
22279       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
22280   if (Subtarget->is64Bit()) {
22281     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22282                                       TII->get(X86::MOV64rm), X86::RDI)
22283     .addReg(X86::RIP)
22284     .addImm(0).addReg(0)
22285     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22286                       MI->getOperand(3).getTargetFlags())
22287     .addReg(0);
22288     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
22289     addDirectMem(MIB, X86::RDI);
22290     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
22291   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
22292     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22293                                       TII->get(X86::MOV32rm), X86::EAX)
22294     .addReg(0)
22295     .addImm(0).addReg(0)
22296     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22297                       MI->getOperand(3).getTargetFlags())
22298     .addReg(0);
22299     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22300     addDirectMem(MIB, X86::EAX);
22301     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22302   } else {
22303     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22304                                       TII->get(X86::MOV32rm), X86::EAX)
22305     .addReg(TII->getGlobalBaseReg(F))
22306     .addImm(0).addReg(0)
22307     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22308                       MI->getOperand(3).getTargetFlags())
22309     .addReg(0);
22310     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22311     addDirectMem(MIB, X86::EAX);
22312     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22313   }
22314
22315   MI->eraseFromParent(); // The pseudo instruction is gone now.
22316   return BB;
22317 }
22318
22319 MachineBasicBlock *
22320 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
22321                                     MachineBasicBlock *MBB) const {
22322   DebugLoc DL = MI->getDebugLoc();
22323   MachineFunction *MF = MBB->getParent();
22324   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22325   MachineRegisterInfo &MRI = MF->getRegInfo();
22326
22327   const BasicBlock *BB = MBB->getBasicBlock();
22328   MachineFunction::iterator I = ++MBB->getIterator();
22329
22330   // Memory Reference
22331   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22332   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22333
22334   unsigned DstReg;
22335   unsigned MemOpndSlot = 0;
22336
22337   unsigned CurOp = 0;
22338
22339   DstReg = MI->getOperand(CurOp++).getReg();
22340   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
22341   assert(RC->hasType(MVT::i32) && "Invalid destination!");
22342   unsigned mainDstReg = MRI.createVirtualRegister(RC);
22343   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
22344
22345   MemOpndSlot = CurOp;
22346
22347   MVT PVT = getPointerTy(MF->getDataLayout());
22348   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22349          "Invalid Pointer Size!");
22350
22351   // For v = setjmp(buf), we generate
22352   //
22353   // thisMBB:
22354   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
22355   //  SjLjSetup restoreMBB
22356   //
22357   // mainMBB:
22358   //  v_main = 0
22359   //
22360   // sinkMBB:
22361   //  v = phi(main, restore)
22362   //
22363   // restoreMBB:
22364   //  if base pointer being used, load it from frame
22365   //  v_restore = 1
22366
22367   MachineBasicBlock *thisMBB = MBB;
22368   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22369   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22370   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
22371   MF->insert(I, mainMBB);
22372   MF->insert(I, sinkMBB);
22373   MF->push_back(restoreMBB);
22374   restoreMBB->setHasAddressTaken();
22375
22376   MachineInstrBuilder MIB;
22377
22378   // Transfer the remainder of BB and its successor edges to sinkMBB.
22379   sinkMBB->splice(sinkMBB->begin(), MBB,
22380                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22381   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22382
22383   // thisMBB:
22384   unsigned PtrStoreOpc = 0;
22385   unsigned LabelReg = 0;
22386   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22387   Reloc::Model RM = MF->getTarget().getRelocationModel();
22388   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
22389                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
22390
22391   // Prepare IP either in reg or imm.
22392   if (!UseImmLabel) {
22393     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
22394     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
22395     LabelReg = MRI.createVirtualRegister(PtrRC);
22396     if (Subtarget->is64Bit()) {
22397       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
22398               .addReg(X86::RIP)
22399               .addImm(0)
22400               .addReg(0)
22401               .addMBB(restoreMBB)
22402               .addReg(0);
22403     } else {
22404       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
22405       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
22406               .addReg(XII->getGlobalBaseReg(MF))
22407               .addImm(0)
22408               .addReg(0)
22409               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
22410               .addReg(0);
22411     }
22412   } else
22413     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
22414   // Store IP
22415   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
22416   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22417     if (i == X86::AddrDisp)
22418       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
22419     else
22420       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
22421   }
22422   if (!UseImmLabel)
22423     MIB.addReg(LabelReg);
22424   else
22425     MIB.addMBB(restoreMBB);
22426   MIB.setMemRefs(MMOBegin, MMOEnd);
22427   // Setup
22428   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
22429           .addMBB(restoreMBB);
22430
22431   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22432   MIB.addRegMask(RegInfo->getNoPreservedMask());
22433   thisMBB->addSuccessor(mainMBB);
22434   thisMBB->addSuccessor(restoreMBB);
22435
22436   // mainMBB:
22437   //  EAX = 0
22438   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
22439   mainMBB->addSuccessor(sinkMBB);
22440
22441   // sinkMBB:
22442   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
22443           TII->get(X86::PHI), DstReg)
22444     .addReg(mainDstReg).addMBB(mainMBB)
22445     .addReg(restoreDstReg).addMBB(restoreMBB);
22446
22447   // restoreMBB:
22448   if (RegInfo->hasBasePointer(*MF)) {
22449     const bool Uses64BitFramePtr =
22450         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
22451     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
22452     X86FI->setRestoreBasePointer(MF);
22453     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
22454     unsigned BasePtr = RegInfo->getBaseRegister();
22455     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
22456     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
22457                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
22458       .setMIFlag(MachineInstr::FrameSetup);
22459   }
22460   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
22461   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
22462   restoreMBB->addSuccessor(sinkMBB);
22463
22464   MI->eraseFromParent();
22465   return sinkMBB;
22466 }
22467
22468 MachineBasicBlock *
22469 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22470                                      MachineBasicBlock *MBB) const {
22471   DebugLoc DL = MI->getDebugLoc();
22472   MachineFunction *MF = MBB->getParent();
22473   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22474   MachineRegisterInfo &MRI = MF->getRegInfo();
22475
22476   // Memory Reference
22477   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22478   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22479
22480   MVT PVT = getPointerTy(MF->getDataLayout());
22481   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22482          "Invalid Pointer Size!");
22483
22484   const TargetRegisterClass *RC =
22485     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22486   unsigned Tmp = MRI.createVirtualRegister(RC);
22487   // Since FP is only updated here but NOT referenced, it's treated as GPR.
22488   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22489   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22490   unsigned SP = RegInfo->getStackRegister();
22491
22492   MachineInstrBuilder MIB;
22493
22494   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22495   const int64_t SPOffset = 2 * PVT.getStoreSize();
22496
22497   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22498   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22499
22500   // Reload FP
22501   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22502   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22503     MIB.addOperand(MI->getOperand(i));
22504   MIB.setMemRefs(MMOBegin, MMOEnd);
22505   // Reload IP
22506   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22507   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22508     if (i == X86::AddrDisp)
22509       MIB.addDisp(MI->getOperand(i), LabelOffset);
22510     else
22511       MIB.addOperand(MI->getOperand(i));
22512   }
22513   MIB.setMemRefs(MMOBegin, MMOEnd);
22514   // Reload SP
22515   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22516   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22517     if (i == X86::AddrDisp)
22518       MIB.addDisp(MI->getOperand(i), SPOffset);
22519     else
22520       MIB.addOperand(MI->getOperand(i));
22521   }
22522   MIB.setMemRefs(MMOBegin, MMOEnd);
22523   // Jump
22524   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22525
22526   MI->eraseFromParent();
22527   return MBB;
22528 }
22529
22530 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22531 // accumulator loops. Writing back to the accumulator allows the coalescer
22532 // to remove extra copies in the loop.
22533 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
22534 MachineBasicBlock *
22535 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22536                                  MachineBasicBlock *MBB) const {
22537   MachineOperand &AddendOp = MI->getOperand(3);
22538
22539   // Bail out early if the addend isn't a register - we can't switch these.
22540   if (!AddendOp.isReg())
22541     return MBB;
22542
22543   MachineFunction &MF = *MBB->getParent();
22544   MachineRegisterInfo &MRI = MF.getRegInfo();
22545
22546   // Check whether the addend is defined by a PHI:
22547   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22548   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22549   if (!AddendDef.isPHI())
22550     return MBB;
22551
22552   // Look for the following pattern:
22553   // loop:
22554   //   %addend = phi [%entry, 0], [%loop, %result]
22555   //   ...
22556   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22557
22558   // Replace with:
22559   //   loop:
22560   //   %addend = phi [%entry, 0], [%loop, %result]
22561   //   ...
22562   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22563
22564   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22565     assert(AddendDef.getOperand(i).isReg());
22566     MachineOperand PHISrcOp = AddendDef.getOperand(i);
22567     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22568     if (&PHISrcInst == MI) {
22569       // Found a matching instruction.
22570       unsigned NewFMAOpc = 0;
22571       switch (MI->getOpcode()) {
22572         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22573         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22574         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22575         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22576         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22577         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22578         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22579         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22580         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22581         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22582         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22583         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22584         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22585         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22586         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22587         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22588         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22589         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22590         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22591         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22592
22593         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22594         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22595         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22596         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22597         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22598         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22599         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22600         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22601         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22602         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22603         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22604         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22605         default: llvm_unreachable("Unrecognized FMA variant.");
22606       }
22607
22608       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22609       MachineInstrBuilder MIB =
22610         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22611         .addOperand(MI->getOperand(0))
22612         .addOperand(MI->getOperand(3))
22613         .addOperand(MI->getOperand(2))
22614         .addOperand(MI->getOperand(1));
22615       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22616       MI->eraseFromParent();
22617     }
22618   }
22619
22620   return MBB;
22621 }
22622
22623 MachineBasicBlock *
22624 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22625                                                MachineBasicBlock *BB) const {
22626   switch (MI->getOpcode()) {
22627   default: llvm_unreachable("Unexpected instr type to insert");
22628   case X86::TAILJMPd64:
22629   case X86::TAILJMPr64:
22630   case X86::TAILJMPm64:
22631   case X86::TAILJMPd64_REX:
22632   case X86::TAILJMPr64_REX:
22633   case X86::TAILJMPm64_REX:
22634     llvm_unreachable("TAILJMP64 would not be touched here.");
22635   case X86::TCRETURNdi64:
22636   case X86::TCRETURNri64:
22637   case X86::TCRETURNmi64:
22638     return BB;
22639   case X86::TLS_addr32:
22640   case X86::TLS_addr64:
22641   case X86::TLS_base_addr32:
22642   case X86::TLS_base_addr64:
22643     return EmitLoweredTLSAddr(MI, BB);
22644   case X86::WIN_ALLOCA:
22645     return EmitLoweredWinAlloca(MI, BB);
22646   case X86::CATCHRET:
22647     return EmitLoweredCatchRet(MI, BB);
22648   case X86::CATCHPAD:
22649     return EmitLoweredCatchPad(MI, BB);
22650   case X86::SEG_ALLOCA_32:
22651   case X86::SEG_ALLOCA_64:
22652     return EmitLoweredSegAlloca(MI, BB);
22653   case X86::TLSCall_32:
22654   case X86::TLSCall_64:
22655     return EmitLoweredTLSCall(MI, BB);
22656   case X86::CMOV_FR32:
22657   case X86::CMOV_FR64:
22658   case X86::CMOV_FR128:
22659   case X86::CMOV_GR8:
22660   case X86::CMOV_GR16:
22661   case X86::CMOV_GR32:
22662   case X86::CMOV_RFP32:
22663   case X86::CMOV_RFP64:
22664   case X86::CMOV_RFP80:
22665   case X86::CMOV_V2F64:
22666   case X86::CMOV_V2I64:
22667   case X86::CMOV_V4F32:
22668   case X86::CMOV_V4F64:
22669   case X86::CMOV_V4I64:
22670   case X86::CMOV_V16F32:
22671   case X86::CMOV_V8F32:
22672   case X86::CMOV_V8F64:
22673   case X86::CMOV_V8I64:
22674   case X86::CMOV_V8I1:
22675   case X86::CMOV_V16I1:
22676   case X86::CMOV_V32I1:
22677   case X86::CMOV_V64I1:
22678     return EmitLoweredSelect(MI, BB);
22679
22680   case X86::RDFLAGS32:
22681   case X86::RDFLAGS64: {
22682     DebugLoc DL = MI->getDebugLoc();
22683     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22684     unsigned PushF =
22685         MI->getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
22686     unsigned Pop =
22687         MI->getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
22688     BuildMI(*BB, MI, DL, TII->get(PushF));
22689     BuildMI(*BB, MI, DL, TII->get(Pop), MI->getOperand(0).getReg());
22690
22691     MI->eraseFromParent(); // The pseudo is gone now.
22692     return BB;
22693   }
22694
22695   case X86::WRFLAGS32:
22696   case X86::WRFLAGS64: {
22697     DebugLoc DL = MI->getDebugLoc();
22698     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22699     unsigned Push =
22700         MI->getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
22701     unsigned PopF =
22702         MI->getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
22703     BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI->getOperand(0).getReg());
22704     BuildMI(*BB, MI, DL, TII->get(PopF));
22705
22706     MI->eraseFromParent(); // The pseudo is gone now.
22707     return BB;
22708   }
22709
22710   case X86::RELEASE_FADD32mr:
22711   case X86::RELEASE_FADD64mr:
22712     return EmitLoweredAtomicFP(MI, BB);
22713
22714   case X86::FP32_TO_INT16_IN_MEM:
22715   case X86::FP32_TO_INT32_IN_MEM:
22716   case X86::FP32_TO_INT64_IN_MEM:
22717   case X86::FP64_TO_INT16_IN_MEM:
22718   case X86::FP64_TO_INT32_IN_MEM:
22719   case X86::FP64_TO_INT64_IN_MEM:
22720   case X86::FP80_TO_INT16_IN_MEM:
22721   case X86::FP80_TO_INT32_IN_MEM:
22722   case X86::FP80_TO_INT64_IN_MEM: {
22723     MachineFunction *F = BB->getParent();
22724     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22725     DebugLoc DL = MI->getDebugLoc();
22726
22727     // Change the floating point control register to use "round towards zero"
22728     // mode when truncating to an integer value.
22729     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22730     addFrameReference(BuildMI(*BB, MI, DL,
22731                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
22732
22733     // Load the old value of the high byte of the control word...
22734     unsigned OldCW =
22735       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22736     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22737                       CWFrameIdx);
22738
22739     // Set the high part to be round to zero...
22740     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22741       .addImm(0xC7F);
22742
22743     // Reload the modified control word now...
22744     addFrameReference(BuildMI(*BB, MI, DL,
22745                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22746
22747     // Restore the memory image of control word to original value
22748     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22749       .addReg(OldCW);
22750
22751     // Get the X86 opcode to use.
22752     unsigned Opc;
22753     switch (MI->getOpcode()) {
22754     default: llvm_unreachable("illegal opcode!");
22755     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22756     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22757     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22758     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22759     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22760     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22761     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22762     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22763     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22764     }
22765
22766     X86AddressMode AM;
22767     MachineOperand &Op = MI->getOperand(0);
22768     if (Op.isReg()) {
22769       AM.BaseType = X86AddressMode::RegBase;
22770       AM.Base.Reg = Op.getReg();
22771     } else {
22772       AM.BaseType = X86AddressMode::FrameIndexBase;
22773       AM.Base.FrameIndex = Op.getIndex();
22774     }
22775     Op = MI->getOperand(1);
22776     if (Op.isImm())
22777       AM.Scale = Op.getImm();
22778     Op = MI->getOperand(2);
22779     if (Op.isImm())
22780       AM.IndexReg = Op.getImm();
22781     Op = MI->getOperand(3);
22782     if (Op.isGlobal()) {
22783       AM.GV = Op.getGlobal();
22784     } else {
22785       AM.Disp = Op.getImm();
22786     }
22787     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22788                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22789
22790     // Reload the original control word now.
22791     addFrameReference(BuildMI(*BB, MI, DL,
22792                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22793
22794     MI->eraseFromParent();   // The pseudo instruction is gone now.
22795     return BB;
22796   }
22797     // String/text processing lowering.
22798   case X86::PCMPISTRM128REG:
22799   case X86::VPCMPISTRM128REG:
22800   case X86::PCMPISTRM128MEM:
22801   case X86::VPCMPISTRM128MEM:
22802   case X86::PCMPESTRM128REG:
22803   case X86::VPCMPESTRM128REG:
22804   case X86::PCMPESTRM128MEM:
22805   case X86::VPCMPESTRM128MEM:
22806     assert(Subtarget->hasSSE42() &&
22807            "Target must have SSE4.2 or AVX features enabled");
22808     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22809
22810   // String/text processing lowering.
22811   case X86::PCMPISTRIREG:
22812   case X86::VPCMPISTRIREG:
22813   case X86::PCMPISTRIMEM:
22814   case X86::VPCMPISTRIMEM:
22815   case X86::PCMPESTRIREG:
22816   case X86::VPCMPESTRIREG:
22817   case X86::PCMPESTRIMEM:
22818   case X86::VPCMPESTRIMEM:
22819     assert(Subtarget->hasSSE42() &&
22820            "Target must have SSE4.2 or AVX features enabled");
22821     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22822
22823   // Thread synchronization.
22824   case X86::MONITOR:
22825     return EmitMonitor(MI, BB, Subtarget);
22826   // PKU feature
22827   case X86::WRPKRU:
22828     return EmitWRPKRU(MI, BB, Subtarget);
22829   case X86::RDPKRU:
22830     return EmitRDPKRU(MI, BB, Subtarget);
22831   // xbegin
22832   case X86::XBEGIN:
22833     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22834
22835   case X86::VASTART_SAVE_XMM_REGS:
22836     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22837
22838   case X86::VAARG_64:
22839     return EmitVAARG64WithCustomInserter(MI, BB);
22840
22841   case X86::EH_SjLj_SetJmp32:
22842   case X86::EH_SjLj_SetJmp64:
22843     return emitEHSjLjSetJmp(MI, BB);
22844
22845   case X86::EH_SjLj_LongJmp32:
22846   case X86::EH_SjLj_LongJmp64:
22847     return emitEHSjLjLongJmp(MI, BB);
22848
22849   case TargetOpcode::STATEPOINT:
22850     // As an implementation detail, STATEPOINT shares the STACKMAP format at
22851     // this point in the process.  We diverge later.
22852     return emitPatchPoint(MI, BB);
22853
22854   case TargetOpcode::STACKMAP:
22855   case TargetOpcode::PATCHPOINT:
22856     return emitPatchPoint(MI, BB);
22857
22858   case X86::VFMADDPDr213r:
22859   case X86::VFMADDPSr213r:
22860   case X86::VFMADDSDr213r:
22861   case X86::VFMADDSSr213r:
22862   case X86::VFMSUBPDr213r:
22863   case X86::VFMSUBPSr213r:
22864   case X86::VFMSUBSDr213r:
22865   case X86::VFMSUBSSr213r:
22866   case X86::VFNMADDPDr213r:
22867   case X86::VFNMADDPSr213r:
22868   case X86::VFNMADDSDr213r:
22869   case X86::VFNMADDSSr213r:
22870   case X86::VFNMSUBPDr213r:
22871   case X86::VFNMSUBPSr213r:
22872   case X86::VFNMSUBSDr213r:
22873   case X86::VFNMSUBSSr213r:
22874   case X86::VFMADDSUBPDr213r:
22875   case X86::VFMADDSUBPSr213r:
22876   case X86::VFMSUBADDPDr213r:
22877   case X86::VFMSUBADDPSr213r:
22878   case X86::VFMADDPDr213rY:
22879   case X86::VFMADDPSr213rY:
22880   case X86::VFMSUBPDr213rY:
22881   case X86::VFMSUBPSr213rY:
22882   case X86::VFNMADDPDr213rY:
22883   case X86::VFNMADDPSr213rY:
22884   case X86::VFNMSUBPDr213rY:
22885   case X86::VFNMSUBPSr213rY:
22886   case X86::VFMADDSUBPDr213rY:
22887   case X86::VFMADDSUBPSr213rY:
22888   case X86::VFMSUBADDPDr213rY:
22889   case X86::VFMSUBADDPSr213rY:
22890     return emitFMA3Instr(MI, BB);
22891   }
22892 }
22893
22894 //===----------------------------------------------------------------------===//
22895 //                           X86 Optimization Hooks
22896 //===----------------------------------------------------------------------===//
22897
22898 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22899                                                       APInt &KnownZero,
22900                                                       APInt &KnownOne,
22901                                                       const SelectionDAG &DAG,
22902                                                       unsigned Depth) const {
22903   unsigned BitWidth = KnownZero.getBitWidth();
22904   unsigned Opc = Op.getOpcode();
22905   assert((Opc >= ISD::BUILTIN_OP_END ||
22906           Opc == ISD::INTRINSIC_WO_CHAIN ||
22907           Opc == ISD::INTRINSIC_W_CHAIN ||
22908           Opc == ISD::INTRINSIC_VOID) &&
22909          "Should use MaskedValueIsZero if you don't know whether Op"
22910          " is a target node!");
22911
22912   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
22913   switch (Opc) {
22914   default: break;
22915   case X86ISD::ADD:
22916   case X86ISD::SUB:
22917   case X86ISD::ADC:
22918   case X86ISD::SBB:
22919   case X86ISD::SMUL:
22920   case X86ISD::UMUL:
22921   case X86ISD::INC:
22922   case X86ISD::DEC:
22923   case X86ISD::OR:
22924   case X86ISD::XOR:
22925   case X86ISD::AND:
22926     // These nodes' second result is a boolean.
22927     if (Op.getResNo() == 0)
22928       break;
22929     // Fallthrough
22930   case X86ISD::SETCC:
22931     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22932     break;
22933   case ISD::INTRINSIC_WO_CHAIN: {
22934     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22935     unsigned NumLoBits = 0;
22936     switch (IntId) {
22937     default: break;
22938     case Intrinsic::x86_sse_movmsk_ps:
22939     case Intrinsic::x86_avx_movmsk_ps_256:
22940     case Intrinsic::x86_sse2_movmsk_pd:
22941     case Intrinsic::x86_avx_movmsk_pd_256:
22942     case Intrinsic::x86_mmx_pmovmskb:
22943     case Intrinsic::x86_sse2_pmovmskb_128:
22944     case Intrinsic::x86_avx2_pmovmskb: {
22945       // High bits of movmskp{s|d}, pmovmskb are known zero.
22946       switch (IntId) {
22947         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22948         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22949         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22950         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22951         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22952         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22953         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22954         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22955       }
22956       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22957       break;
22958     }
22959     }
22960     break;
22961   }
22962   }
22963 }
22964
22965 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22966   SDValue Op,
22967   const SelectionDAG &,
22968   unsigned Depth) const {
22969   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22970   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22971     return Op.getValueType().getScalarSizeInBits();
22972
22973   // Fallback case.
22974   return 1;
22975 }
22976
22977 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22978 /// node is a GlobalAddress + offset.
22979 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22980                                        const GlobalValue* &GA,
22981                                        int64_t &Offset) const {
22982   if (N->getOpcode() == X86ISD::Wrapper) {
22983     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22984       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22985       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22986       return true;
22987     }
22988   }
22989   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22990 }
22991
22992 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22993 /// FIXME: This could be expanded to support 512 bit vectors as well.
22994 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22995                                         TargetLowering::DAGCombinerInfo &DCI,
22996                                         const X86Subtarget* Subtarget) {
22997   SDLoc dl(N);
22998   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22999   SDValue V1 = SVOp->getOperand(0);
23000   SDValue V2 = SVOp->getOperand(1);
23001   MVT VT = SVOp->getSimpleValueType(0);
23002   unsigned NumElems = VT.getVectorNumElements();
23003
23004   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
23005       V2.getOpcode() == ISD::CONCAT_VECTORS) {
23006     //
23007     //                   0,0,0,...
23008     //                      |
23009     //    V      UNDEF    BUILD_VECTOR    UNDEF
23010     //     \      /           \           /
23011     //  CONCAT_VECTOR         CONCAT_VECTOR
23012     //         \                  /
23013     //          \                /
23014     //          RESULT: V + zero extended
23015     //
23016     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
23017         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
23018         V1.getOperand(1).getOpcode() != ISD::UNDEF)
23019       return SDValue();
23020
23021     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
23022       return SDValue();
23023
23024     // To match the shuffle mask, the first half of the mask should
23025     // be exactly the first vector, and all the rest a splat with the
23026     // first element of the second one.
23027     for (unsigned i = 0; i != NumElems/2; ++i)
23028       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
23029           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
23030         return SDValue();
23031
23032     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
23033     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
23034       if (Ld->hasNUsesOfValue(1, 0)) {
23035         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
23036         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
23037         SDValue ResNode =
23038           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
23039                                   Ld->getMemoryVT(),
23040                                   Ld->getPointerInfo(),
23041                                   Ld->getAlignment(),
23042                                   false/*isVolatile*/, true/*ReadMem*/,
23043                                   false/*WriteMem*/);
23044
23045         // Make sure the newly-created LOAD is in the same position as Ld in
23046         // terms of dependency. We create a TokenFactor for Ld and ResNode,
23047         // and update uses of Ld's output chain to use the TokenFactor.
23048         if (Ld->hasAnyUseOfValue(1)) {
23049           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23050                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
23051           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
23052           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
23053                                  SDValue(ResNode.getNode(), 1));
23054         }
23055
23056         return DAG.getBitcast(VT, ResNode);
23057       }
23058     }
23059
23060     // Emit a zeroed vector and insert the desired subvector on its
23061     // first half.
23062     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
23063     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
23064     return DCI.CombineTo(N, InsV);
23065   }
23066
23067   return SDValue();
23068 }
23069
23070 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
23071 /// possible.
23072 ///
23073 /// This is the leaf of the recursive combinine below. When we have found some
23074 /// chain of single-use x86 shuffle instructions and accumulated the combined
23075 /// shuffle mask represented by them, this will try to pattern match that mask
23076 /// into either a single instruction if there is a special purpose instruction
23077 /// for this operation, or into a PSHUFB instruction which is a fully general
23078 /// instruction but should only be used to replace chains over a certain depth.
23079 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
23080                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
23081                                    TargetLowering::DAGCombinerInfo &DCI,
23082                                    const X86Subtarget *Subtarget) {
23083   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
23084
23085   // Find the operand that enters the chain. Note that multiple uses are OK
23086   // here, we're not going to remove the operand we find.
23087   SDValue Input = Op.getOperand(0);
23088   while (Input.getOpcode() == ISD::BITCAST)
23089     Input = Input.getOperand(0);
23090
23091   MVT VT = Input.getSimpleValueType();
23092   MVT RootVT = Root.getSimpleValueType();
23093   SDLoc DL(Root);
23094
23095   if (Mask.size() == 1) {
23096     int Index = Mask[0];
23097     assert((Index >= 0 || Index == SM_SentinelUndef ||
23098             Index == SM_SentinelZero) &&
23099            "Invalid shuffle index found!");
23100
23101     // We may end up with an accumulated mask of size 1 as a result of
23102     // widening of shuffle operands (see function canWidenShuffleElements).
23103     // If the only shuffle index is equal to SM_SentinelZero then propagate
23104     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
23105     // mask, and therefore the entire chain of shuffles can be folded away.
23106     if (Index == SM_SentinelZero)
23107       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
23108     else
23109       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
23110                     /*AddTo*/ true);
23111     return true;
23112   }
23113
23114   // Use the float domain if the operand type is a floating point type.
23115   bool FloatDomain = VT.isFloatingPoint();
23116
23117   // For floating point shuffles, we don't have free copies in the shuffle
23118   // instructions or the ability to load as part of the instruction, so
23119   // canonicalize their shuffles to UNPCK or MOV variants.
23120   //
23121   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
23122   // vectors because it can have a load folded into it that UNPCK cannot. This
23123   // doesn't preclude something switching to the shorter encoding post-RA.
23124   //
23125   // FIXME: Should teach these routines about AVX vector widths.
23126   if (FloatDomain && VT.is128BitVector()) {
23127     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
23128       bool Lo = Mask.equals({0, 0});
23129       unsigned Shuffle;
23130       MVT ShuffleVT;
23131       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
23132       // is no slower than UNPCKLPD but has the option to fold the input operand
23133       // into even an unaligned memory load.
23134       if (Lo && Subtarget->hasSSE3()) {
23135         Shuffle = X86ISD::MOVDDUP;
23136         ShuffleVT = MVT::v2f64;
23137       } else {
23138         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
23139         // than the UNPCK variants.
23140         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
23141         ShuffleVT = MVT::v4f32;
23142       }
23143       if (Depth == 1 && Root->getOpcode() == Shuffle)
23144         return false; // Nothing to do!
23145       Op = DAG.getBitcast(ShuffleVT, Input);
23146       DCI.AddToWorklist(Op.getNode());
23147       if (Shuffle == X86ISD::MOVDDUP)
23148         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23149       else
23150         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23151       DCI.AddToWorklist(Op.getNode());
23152       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23153                     /*AddTo*/ true);
23154       return true;
23155     }
23156     if (Subtarget->hasSSE3() &&
23157         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
23158       bool Lo = Mask.equals({0, 0, 2, 2});
23159       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
23160       MVT ShuffleVT = MVT::v4f32;
23161       if (Depth == 1 && Root->getOpcode() == Shuffle)
23162         return false; // Nothing to do!
23163       Op = DAG.getBitcast(ShuffleVT, Input);
23164       DCI.AddToWorklist(Op.getNode());
23165       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23166       DCI.AddToWorklist(Op.getNode());
23167       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23168                     /*AddTo*/ true);
23169       return true;
23170     }
23171     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
23172       bool Lo = Mask.equals({0, 0, 1, 1});
23173       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23174       MVT ShuffleVT = MVT::v4f32;
23175       if (Depth == 1 && Root->getOpcode() == Shuffle)
23176         return false; // Nothing to do!
23177       Op = DAG.getBitcast(ShuffleVT, Input);
23178       DCI.AddToWorklist(Op.getNode());
23179       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23180       DCI.AddToWorklist(Op.getNode());
23181       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23182                     /*AddTo*/ true);
23183       return true;
23184     }
23185   }
23186
23187   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
23188   // variants as none of these have single-instruction variants that are
23189   // superior to the UNPCK formulation.
23190   if (!FloatDomain && VT.is128BitVector() &&
23191       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23192        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
23193        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
23194        Mask.equals(
23195            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
23196     bool Lo = Mask[0] == 0;
23197     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23198     if (Depth == 1 && Root->getOpcode() == Shuffle)
23199       return false; // Nothing to do!
23200     MVT ShuffleVT;
23201     switch (Mask.size()) {
23202     case 8:
23203       ShuffleVT = MVT::v8i16;
23204       break;
23205     case 16:
23206       ShuffleVT = MVT::v16i8;
23207       break;
23208     default:
23209       llvm_unreachable("Impossible mask size!");
23210     };
23211     Op = DAG.getBitcast(ShuffleVT, Input);
23212     DCI.AddToWorklist(Op.getNode());
23213     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23214     DCI.AddToWorklist(Op.getNode());
23215     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23216                   /*AddTo*/ true);
23217     return true;
23218   }
23219
23220   // Don't try to re-form single instruction chains under any circumstances now
23221   // that we've done encoding canonicalization for them.
23222   if (Depth < 2)
23223     return false;
23224
23225   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
23226   // can replace them with a single PSHUFB instruction profitably. Intel's
23227   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
23228   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
23229   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
23230     SmallVector<SDValue, 16> PSHUFBMask;
23231     int NumBytes = VT.getSizeInBits() / 8;
23232     int Ratio = NumBytes / Mask.size();
23233     for (int i = 0; i < NumBytes; ++i) {
23234       if (Mask[i / Ratio] == SM_SentinelUndef) {
23235         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
23236         continue;
23237       }
23238       int M = Mask[i / Ratio] != SM_SentinelZero
23239                   ? Ratio * Mask[i / Ratio] + i % Ratio
23240                   : 255;
23241       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
23242     }
23243     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
23244     Op = DAG.getBitcast(ByteVT, Input);
23245     DCI.AddToWorklist(Op.getNode());
23246     SDValue PSHUFBMaskOp =
23247         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
23248     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
23249     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
23250     DCI.AddToWorklist(Op.getNode());
23251     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23252                   /*AddTo*/ true);
23253     return true;
23254   }
23255
23256   // Failed to find any combines.
23257   return false;
23258 }
23259
23260 /// \brief Fully generic combining of x86 shuffle instructions.
23261 ///
23262 /// This should be the last combine run over the x86 shuffle instructions. Once
23263 /// they have been fully optimized, this will recursively consider all chains
23264 /// of single-use shuffle instructions, build a generic model of the cumulative
23265 /// shuffle operation, and check for simpler instructions which implement this
23266 /// operation. We use this primarily for two purposes:
23267 ///
23268 /// 1) Collapse generic shuffles to specialized single instructions when
23269 ///    equivalent. In most cases, this is just an encoding size win, but
23270 ///    sometimes we will collapse multiple generic shuffles into a single
23271 ///    special-purpose shuffle.
23272 /// 2) Look for sequences of shuffle instructions with 3 or more total
23273 ///    instructions, and replace them with the slightly more expensive SSSE3
23274 ///    PSHUFB instruction if available. We do this as the last combining step
23275 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
23276 ///    a suitable short sequence of other instructions. The PHUFB will either
23277 ///    use a register or have to read from memory and so is slightly (but only
23278 ///    slightly) more expensive than the other shuffle instructions.
23279 ///
23280 /// Because this is inherently a quadratic operation (for each shuffle in
23281 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
23282 /// This should never be an issue in practice as the shuffle lowering doesn't
23283 /// produce sequences of more than 8 instructions.
23284 ///
23285 /// FIXME: We will currently miss some cases where the redundant shuffling
23286 /// would simplify under the threshold for PSHUFB formation because of
23287 /// combine-ordering. To fix this, we should do the redundant instruction
23288 /// combining in this recursive walk.
23289 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
23290                                           ArrayRef<int> RootMask,
23291                                           int Depth, bool HasPSHUFB,
23292                                           SelectionDAG &DAG,
23293                                           TargetLowering::DAGCombinerInfo &DCI,
23294                                           const X86Subtarget *Subtarget) {
23295   // Bound the depth of our recursive combine because this is ultimately
23296   // quadratic in nature.
23297   if (Depth > 8)
23298     return false;
23299
23300   // Directly rip through bitcasts to find the underlying operand.
23301   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
23302     Op = Op.getOperand(0);
23303
23304   MVT VT = Op.getSimpleValueType();
23305   if (!VT.isVector())
23306     return false; // Bail if we hit a non-vector.
23307
23308   assert(Root.getSimpleValueType().isVector() &&
23309          "Shuffles operate on vector types!");
23310   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
23311          "Can only combine shuffles of the same vector register size.");
23312
23313   if (!isTargetShuffle(Op.getOpcode()))
23314     return false;
23315   SmallVector<int, 16> OpMask;
23316   bool IsUnary;
23317   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, true, OpMask, IsUnary);
23318   // We only can combine unary shuffles which we can decode the mask for.
23319   if (!HaveMask || !IsUnary)
23320     return false;
23321
23322   assert(VT.getVectorNumElements() == OpMask.size() &&
23323          "Different mask size from vector size!");
23324   assert(((RootMask.size() > OpMask.size() &&
23325            RootMask.size() % OpMask.size() == 0) ||
23326           (OpMask.size() > RootMask.size() &&
23327            OpMask.size() % RootMask.size() == 0) ||
23328           OpMask.size() == RootMask.size()) &&
23329          "The smaller number of elements must divide the larger.");
23330   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
23331   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
23332   assert(((RootRatio == 1 && OpRatio == 1) ||
23333           (RootRatio == 1) != (OpRatio == 1)) &&
23334          "Must not have a ratio for both incoming and op masks!");
23335
23336   SmallVector<int, 16> Mask;
23337   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
23338
23339   // Merge this shuffle operation's mask into our accumulated mask. Note that
23340   // this shuffle's mask will be the first applied to the input, followed by the
23341   // root mask to get us all the way to the root value arrangement. The reason
23342   // for this order is that we are recursing up the operation chain.
23343   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
23344     int RootIdx = i / RootRatio;
23345     if (RootMask[RootIdx] < 0) {
23346       // This is a zero or undef lane, we're done.
23347       Mask.push_back(RootMask[RootIdx]);
23348       continue;
23349     }
23350
23351     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
23352     int OpIdx = RootMaskedIdx / OpRatio;
23353     if (OpMask[OpIdx] < 0) {
23354       // The incoming lanes are zero or undef, it doesn't matter which ones we
23355       // are using.
23356       Mask.push_back(OpMask[OpIdx]);
23357       continue;
23358     }
23359
23360     // Ok, we have non-zero lanes, map them through.
23361     Mask.push_back(OpMask[OpIdx] * OpRatio +
23362                    RootMaskedIdx % OpRatio);
23363   }
23364
23365   // See if we can recurse into the operand to combine more things.
23366   switch (Op.getOpcode()) {
23367   case X86ISD::PSHUFB:
23368     HasPSHUFB = true;
23369   case X86ISD::PSHUFD:
23370   case X86ISD::PSHUFHW:
23371   case X86ISD::PSHUFLW:
23372     if (Op.getOperand(0).hasOneUse() &&
23373         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23374                                       HasPSHUFB, DAG, DCI, Subtarget))
23375       return true;
23376     break;
23377
23378   case X86ISD::UNPCKL:
23379   case X86ISD::UNPCKH:
23380     assert(Op.getOperand(0) == Op.getOperand(1) &&
23381            "We only combine unary shuffles!");
23382     // We can't check for single use, we have to check that this shuffle is the
23383     // only user.
23384     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
23385         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23386                                       HasPSHUFB, DAG, DCI, Subtarget))
23387       return true;
23388     break;
23389   }
23390
23391   // Minor canonicalization of the accumulated shuffle mask to make it easier
23392   // to match below. All this does is detect masks with squential pairs of
23393   // elements, and shrink them to the half-width mask. It does this in a loop
23394   // so it will reduce the size of the mask to the minimal width mask which
23395   // performs an equivalent shuffle.
23396   SmallVector<int, 16> WidenedMask;
23397   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
23398     Mask = std::move(WidenedMask);
23399     WidenedMask.clear();
23400   }
23401
23402   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
23403                                 Subtarget);
23404 }
23405
23406 /// \brief Get the PSHUF-style mask from PSHUF node.
23407 ///
23408 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
23409 /// PSHUF-style masks that can be reused with such instructions.
23410 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
23411   MVT VT = N.getSimpleValueType();
23412   SmallVector<int, 4> Mask;
23413   bool IsUnary;
23414   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, false, Mask, IsUnary);
23415   (void)HaveMask;
23416   assert(HaveMask);
23417
23418   // If we have more than 128-bits, only the low 128-bits of shuffle mask
23419   // matter. Check that the upper masks are repeats and remove them.
23420   if (VT.getSizeInBits() > 128) {
23421     int LaneElts = 128 / VT.getScalarSizeInBits();
23422 #ifndef NDEBUG
23423     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
23424       for (int j = 0; j < LaneElts; ++j)
23425         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
23426                "Mask doesn't repeat in high 128-bit lanes!");
23427 #endif
23428     Mask.resize(LaneElts);
23429   }
23430
23431   switch (N.getOpcode()) {
23432   case X86ISD::PSHUFD:
23433     return Mask;
23434   case X86ISD::PSHUFLW:
23435     Mask.resize(4);
23436     return Mask;
23437   case X86ISD::PSHUFHW:
23438     Mask.erase(Mask.begin(), Mask.begin() + 4);
23439     for (int &M : Mask)
23440       M -= 4;
23441     return Mask;
23442   default:
23443     llvm_unreachable("No valid shuffle instruction found!");
23444   }
23445 }
23446
23447 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
23448 ///
23449 /// We walk up the chain and look for a combinable shuffle, skipping over
23450 /// shuffles that we could hoist this shuffle's transformation past without
23451 /// altering anything.
23452 static SDValue
23453 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23454                              SelectionDAG &DAG,
23455                              TargetLowering::DAGCombinerInfo &DCI) {
23456   assert(N.getOpcode() == X86ISD::PSHUFD &&
23457          "Called with something other than an x86 128-bit half shuffle!");
23458   SDLoc DL(N);
23459
23460   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23461   // of the shuffles in the chain so that we can form a fresh chain to replace
23462   // this one.
23463   SmallVector<SDValue, 8> Chain;
23464   SDValue V = N.getOperand(0);
23465   for (; V.hasOneUse(); V = V.getOperand(0)) {
23466     switch (V.getOpcode()) {
23467     default:
23468       return SDValue(); // Nothing combined!
23469
23470     case ISD::BITCAST:
23471       // Skip bitcasts as we always know the type for the target specific
23472       // instructions.
23473       continue;
23474
23475     case X86ISD::PSHUFD:
23476       // Found another dword shuffle.
23477       break;
23478
23479     case X86ISD::PSHUFLW:
23480       // Check that the low words (being shuffled) are the identity in the
23481       // dword shuffle, and the high words are self-contained.
23482       if (Mask[0] != 0 || Mask[1] != 1 ||
23483           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23484         return SDValue();
23485
23486       Chain.push_back(V);
23487       continue;
23488
23489     case X86ISD::PSHUFHW:
23490       // Check that the high words (being shuffled) are the identity in the
23491       // dword shuffle, and the low words are self-contained.
23492       if (Mask[2] != 2 || Mask[3] != 3 ||
23493           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23494         return SDValue();
23495
23496       Chain.push_back(V);
23497       continue;
23498
23499     case X86ISD::UNPCKL:
23500     case X86ISD::UNPCKH:
23501       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23502       // shuffle into a preceding word shuffle.
23503       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23504           V.getSimpleValueType().getVectorElementType() != MVT::i16)
23505         return SDValue();
23506
23507       // Search for a half-shuffle which we can combine with.
23508       unsigned CombineOp =
23509           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23510       if (V.getOperand(0) != V.getOperand(1) ||
23511           !V->isOnlyUserOf(V.getOperand(0).getNode()))
23512         return SDValue();
23513       Chain.push_back(V);
23514       V = V.getOperand(0);
23515       do {
23516         switch (V.getOpcode()) {
23517         default:
23518           return SDValue(); // Nothing to combine.
23519
23520         case X86ISD::PSHUFLW:
23521         case X86ISD::PSHUFHW:
23522           if (V.getOpcode() == CombineOp)
23523             break;
23524
23525           Chain.push_back(V);
23526
23527           // Fallthrough!
23528         case ISD::BITCAST:
23529           V = V.getOperand(0);
23530           continue;
23531         }
23532         break;
23533       } while (V.hasOneUse());
23534       break;
23535     }
23536     // Break out of the loop if we break out of the switch.
23537     break;
23538   }
23539
23540   if (!V.hasOneUse())
23541     // We fell out of the loop without finding a viable combining instruction.
23542     return SDValue();
23543
23544   // Merge this node's mask and our incoming mask.
23545   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23546   for (int &M : Mask)
23547     M = VMask[M];
23548   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23549                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23550
23551   // Rebuild the chain around this new shuffle.
23552   while (!Chain.empty()) {
23553     SDValue W = Chain.pop_back_val();
23554
23555     if (V.getValueType() != W.getOperand(0).getValueType())
23556       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23557
23558     switch (W.getOpcode()) {
23559     default:
23560       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23561
23562     case X86ISD::UNPCKL:
23563     case X86ISD::UNPCKH:
23564       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23565       break;
23566
23567     case X86ISD::PSHUFD:
23568     case X86ISD::PSHUFLW:
23569     case X86ISD::PSHUFHW:
23570       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23571       break;
23572     }
23573   }
23574   if (V.getValueType() != N.getValueType())
23575     V = DAG.getBitcast(N.getValueType(), V);
23576
23577   // Return the new chain to replace N.
23578   return V;
23579 }
23580
23581 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23582 /// pshufhw.
23583 ///
23584 /// We walk up the chain, skipping shuffles of the other half and looking
23585 /// through shuffles which switch halves trying to find a shuffle of the same
23586 /// pair of dwords.
23587 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23588                                         SelectionDAG &DAG,
23589                                         TargetLowering::DAGCombinerInfo &DCI) {
23590   assert(
23591       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23592       "Called with something other than an x86 128-bit half shuffle!");
23593   SDLoc DL(N);
23594   unsigned CombineOpcode = N.getOpcode();
23595
23596   // Walk up a single-use chain looking for a combinable shuffle.
23597   SDValue V = N.getOperand(0);
23598   for (; V.hasOneUse(); V = V.getOperand(0)) {
23599     switch (V.getOpcode()) {
23600     default:
23601       return false; // Nothing combined!
23602
23603     case ISD::BITCAST:
23604       // Skip bitcasts as we always know the type for the target specific
23605       // instructions.
23606       continue;
23607
23608     case X86ISD::PSHUFLW:
23609     case X86ISD::PSHUFHW:
23610       if (V.getOpcode() == CombineOpcode)
23611         break;
23612
23613       // Other-half shuffles are no-ops.
23614       continue;
23615     }
23616     // Break out of the loop if we break out of the switch.
23617     break;
23618   }
23619
23620   if (!V.hasOneUse())
23621     // We fell out of the loop without finding a viable combining instruction.
23622     return false;
23623
23624   // Combine away the bottom node as its shuffle will be accumulated into
23625   // a preceding shuffle.
23626   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23627
23628   // Record the old value.
23629   SDValue Old = V;
23630
23631   // Merge this node's mask and our incoming mask (adjusted to account for all
23632   // the pshufd instructions encountered).
23633   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23634   for (int &M : Mask)
23635     M = VMask[M];
23636   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23637                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23638
23639   // Check that the shuffles didn't cancel each other out. If not, we need to
23640   // combine to the new one.
23641   if (Old != V)
23642     // Replace the combinable shuffle with the combined one, updating all users
23643     // so that we re-evaluate the chain here.
23644     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23645
23646   return true;
23647 }
23648
23649 /// \brief Try to combine x86 target specific shuffles.
23650 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23651                                            TargetLowering::DAGCombinerInfo &DCI,
23652                                            const X86Subtarget *Subtarget) {
23653   SDLoc DL(N);
23654   MVT VT = N.getSimpleValueType();
23655   SmallVector<int, 4> Mask;
23656
23657   switch (N.getOpcode()) {
23658   case X86ISD::PSHUFD:
23659   case X86ISD::PSHUFLW:
23660   case X86ISD::PSHUFHW:
23661     Mask = getPSHUFShuffleMask(N);
23662     assert(Mask.size() == 4);
23663     break;
23664   case X86ISD::UNPCKL: {
23665     // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23666     // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23667     // moves upper half elements into the lower half part. For example:
23668     //
23669     // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23670     //     undef:v16i8
23671     // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23672     //
23673     // will be combined to:
23674     //
23675     // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23676
23677     // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23678     // happen due to advanced instructions.
23679     if (!VT.is128BitVector())
23680       return SDValue();
23681
23682     auto Op0 = N.getOperand(0);
23683     auto Op1 = N.getOperand(1);
23684     if (Op0.getOpcode() == ISD::UNDEF &&
23685         Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23686       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23687
23688       unsigned NumElts = VT.getVectorNumElements();
23689       SmallVector<int, 8> ExpectedMask(NumElts, -1);
23690       std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23691                 NumElts / 2);
23692
23693       auto ShufOp = Op1.getOperand(0);
23694       if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23695         return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23696     }
23697     return SDValue();
23698   }
23699   case X86ISD::BLENDI: {
23700     SDValue V0 = N->getOperand(0);
23701     SDValue V1 = N->getOperand(1);
23702     assert(VT == V0.getSimpleValueType() && VT == V1.getSimpleValueType() &&
23703            "Unexpected input vector types");
23704
23705     // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23706     // operands and changing the mask to 1. This saves us a bunch of
23707     // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23708     // x86InstrInfo knows how to commute this back after instruction selection
23709     // if it would help register allocation.
23710
23711     // TODO: If optimizing for size or a processor that doesn't suffer from
23712     // partial register update stalls, this should be transformed into a MOVSD
23713     // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23714
23715     if (VT == MVT::v2f64)
23716       if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23717         if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23718           SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23719           return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23720         }
23721
23722     return SDValue();
23723   }
23724   default:
23725     return SDValue();
23726   }
23727
23728   // Nuke no-op shuffles that show up after combining.
23729   if (isNoopShuffleMask(Mask))
23730     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23731
23732   // Look for simplifications involving one or two shuffle instructions.
23733   SDValue V = N.getOperand(0);
23734   switch (N.getOpcode()) {
23735   default:
23736     break;
23737   case X86ISD::PSHUFLW:
23738   case X86ISD::PSHUFHW:
23739     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23740
23741     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23742       return SDValue(); // We combined away this shuffle, so we're done.
23743
23744     // See if this reduces to a PSHUFD which is no more expensive and can
23745     // combine with more operations. Note that it has to at least flip the
23746     // dwords as otherwise it would have been removed as a no-op.
23747     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23748       int DMask[] = {0, 1, 2, 3};
23749       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23750       DMask[DOffset + 0] = DOffset + 1;
23751       DMask[DOffset + 1] = DOffset + 0;
23752       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23753       V = DAG.getBitcast(DVT, V);
23754       DCI.AddToWorklist(V.getNode());
23755       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23756                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23757       DCI.AddToWorklist(V.getNode());
23758       return DAG.getBitcast(VT, V);
23759     }
23760
23761     // Look for shuffle patterns which can be implemented as a single unpack.
23762     // FIXME: This doesn't handle the location of the PSHUFD generically, and
23763     // only works when we have a PSHUFD followed by two half-shuffles.
23764     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23765         (V.getOpcode() == X86ISD::PSHUFLW ||
23766          V.getOpcode() == X86ISD::PSHUFHW) &&
23767         V.getOpcode() != N.getOpcode() &&
23768         V.hasOneUse()) {
23769       SDValue D = V.getOperand(0);
23770       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23771         D = D.getOperand(0);
23772       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23773         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23774         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23775         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23776         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23777         int WordMask[8];
23778         for (int i = 0; i < 4; ++i) {
23779           WordMask[i + NOffset] = Mask[i] + NOffset;
23780           WordMask[i + VOffset] = VMask[i] + VOffset;
23781         }
23782         // Map the word mask through the DWord mask.
23783         int MappedMask[8];
23784         for (int i = 0; i < 8; ++i)
23785           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23786         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23787             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23788           // We can replace all three shuffles with an unpack.
23789           V = DAG.getBitcast(VT, D.getOperand(0));
23790           DCI.AddToWorklist(V.getNode());
23791           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23792                                                 : X86ISD::UNPCKH,
23793                              DL, VT, V, V);
23794         }
23795       }
23796     }
23797
23798     break;
23799
23800   case X86ISD::PSHUFD:
23801     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23802       return NewN;
23803
23804     break;
23805   }
23806
23807   return SDValue();
23808 }
23809
23810 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23811 ///
23812 /// We combine this directly on the abstract vector shuffle nodes so it is
23813 /// easier to generically match. We also insert dummy vector shuffle nodes for
23814 /// the operands which explicitly discard the lanes which are unused by this
23815 /// operation to try to flow through the rest of the combiner the fact that
23816 /// they're unused.
23817 static SDValue combineShuffleToAddSub(SDNode *N, const X86Subtarget *Subtarget,
23818                                       SelectionDAG &DAG) {
23819   SDLoc DL(N);
23820   EVT VT = N->getValueType(0);
23821   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
23822       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
23823     return SDValue();
23824
23825   // We only handle target-independent shuffles.
23826   // FIXME: It would be easy and harmless to use the target shuffle mask
23827   // extraction tool to support more.
23828   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23829     return SDValue();
23830
23831   auto *SVN = cast<ShuffleVectorSDNode>(N);
23832   SmallVector<int, 8> Mask;
23833   for (int M : SVN->getMask())
23834     Mask.push_back(M);
23835
23836   SDValue V1 = N->getOperand(0);
23837   SDValue V2 = N->getOperand(1);
23838
23839   // We require the first shuffle operand to be the FSUB node, and the second to
23840   // be the FADD node.
23841   if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23842     ShuffleVectorSDNode::commuteMask(Mask);
23843     std::swap(V1, V2);
23844   } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23845     return SDValue();
23846
23847   // If there are other uses of these operations we can't fold them.
23848   if (!V1->hasOneUse() || !V2->hasOneUse())
23849     return SDValue();
23850
23851   // Ensure that both operations have the same operands. Note that we can
23852   // commute the FADD operands.
23853   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23854   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23855       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23856     return SDValue();
23857
23858   // We're looking for blends between FADD and FSUB nodes. We insist on these
23859   // nodes being lined up in a specific expected pattern.
23860   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23861         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23862         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23863     return SDValue();
23864
23865   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23866 }
23867
23868 /// PerformShuffleCombine - Performs several different shuffle combines.
23869 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23870                                      TargetLowering::DAGCombinerInfo &DCI,
23871                                      const X86Subtarget *Subtarget) {
23872   SDLoc dl(N);
23873   SDValue N0 = N->getOperand(0);
23874   SDValue N1 = N->getOperand(1);
23875   EVT VT = N->getValueType(0);
23876
23877   // Don't create instructions with illegal types after legalize types has run.
23878   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23879   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23880     return SDValue();
23881
23882   // If we have legalized the vector types, look for blends of FADD and FSUB
23883   // nodes that we can fuse into an ADDSUB node.
23884   if (TLI.isTypeLegal(VT))
23885     if (SDValue AddSub = combineShuffleToAddSub(N, Subtarget, DAG))
23886       return AddSub;
23887
23888   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23889   if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23890       N->getOpcode() == ISD::VECTOR_SHUFFLE)
23891     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23892
23893   // During Type Legalization, when promoting illegal vector types,
23894   // the backend might introduce new shuffle dag nodes and bitcasts.
23895   //
23896   // This code performs the following transformation:
23897   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23898   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23899   //
23900   // We do this only if both the bitcast and the BINOP dag nodes have
23901   // one use. Also, perform this transformation only if the new binary
23902   // operation is legal. This is to avoid introducing dag nodes that
23903   // potentially need to be further expanded (or custom lowered) into a
23904   // less optimal sequence of dag nodes.
23905   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23906       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23907       N0.getOpcode() == ISD::BITCAST) {
23908     SDValue BC0 = N0.getOperand(0);
23909     EVT SVT = BC0.getValueType();
23910     unsigned Opcode = BC0.getOpcode();
23911     unsigned NumElts = VT.getVectorNumElements();
23912
23913     if (BC0.hasOneUse() && SVT.isVector() &&
23914         SVT.getVectorNumElements() * 2 == NumElts &&
23915         TLI.isOperationLegal(Opcode, VT)) {
23916       bool CanFold = false;
23917       switch (Opcode) {
23918       default : break;
23919       case ISD::ADD :
23920       case ISD::FADD :
23921       case ISD::SUB :
23922       case ISD::FSUB :
23923       case ISD::MUL :
23924       case ISD::FMUL :
23925         CanFold = true;
23926       }
23927
23928       unsigned SVTNumElts = SVT.getVectorNumElements();
23929       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23930       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23931         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23932       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23933         CanFold = SVOp->getMaskElt(i) < 0;
23934
23935       if (CanFold) {
23936         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23937         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23938         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23939         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23940       }
23941     }
23942   }
23943
23944   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23945   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23946   // consecutive, non-overlapping, and in the right order.
23947   SmallVector<SDValue, 16> Elts;
23948   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23949     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23950
23951   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23952     return LD;
23953
23954   if (isTargetShuffle(N->getOpcode())) {
23955     SDValue Shuffle =
23956         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23957     if (Shuffle.getNode())
23958       return Shuffle;
23959
23960     // Try recursively combining arbitrary sequences of x86 shuffle
23961     // instructions into higher-order shuffles. We do this after combining
23962     // specific PSHUF instruction sequences into their minimal form so that we
23963     // can evaluate how many specialized shuffle instructions are involved in
23964     // a particular chain.
23965     SmallVector<int, 1> NonceMask; // Just a placeholder.
23966     NonceMask.push_back(0);
23967     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23968                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23969                                       DCI, Subtarget))
23970       return SDValue(); // This routine will use CombineTo to replace N.
23971   }
23972
23973   return SDValue();
23974 }
23975
23976 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23977 /// specific shuffle of a load can be folded into a single element load.
23978 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23979 /// shuffles have been custom lowered so we need to handle those here.
23980 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23981                                          TargetLowering::DAGCombinerInfo &DCI) {
23982   if (DCI.isBeforeLegalizeOps())
23983     return SDValue();
23984
23985   SDValue InVec = N->getOperand(0);
23986   SDValue EltNo = N->getOperand(1);
23987   EVT EltVT = N->getValueType(0);
23988
23989   if (!isa<ConstantSDNode>(EltNo))
23990     return SDValue();
23991
23992   EVT OriginalVT = InVec.getValueType();
23993
23994   if (InVec.getOpcode() == ISD::BITCAST) {
23995     // Don't duplicate a load with other uses.
23996     if (!InVec.hasOneUse())
23997       return SDValue();
23998     EVT BCVT = InVec.getOperand(0).getValueType();
23999     if (!BCVT.isVector() ||
24000         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
24001       return SDValue();
24002     InVec = InVec.getOperand(0);
24003   }
24004
24005   EVT CurrentVT = InVec.getValueType();
24006
24007   if (!isTargetShuffle(InVec.getOpcode()))
24008     return SDValue();
24009
24010   // Don't duplicate a load with other uses.
24011   if (!InVec.hasOneUse())
24012     return SDValue();
24013
24014   SmallVector<int, 16> ShuffleMask;
24015   bool UnaryShuffle;
24016   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(), true,
24017                             ShuffleMask, UnaryShuffle))
24018     return SDValue();
24019
24020   // Select the input vector, guarding against out of range extract vector.
24021   unsigned NumElems = CurrentVT.getVectorNumElements();
24022   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
24023   int Idx = (Elt > (int)NumElems) ? SM_SentinelUndef : ShuffleMask[Elt];
24024
24025   if (Idx == SM_SentinelZero)
24026     return EltVT.isInteger() ? DAG.getConstant(0, SDLoc(N), EltVT)
24027                              : DAG.getConstantFP(+0.0, SDLoc(N), EltVT);
24028   if (Idx == SM_SentinelUndef)
24029     return DAG.getUNDEF(EltVT);
24030
24031   assert(0 <= Idx && Idx < (int)(2 * NumElems) && "Shuffle index out of range");
24032   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
24033                                          : InVec.getOperand(1);
24034
24035   // If inputs to shuffle are the same for both ops, then allow 2 uses
24036   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
24037                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
24038
24039   if (LdNode.getOpcode() == ISD::BITCAST) {
24040     // Don't duplicate a load with other uses.
24041     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
24042       return SDValue();
24043
24044     AllowedUses = 1; // only allow 1 load use if we have a bitcast
24045     LdNode = LdNode.getOperand(0);
24046   }
24047
24048   if (!ISD::isNormalLoad(LdNode.getNode()))
24049     return SDValue();
24050
24051   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
24052
24053   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
24054     return SDValue();
24055
24056   // If there's a bitcast before the shuffle, check if the load type and
24057   // alignment is valid.
24058   unsigned Align = LN0->getAlignment();
24059   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24060   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
24061       EltVT.getTypeForEVT(*DAG.getContext()));
24062
24063   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
24064     return SDValue();
24065
24066   // All checks match so transform back to vector_shuffle so that DAG combiner
24067   // can finish the job
24068   SDLoc dl(N);
24069
24070   // Create shuffle node taking into account the case that its a unary shuffle
24071   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
24072                                    : InVec.getOperand(1);
24073   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
24074                                  InVec.getOperand(0), Shuffle,
24075                                  &ShuffleMask[0]);
24076   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
24077   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
24078                      EltNo);
24079 }
24080
24081 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
24082                                      const X86Subtarget *Subtarget) {
24083   SDValue N0 = N->getOperand(0);
24084   EVT VT = N->getValueType(0);
24085
24086   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
24087   // special and don't usually play with other vector types, it's better to
24088   // handle them early to be sure we emit efficient code by avoiding
24089   // store-load conversions.
24090   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
24091       N0.getValueType() == MVT::v2i32 &&
24092       isNullConstant(N0.getOperand(1))) {
24093     SDValue N00 = N0->getOperand(0);
24094     if (N00.getValueType() == MVT::i32)
24095       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
24096   }
24097
24098   // Convert a bitcasted integer logic operation that has one bitcasted
24099   // floating-point operand and one constant operand into a floating-point
24100   // logic operation. This may create a load of the constant, but that is
24101   // cheaper than materializing the constant in an integer register and
24102   // transferring it to an SSE register or transferring the SSE operand to
24103   // integer register and back.
24104   unsigned FPOpcode;
24105   switch (N0.getOpcode()) {
24106     case ISD::AND: FPOpcode = X86ISD::FAND; break;
24107     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
24108     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
24109     default: return SDValue();
24110   }
24111   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
24112        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
24113       isa<ConstantSDNode>(N0.getOperand(1)) &&
24114       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
24115       N0.getOperand(0).getOperand(0).getValueType() == VT) {
24116     SDValue N000 = N0.getOperand(0).getOperand(0);
24117     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
24118     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
24119   }
24120
24121   return SDValue();
24122 }
24123
24124 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
24125 /// generation and convert it from being a bunch of shuffles and extracts
24126 /// into a somewhat faster sequence. For i686, the best sequence is apparently
24127 /// storing the value and loading scalars back, while for x64 we should
24128 /// use 64-bit extracts and shifts.
24129 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
24130                                          TargetLowering::DAGCombinerInfo &DCI) {
24131   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
24132     return NewOp;
24133
24134   SDValue InputVector = N->getOperand(0);
24135   SDLoc dl(InputVector);
24136   // Detect mmx to i32 conversion through a v2i32 elt extract.
24137   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
24138       N->getValueType(0) == MVT::i32 &&
24139       InputVector.getValueType() == MVT::v2i32) {
24140
24141     // The bitcast source is a direct mmx result.
24142     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
24143     if (MMXSrc.getValueType() == MVT::x86mmx)
24144       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24145                          N->getValueType(0),
24146                          InputVector.getNode()->getOperand(0));
24147
24148     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
24149     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
24150         MMXSrc.getValueType() == MVT::i64) {
24151       SDValue MMXSrcOp = MMXSrc.getOperand(0);
24152       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
24153           MMXSrcOp.getValueType() == MVT::v1i64 &&
24154           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
24155         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24156                            N->getValueType(0), MMXSrcOp.getOperand(0));
24157     }
24158   }
24159
24160   EVT VT = N->getValueType(0);
24161
24162   if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
24163       InputVector.getOpcode() == ISD::BITCAST &&
24164       isa<ConstantSDNode>(InputVector.getOperand(0))) {
24165     uint64_t ExtractedElt =
24166         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
24167     uint64_t InputValue =
24168         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
24169     uint64_t Res = (InputValue >> ExtractedElt) & 1;
24170     return DAG.getConstant(Res, dl, MVT::i1);
24171   }
24172   // Only operate on vectors of 4 elements, where the alternative shuffling
24173   // gets to be more expensive.
24174   if (InputVector.getValueType() != MVT::v4i32)
24175     return SDValue();
24176
24177   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
24178   // single use which is a sign-extend or zero-extend, and all elements are
24179   // used.
24180   SmallVector<SDNode *, 4> Uses;
24181   unsigned ExtractedElements = 0;
24182   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
24183        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
24184     if (UI.getUse().getResNo() != InputVector.getResNo())
24185       return SDValue();
24186
24187     SDNode *Extract = *UI;
24188     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
24189       return SDValue();
24190
24191     if (Extract->getValueType(0) != MVT::i32)
24192       return SDValue();
24193     if (!Extract->hasOneUse())
24194       return SDValue();
24195     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
24196         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
24197       return SDValue();
24198     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
24199       return SDValue();
24200
24201     // Record which element was extracted.
24202     ExtractedElements |=
24203       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
24204
24205     Uses.push_back(Extract);
24206   }
24207
24208   // If not all the elements were used, this may not be worthwhile.
24209   if (ExtractedElements != 15)
24210     return SDValue();
24211
24212   // Ok, we've now decided to do the transformation.
24213   // If 64-bit shifts are legal, use the extract-shift sequence,
24214   // otherwise bounce the vector off the cache.
24215   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24216   SDValue Vals[4];
24217
24218   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
24219     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
24220     auto &DL = DAG.getDataLayout();
24221     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
24222     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24223       DAG.getConstant(0, dl, VecIdxTy));
24224     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24225       DAG.getConstant(1, dl, VecIdxTy));
24226
24227     SDValue ShAmt = DAG.getConstant(
24228         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
24229     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
24230     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24231       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
24232     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
24233     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24234       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
24235   } else {
24236     // Store the value to a temporary stack slot.
24237     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
24238     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
24239       MachinePointerInfo(), false, false, 0);
24240
24241     EVT ElementType = InputVector.getValueType().getVectorElementType();
24242     unsigned EltSize = ElementType.getSizeInBits() / 8;
24243
24244     // Replace each use (extract) with a load of the appropriate element.
24245     for (unsigned i = 0; i < 4; ++i) {
24246       uint64_t Offset = EltSize * i;
24247       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24248       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
24249
24250       SDValue ScalarAddr =
24251           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
24252
24253       // Load the scalar.
24254       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
24255                             ScalarAddr, MachinePointerInfo(),
24256                             false, false, false, 0);
24257
24258     }
24259   }
24260
24261   // Replace the extracts
24262   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
24263     UE = Uses.end(); UI != UE; ++UI) {
24264     SDNode *Extract = *UI;
24265
24266     SDValue Idx = Extract->getOperand(1);
24267     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
24268     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
24269   }
24270
24271   // The replacement was made in place; don't return anything.
24272   return SDValue();
24273 }
24274
24275 static SDValue
24276 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
24277                                       const X86Subtarget *Subtarget) {
24278   SDLoc dl(N);
24279   SDValue Cond = N->getOperand(0);
24280   SDValue LHS = N->getOperand(1);
24281   SDValue RHS = N->getOperand(2);
24282
24283   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
24284     SDValue CondSrc = Cond->getOperand(0);
24285     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
24286       Cond = CondSrc->getOperand(0);
24287   }
24288
24289   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
24290     return SDValue();
24291
24292   // A vselect where all conditions and data are constants can be optimized into
24293   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
24294   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
24295       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
24296     return SDValue();
24297
24298   unsigned MaskValue = 0;
24299   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
24300     return SDValue();
24301
24302   MVT VT = N->getSimpleValueType(0);
24303   unsigned NumElems = VT.getVectorNumElements();
24304   SmallVector<int, 8> ShuffleMask(NumElems, -1);
24305   for (unsigned i = 0; i < NumElems; ++i) {
24306     // Be sure we emit undef where we can.
24307     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
24308       ShuffleMask[i] = -1;
24309     else
24310       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
24311   }
24312
24313   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24314   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
24315     return SDValue();
24316   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
24317 }
24318
24319 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
24320 /// nodes.
24321 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
24322                                     TargetLowering::DAGCombinerInfo &DCI,
24323                                     const X86Subtarget *Subtarget) {
24324   SDLoc DL(N);
24325   SDValue Cond = N->getOperand(0);
24326   // Get the LHS/RHS of the select.
24327   SDValue LHS = N->getOperand(1);
24328   SDValue RHS = N->getOperand(2);
24329   EVT VT = LHS.getValueType();
24330   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24331
24332   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
24333   // instructions match the semantics of the common C idiom x<y?x:y but not
24334   // x<=y?x:y, because of how they handle negative zero (which can be
24335   // ignored in unsafe-math mode).
24336   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
24337   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
24338       VT != MVT::f80 && VT != MVT::f128 &&
24339       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
24340       (Subtarget->hasSSE2() ||
24341        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
24342     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24343
24344     unsigned Opcode = 0;
24345     // Check for x CC y ? x : y.
24346     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24347         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24348       switch (CC) {
24349       default: break;
24350       case ISD::SETULT:
24351         // Converting this to a min would handle NaNs incorrectly, and swapping
24352         // the operands would cause it to handle comparisons between positive
24353         // and negative zero incorrectly.
24354         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24355           if (!DAG.getTarget().Options.UnsafeFPMath &&
24356               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24357             break;
24358           std::swap(LHS, RHS);
24359         }
24360         Opcode = X86ISD::FMIN;
24361         break;
24362       case ISD::SETOLE:
24363         // Converting this to a min would handle comparisons between positive
24364         // and negative zero incorrectly.
24365         if (!DAG.getTarget().Options.UnsafeFPMath &&
24366             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24367           break;
24368         Opcode = X86ISD::FMIN;
24369         break;
24370       case ISD::SETULE:
24371         // Converting this to a min would handle both negative zeros and NaNs
24372         // incorrectly, but we can swap the operands to fix both.
24373         std::swap(LHS, RHS);
24374       case ISD::SETOLT:
24375       case ISD::SETLT:
24376       case ISD::SETLE:
24377         Opcode = X86ISD::FMIN;
24378         break;
24379
24380       case ISD::SETOGE:
24381         // Converting this to a max would handle comparisons between positive
24382         // and negative zero incorrectly.
24383         if (!DAG.getTarget().Options.UnsafeFPMath &&
24384             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24385           break;
24386         Opcode = X86ISD::FMAX;
24387         break;
24388       case ISD::SETUGT:
24389         // Converting this to a max would handle NaNs incorrectly, and swapping
24390         // the operands would cause it to handle comparisons between positive
24391         // and negative zero incorrectly.
24392         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24393           if (!DAG.getTarget().Options.UnsafeFPMath &&
24394               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24395             break;
24396           std::swap(LHS, RHS);
24397         }
24398         Opcode = X86ISD::FMAX;
24399         break;
24400       case ISD::SETUGE:
24401         // Converting this to a max would handle both negative zeros and NaNs
24402         // incorrectly, but we can swap the operands to fix both.
24403         std::swap(LHS, RHS);
24404       case ISD::SETOGT:
24405       case ISD::SETGT:
24406       case ISD::SETGE:
24407         Opcode = X86ISD::FMAX;
24408         break;
24409       }
24410     // Check for x CC y ? y : x -- a min/max with reversed arms.
24411     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
24412                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
24413       switch (CC) {
24414       default: break;
24415       case ISD::SETOGE:
24416         // Converting this to a min would handle comparisons between positive
24417         // and negative zero incorrectly, and swapping the operands would
24418         // cause it to handle NaNs incorrectly.
24419         if (!DAG.getTarget().Options.UnsafeFPMath &&
24420             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
24421           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24422             break;
24423           std::swap(LHS, RHS);
24424         }
24425         Opcode = X86ISD::FMIN;
24426         break;
24427       case ISD::SETUGT:
24428         // Converting this to a min would handle NaNs incorrectly.
24429         if (!DAG.getTarget().Options.UnsafeFPMath &&
24430             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
24431           break;
24432         Opcode = X86ISD::FMIN;
24433         break;
24434       case ISD::SETUGE:
24435         // Converting this to a min would handle both negative zeros and NaNs
24436         // incorrectly, but we can swap the operands to fix both.
24437         std::swap(LHS, RHS);
24438       case ISD::SETOGT:
24439       case ISD::SETGT:
24440       case ISD::SETGE:
24441         Opcode = X86ISD::FMIN;
24442         break;
24443
24444       case ISD::SETULT:
24445         // Converting this to a max would handle NaNs incorrectly.
24446         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24447           break;
24448         Opcode = X86ISD::FMAX;
24449         break;
24450       case ISD::SETOLE:
24451         // Converting this to a max would handle comparisons between positive
24452         // and negative zero incorrectly, and swapping the operands would
24453         // cause it to handle NaNs incorrectly.
24454         if (!DAG.getTarget().Options.UnsafeFPMath &&
24455             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
24456           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24457             break;
24458           std::swap(LHS, RHS);
24459         }
24460         Opcode = X86ISD::FMAX;
24461         break;
24462       case ISD::SETULE:
24463         // Converting this to a max would handle both negative zeros and NaNs
24464         // incorrectly, but we can swap the operands to fix both.
24465         std::swap(LHS, RHS);
24466       case ISD::SETOLT:
24467       case ISD::SETLT:
24468       case ISD::SETLE:
24469         Opcode = X86ISD::FMAX;
24470         break;
24471       }
24472     }
24473
24474     if (Opcode)
24475       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
24476   }
24477
24478   EVT CondVT = Cond.getValueType();
24479   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
24480       CondVT.getVectorElementType() == MVT::i1) {
24481     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
24482     // lowering on KNL. In this case we convert it to
24483     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24484     // The same situation for all 128 and 256-bit vectors of i8 and i16.
24485     // Since SKX these selects have a proper lowering.
24486     EVT OpVT = LHS.getValueType();
24487     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24488         (OpVT.getVectorElementType() == MVT::i8 ||
24489          OpVT.getVectorElementType() == MVT::i16) &&
24490         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24491       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24492       DCI.AddToWorklist(Cond.getNode());
24493       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24494     }
24495   }
24496   // If this is a select between two integer constants, try to do some
24497   // optimizations.
24498   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24499     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24500       // Don't do this for crazy integer types.
24501       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24502         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24503         // so that TrueC (the true value) is larger than FalseC.
24504         bool NeedsCondInvert = false;
24505
24506         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24507             // Efficiently invertible.
24508             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
24509              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
24510               isa<ConstantSDNode>(Cond.getOperand(1))))) {
24511           NeedsCondInvert = true;
24512           std::swap(TrueC, FalseC);
24513         }
24514
24515         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
24516         if (FalseC->getAPIntValue() == 0 &&
24517             TrueC->getAPIntValue().isPowerOf2()) {
24518           if (NeedsCondInvert) // Invert the condition if needed.
24519             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24520                                DAG.getConstant(1, DL, Cond.getValueType()));
24521
24522           // Zero extend the condition if needed.
24523           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
24524
24525           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24526           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24527                              DAG.getConstant(ShAmt, DL, MVT::i8));
24528         }
24529
24530         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24531         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24532           if (NeedsCondInvert) // Invert the condition if needed.
24533             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24534                                DAG.getConstant(1, DL, Cond.getValueType()));
24535
24536           // Zero extend the condition if needed.
24537           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24538                              FalseC->getValueType(0), Cond);
24539           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24540                              SDValue(FalseC, 0));
24541         }
24542
24543         // Optimize cases that will turn into an LEA instruction.  This requires
24544         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24545         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24546           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24547           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24548
24549           bool isFastMultiplier = false;
24550           if (Diff < 10) {
24551             switch ((unsigned char)Diff) {
24552               default: break;
24553               case 1:  // result = add base, cond
24554               case 2:  // result = lea base(    , cond*2)
24555               case 3:  // result = lea base(cond, cond*2)
24556               case 4:  // result = lea base(    , cond*4)
24557               case 5:  // result = lea base(cond, cond*4)
24558               case 8:  // result = lea base(    , cond*8)
24559               case 9:  // result = lea base(cond, cond*8)
24560                 isFastMultiplier = true;
24561                 break;
24562             }
24563           }
24564
24565           if (isFastMultiplier) {
24566             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24567             if (NeedsCondInvert) // Invert the condition if needed.
24568               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24569                                  DAG.getConstant(1, DL, Cond.getValueType()));
24570
24571             // Zero extend the condition if needed.
24572             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24573                                Cond);
24574             // Scale the condition by the difference.
24575             if (Diff != 1)
24576               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24577                                  DAG.getConstant(Diff, DL,
24578                                                  Cond.getValueType()));
24579
24580             // Add the base if non-zero.
24581             if (FalseC->getAPIntValue() != 0)
24582               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24583                                  SDValue(FalseC, 0));
24584             return Cond;
24585           }
24586         }
24587       }
24588   }
24589
24590   // Canonicalize max and min:
24591   // (x > y) ? x : y -> (x >= y) ? x : y
24592   // (x < y) ? x : y -> (x <= y) ? x : y
24593   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24594   // the need for an extra compare
24595   // against zero. e.g.
24596   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24597   // subl   %esi, %edi
24598   // testl  %edi, %edi
24599   // movl   $0, %eax
24600   // cmovgl %edi, %eax
24601   // =>
24602   // xorl   %eax, %eax
24603   // subl   %esi, $edi
24604   // cmovsl %eax, %edi
24605   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24606       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24607       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24608     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24609     switch (CC) {
24610     default: break;
24611     case ISD::SETLT:
24612     case ISD::SETGT: {
24613       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24614       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24615                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
24616       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24617     }
24618     }
24619   }
24620
24621   // Early exit check
24622   if (!TLI.isTypeLegal(VT))
24623     return SDValue();
24624
24625   // Match VSELECTs into subs with unsigned saturation.
24626   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24627       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24628       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24629        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24630     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24631
24632     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24633     // left side invert the predicate to simplify logic below.
24634     SDValue Other;
24635     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24636       Other = RHS;
24637       CC = ISD::getSetCCInverse(CC, true);
24638     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24639       Other = LHS;
24640     }
24641
24642     if (Other.getNode() && Other->getNumOperands() == 2 &&
24643         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24644       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24645       SDValue CondRHS = Cond->getOperand(1);
24646
24647       // Look for a general sub with unsigned saturation first.
24648       // x >= y ? x-y : 0 --> subus x, y
24649       // x >  y ? x-y : 0 --> subus x, y
24650       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24651           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24652         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24653
24654       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24655         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24656           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24657             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24658               // If the RHS is a constant we have to reverse the const
24659               // canonicalization.
24660               // x > C-1 ? x+-C : 0 --> subus x, C
24661               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24662                   CondRHSConst->getAPIntValue() ==
24663                       (-OpRHSConst->getAPIntValue() - 1))
24664                 return DAG.getNode(
24665                     X86ISD::SUBUS, DL, VT, OpLHS,
24666                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24667
24668           // Another special case: If C was a sign bit, the sub has been
24669           // canonicalized into a xor.
24670           // FIXME: Would it be better to use computeKnownBits to determine
24671           //        whether it's safe to decanonicalize the xor?
24672           // x s< 0 ? x^C : 0 --> subus x, C
24673           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24674               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24675               OpRHSConst->getAPIntValue().isSignBit())
24676             // Note that we have to rebuild the RHS constant here to ensure we
24677             // don't rely on particular values of undef lanes.
24678             return DAG.getNode(
24679                 X86ISD::SUBUS, DL, VT, OpLHS,
24680                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24681         }
24682     }
24683   }
24684
24685   // Simplify vector selection if condition value type matches vselect
24686   // operand type
24687   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24688     assert(Cond.getValueType().isVector() &&
24689            "vector select expects a vector selector!");
24690
24691     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24692     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24693
24694     // Try invert the condition if true value is not all 1s and false value
24695     // is not all 0s.
24696     if (!TValIsAllOnes && !FValIsAllZeros &&
24697         // Check if the selector will be produced by CMPP*/PCMP*
24698         Cond.getOpcode() == ISD::SETCC &&
24699         // Check if SETCC has already been promoted
24700         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24701             CondVT) {
24702       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24703       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24704
24705       if (TValIsAllZeros || FValIsAllOnes) {
24706         SDValue CC = Cond.getOperand(2);
24707         ISD::CondCode NewCC =
24708           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24709                                Cond.getOperand(0).getValueType().isInteger());
24710         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24711         std::swap(LHS, RHS);
24712         TValIsAllOnes = FValIsAllOnes;
24713         FValIsAllZeros = TValIsAllZeros;
24714       }
24715     }
24716
24717     if (TValIsAllOnes || FValIsAllZeros) {
24718       SDValue Ret;
24719
24720       if (TValIsAllOnes && FValIsAllZeros)
24721         Ret = Cond;
24722       else if (TValIsAllOnes)
24723         Ret =
24724             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24725       else if (FValIsAllZeros)
24726         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24727                           DAG.getBitcast(CondVT, LHS));
24728
24729       return DAG.getBitcast(VT, Ret);
24730     }
24731   }
24732
24733   // We should generate an X86ISD::BLENDI from a vselect if its argument
24734   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24735   // constants. This specific pattern gets generated when we split a
24736   // selector for a 512 bit vector in a machine without AVX512 (but with
24737   // 256-bit vectors), during legalization:
24738   //
24739   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24740   //
24741   // Iff we find this pattern and the build_vectors are built from
24742   // constants, we translate the vselect into a shuffle_vector that we
24743   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24744   if ((N->getOpcode() == ISD::VSELECT ||
24745        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24746       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24747     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24748     if (Shuffle.getNode())
24749       return Shuffle;
24750   }
24751
24752   // If this is a *dynamic* select (non-constant condition) and we can match
24753   // this node with one of the variable blend instructions, restructure the
24754   // condition so that the blends can use the high bit of each element and use
24755   // SimplifyDemandedBits to simplify the condition operand.
24756   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24757       !DCI.isBeforeLegalize() &&
24758       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24759     unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24760
24761     // Don't optimize vector selects that map to mask-registers.
24762     if (BitWidth == 1)
24763       return SDValue();
24764
24765     // We can only handle the cases where VSELECT is directly legal on the
24766     // subtarget. We custom lower VSELECT nodes with constant conditions and
24767     // this makes it hard to see whether a dynamic VSELECT will correctly
24768     // lower, so we both check the operation's status and explicitly handle the
24769     // cases where a *dynamic* blend will fail even though a constant-condition
24770     // blend could be custom lowered.
24771     // FIXME: We should find a better way to handle this class of problems.
24772     // Potentially, we should combine constant-condition vselect nodes
24773     // pre-legalization into shuffles and not mark as many types as custom
24774     // lowered.
24775     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24776       return SDValue();
24777     // FIXME: We don't support i16-element blends currently. We could and
24778     // should support them by making *all* the bits in the condition be set
24779     // rather than just the high bit and using an i8-element blend.
24780     if (VT.getVectorElementType() == MVT::i16)
24781       return SDValue();
24782     // Dynamic blending was only available from SSE4.1 onward.
24783     if (VT.is128BitVector() && !Subtarget->hasSSE41())
24784       return SDValue();
24785     // Byte blends are only available in AVX2
24786     if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24787       return SDValue();
24788
24789     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24790     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24791
24792     APInt KnownZero, KnownOne;
24793     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24794                                           DCI.isBeforeLegalizeOps());
24795     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24796         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24797                                  TLO)) {
24798       // If we changed the computation somewhere in the DAG, this change
24799       // will affect all users of Cond.
24800       // Make sure it is fine and update all the nodes so that we do not
24801       // use the generic VSELECT anymore. Otherwise, we may perform
24802       // wrong optimizations as we messed up with the actual expectation
24803       // for the vector boolean values.
24804       if (Cond != TLO.Old) {
24805         // Check all uses of that condition operand to check whether it will be
24806         // consumed by non-BLEND instructions, which may depend on all bits are
24807         // set properly.
24808         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24809              I != E; ++I)
24810           if (I->getOpcode() != ISD::VSELECT)
24811             // TODO: Add other opcodes eventually lowered into BLEND.
24812             return SDValue();
24813
24814         // Update all the users of the condition, before committing the change,
24815         // so that the VSELECT optimizations that expect the correct vector
24816         // boolean value will not be triggered.
24817         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24818              I != E; ++I)
24819           DAG.ReplaceAllUsesOfValueWith(
24820               SDValue(*I, 0),
24821               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24822                           Cond, I->getOperand(1), I->getOperand(2)));
24823         DCI.CommitTargetLoweringOpt(TLO);
24824         return SDValue();
24825       }
24826       // At this point, only Cond is changed. Change the condition
24827       // just for N to keep the opportunity to optimize all other
24828       // users their own way.
24829       DAG.ReplaceAllUsesOfValueWith(
24830           SDValue(N, 0),
24831           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24832                       TLO.New, N->getOperand(1), N->getOperand(2)));
24833       return SDValue();
24834     }
24835   }
24836
24837   return SDValue();
24838 }
24839
24840 // Check whether a boolean test is testing a boolean value generated by
24841 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24842 // code.
24843 //
24844 // Simplify the following patterns:
24845 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24846 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24847 // to (Op EFLAGS Cond)
24848 //
24849 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24850 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24851 // to (Op EFLAGS !Cond)
24852 //
24853 // where Op could be BRCOND or CMOV.
24854 //
24855 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24856   // Quit if not CMP and SUB with its value result used.
24857   if (Cmp.getOpcode() != X86ISD::CMP &&
24858       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24859       return SDValue();
24860
24861   // Quit if not used as a boolean value.
24862   if (CC != X86::COND_E && CC != X86::COND_NE)
24863     return SDValue();
24864
24865   // Check CMP operands. One of them should be 0 or 1 and the other should be
24866   // an SetCC or extended from it.
24867   SDValue Op1 = Cmp.getOperand(0);
24868   SDValue Op2 = Cmp.getOperand(1);
24869
24870   SDValue SetCC;
24871   const ConstantSDNode* C = nullptr;
24872   bool needOppositeCond = (CC == X86::COND_E);
24873   bool checkAgainstTrue = false; // Is it a comparison against 1?
24874
24875   if ((C = dyn_cast<ConstantSDNode>(Op1)))
24876     SetCC = Op2;
24877   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24878     SetCC = Op1;
24879   else // Quit if all operands are not constants.
24880     return SDValue();
24881
24882   if (C->getZExtValue() == 1) {
24883     needOppositeCond = !needOppositeCond;
24884     checkAgainstTrue = true;
24885   } else if (C->getZExtValue() != 0)
24886     // Quit if the constant is neither 0 or 1.
24887     return SDValue();
24888
24889   bool truncatedToBoolWithAnd = false;
24890   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24891   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24892          SetCC.getOpcode() == ISD::TRUNCATE ||
24893          SetCC.getOpcode() == ISD::AND) {
24894     if (SetCC.getOpcode() == ISD::AND) {
24895       int OpIdx = -1;
24896       if (isOneConstant(SetCC.getOperand(0)))
24897         OpIdx = 1;
24898       if (isOneConstant(SetCC.getOperand(1)))
24899         OpIdx = 0;
24900       if (OpIdx == -1)
24901         break;
24902       SetCC = SetCC.getOperand(OpIdx);
24903       truncatedToBoolWithAnd = true;
24904     } else
24905       SetCC = SetCC.getOperand(0);
24906   }
24907
24908   switch (SetCC.getOpcode()) {
24909   case X86ISD::SETCC_CARRY:
24910     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24911     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24912     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24913     // truncated to i1 using 'and'.
24914     if (checkAgainstTrue && !truncatedToBoolWithAnd)
24915       break;
24916     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24917            "Invalid use of SETCC_CARRY!");
24918     // FALL THROUGH
24919   case X86ISD::SETCC:
24920     // Set the condition code or opposite one if necessary.
24921     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24922     if (needOppositeCond)
24923       CC = X86::GetOppositeBranchCondition(CC);
24924     return SetCC.getOperand(1);
24925   case X86ISD::CMOV: {
24926     // Check whether false/true value has canonical one, i.e. 0 or 1.
24927     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24928     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24929     // Quit if true value is not a constant.
24930     if (!TVal)
24931       return SDValue();
24932     // Quit if false value is not a constant.
24933     if (!FVal) {
24934       SDValue Op = SetCC.getOperand(0);
24935       // Skip 'zext' or 'trunc' node.
24936       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24937           Op.getOpcode() == ISD::TRUNCATE)
24938         Op = Op.getOperand(0);
24939       // A special case for rdrand/rdseed, where 0 is set if false cond is
24940       // found.
24941       if ((Op.getOpcode() != X86ISD::RDRAND &&
24942            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24943         return SDValue();
24944     }
24945     // Quit if false value is not the constant 0 or 1.
24946     bool FValIsFalse = true;
24947     if (FVal && FVal->getZExtValue() != 0) {
24948       if (FVal->getZExtValue() != 1)
24949         return SDValue();
24950       // If FVal is 1, opposite cond is needed.
24951       needOppositeCond = !needOppositeCond;
24952       FValIsFalse = false;
24953     }
24954     // Quit if TVal is not the constant opposite of FVal.
24955     if (FValIsFalse && TVal->getZExtValue() != 1)
24956       return SDValue();
24957     if (!FValIsFalse && TVal->getZExtValue() != 0)
24958       return SDValue();
24959     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24960     if (needOppositeCond)
24961       CC = X86::GetOppositeBranchCondition(CC);
24962     return SetCC.getOperand(3);
24963   }
24964   }
24965
24966   return SDValue();
24967 }
24968
24969 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24970 /// Match:
24971 ///   (X86or (X86setcc) (X86setcc))
24972 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24973 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24974                                            X86::CondCode &CC1, SDValue &Flags,
24975                                            bool &isAnd) {
24976   if (Cond->getOpcode() == X86ISD::CMP) {
24977     if (!isNullConstant(Cond->getOperand(1)))
24978       return false;
24979
24980     Cond = Cond->getOperand(0);
24981   }
24982
24983   isAnd = false;
24984
24985   SDValue SetCC0, SetCC1;
24986   switch (Cond->getOpcode()) {
24987   default: return false;
24988   case ISD::AND:
24989   case X86ISD::AND:
24990     isAnd = true;
24991     // fallthru
24992   case ISD::OR:
24993   case X86ISD::OR:
24994     SetCC0 = Cond->getOperand(0);
24995     SetCC1 = Cond->getOperand(1);
24996     break;
24997   };
24998
24999   // Make sure we have SETCC nodes, using the same flags value.
25000   if (SetCC0.getOpcode() != X86ISD::SETCC ||
25001       SetCC1.getOpcode() != X86ISD::SETCC ||
25002       SetCC0->getOperand(1) != SetCC1->getOperand(1))
25003     return false;
25004
25005   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
25006   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
25007   Flags = SetCC0->getOperand(1);
25008   return true;
25009 }
25010
25011 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
25012 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
25013                                   TargetLowering::DAGCombinerInfo &DCI,
25014                                   const X86Subtarget *Subtarget) {
25015   SDLoc DL(N);
25016
25017   // If the flag operand isn't dead, don't touch this CMOV.
25018   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
25019     return SDValue();
25020
25021   SDValue FalseOp = N->getOperand(0);
25022   SDValue TrueOp = N->getOperand(1);
25023   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
25024   SDValue Cond = N->getOperand(3);
25025
25026   if (CC == X86::COND_E || CC == X86::COND_NE) {
25027     switch (Cond.getOpcode()) {
25028     default: break;
25029     case X86ISD::BSR:
25030     case X86ISD::BSF:
25031       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
25032       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
25033         return (CC == X86::COND_E) ? FalseOp : TrueOp;
25034     }
25035   }
25036
25037   SDValue Flags;
25038
25039   Flags = checkBoolTestSetCCCombine(Cond, CC);
25040   if (Flags.getNode() &&
25041       // Extra check as FCMOV only supports a subset of X86 cond.
25042       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
25043     SDValue Ops[] = { FalseOp, TrueOp,
25044                       DAG.getConstant(CC, DL, MVT::i8), Flags };
25045     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25046   }
25047
25048   // If this is a select between two integer constants, try to do some
25049   // optimizations.  Note that the operands are ordered the opposite of SELECT
25050   // operands.
25051   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
25052     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
25053       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
25054       // larger than FalseC (the false value).
25055       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
25056         CC = X86::GetOppositeBranchCondition(CC);
25057         std::swap(TrueC, FalseC);
25058         std::swap(TrueOp, FalseOp);
25059       }
25060
25061       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
25062       // This is efficient for any integer data type (including i8/i16) and
25063       // shift amount.
25064       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
25065         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25066                            DAG.getConstant(CC, DL, MVT::i8), Cond);
25067
25068         // Zero extend the condition if needed.
25069         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
25070
25071         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
25072         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
25073                            DAG.getConstant(ShAmt, DL, MVT::i8));
25074         if (N->getNumValues() == 2)  // Dead flag value?
25075           return DCI.CombineTo(N, Cond, SDValue());
25076         return Cond;
25077       }
25078
25079       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
25080       // for any integer data type, including i8/i16.
25081       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
25082         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25083                            DAG.getConstant(CC, DL, MVT::i8), Cond);
25084
25085         // Zero extend the condition if needed.
25086         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
25087                            FalseC->getValueType(0), Cond);
25088         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25089                            SDValue(FalseC, 0));
25090
25091         if (N->getNumValues() == 2)  // Dead flag value?
25092           return DCI.CombineTo(N, Cond, SDValue());
25093         return Cond;
25094       }
25095
25096       // Optimize cases that will turn into an LEA instruction.  This requires
25097       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
25098       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
25099         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
25100         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
25101
25102         bool isFastMultiplier = false;
25103         if (Diff < 10) {
25104           switch ((unsigned char)Diff) {
25105           default: break;
25106           case 1:  // result = add base, cond
25107           case 2:  // result = lea base(    , cond*2)
25108           case 3:  // result = lea base(cond, cond*2)
25109           case 4:  // result = lea base(    , cond*4)
25110           case 5:  // result = lea base(cond, cond*4)
25111           case 8:  // result = lea base(    , cond*8)
25112           case 9:  // result = lea base(cond, cond*8)
25113             isFastMultiplier = true;
25114             break;
25115           }
25116         }
25117
25118         if (isFastMultiplier) {
25119           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
25120           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25121                              DAG.getConstant(CC, DL, MVT::i8), Cond);
25122           // Zero extend the condition if needed.
25123           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
25124                              Cond);
25125           // Scale the condition by the difference.
25126           if (Diff != 1)
25127             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
25128                                DAG.getConstant(Diff, DL, Cond.getValueType()));
25129
25130           // Add the base if non-zero.
25131           if (FalseC->getAPIntValue() != 0)
25132             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25133                                SDValue(FalseC, 0));
25134           if (N->getNumValues() == 2)  // Dead flag value?
25135             return DCI.CombineTo(N, Cond, SDValue());
25136           return Cond;
25137         }
25138       }
25139     }
25140   }
25141
25142   // Handle these cases:
25143   //   (select (x != c), e, c) -> select (x != c), e, x),
25144   //   (select (x == c), c, e) -> select (x == c), x, e)
25145   // where the c is an integer constant, and the "select" is the combination
25146   // of CMOV and CMP.
25147   //
25148   // The rationale for this change is that the conditional-move from a constant
25149   // needs two instructions, however, conditional-move from a register needs
25150   // only one instruction.
25151   //
25152   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
25153   //  some instruction-combining opportunities. This opt needs to be
25154   //  postponed as late as possible.
25155   //
25156   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
25157     // the DCI.xxxx conditions are provided to postpone the optimization as
25158     // late as possible.
25159
25160     ConstantSDNode *CmpAgainst = nullptr;
25161     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
25162         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
25163         !isa<ConstantSDNode>(Cond.getOperand(0))) {
25164
25165       if (CC == X86::COND_NE &&
25166           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
25167         CC = X86::GetOppositeBranchCondition(CC);
25168         std::swap(TrueOp, FalseOp);
25169       }
25170
25171       if (CC == X86::COND_E &&
25172           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
25173         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
25174                           DAG.getConstant(CC, DL, MVT::i8), Cond };
25175         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
25176       }
25177     }
25178   }
25179
25180   // Fold and/or of setcc's to double CMOV:
25181   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
25182   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
25183   //
25184   // This combine lets us generate:
25185   //   cmovcc1 (jcc1 if we don't have CMOV)
25186   //   cmovcc2 (same)
25187   // instead of:
25188   //   setcc1
25189   //   setcc2
25190   //   and/or
25191   //   cmovne (jne if we don't have CMOV)
25192   // When we can't use the CMOV instruction, it might increase branch
25193   // mispredicts.
25194   // When we can use CMOV, or when there is no mispredict, this improves
25195   // throughput and reduces register pressure.
25196   //
25197   if (CC == X86::COND_NE) {
25198     SDValue Flags;
25199     X86::CondCode CC0, CC1;
25200     bool isAndSetCC;
25201     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
25202       if (isAndSetCC) {
25203         std::swap(FalseOp, TrueOp);
25204         CC0 = X86::GetOppositeBranchCondition(CC0);
25205         CC1 = X86::GetOppositeBranchCondition(CC1);
25206       }
25207
25208       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
25209         Flags};
25210       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
25211       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
25212       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25213       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
25214       return CMOV;
25215     }
25216   }
25217
25218   return SDValue();
25219 }
25220
25221 /// PerformMulCombine - Optimize a single multiply with constant into two
25222 /// in order to implement it with two cheaper instructions, e.g.
25223 /// LEA + SHL, LEA + LEA.
25224 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
25225                                  TargetLowering::DAGCombinerInfo &DCI) {
25226   // An imul is usually smaller than the alternative sequence.
25227   if (DAG.getMachineFunction().getFunction()->optForMinSize())
25228     return SDValue();
25229
25230   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
25231     return SDValue();
25232
25233   EVT VT = N->getValueType(0);
25234   if (VT != MVT::i64 && VT != MVT::i32)
25235     return SDValue();
25236
25237   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
25238   if (!C)
25239     return SDValue();
25240   uint64_t MulAmt = C->getZExtValue();
25241   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
25242     return SDValue();
25243
25244   uint64_t MulAmt1 = 0;
25245   uint64_t MulAmt2 = 0;
25246   if ((MulAmt % 9) == 0) {
25247     MulAmt1 = 9;
25248     MulAmt2 = MulAmt / 9;
25249   } else if ((MulAmt % 5) == 0) {
25250     MulAmt1 = 5;
25251     MulAmt2 = MulAmt / 5;
25252   } else if ((MulAmt % 3) == 0) {
25253     MulAmt1 = 3;
25254     MulAmt2 = MulAmt / 3;
25255   }
25256
25257   SDLoc DL(N);
25258   SDValue NewMul;
25259   if (MulAmt2 &&
25260       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
25261
25262     if (isPowerOf2_64(MulAmt2) &&
25263         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
25264       // If second multiplifer is pow2, issue it first. We want the multiply by
25265       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
25266       // is an add.
25267       std::swap(MulAmt1, MulAmt2);
25268
25269     if (isPowerOf2_64(MulAmt1))
25270       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25271                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
25272     else
25273       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
25274                            DAG.getConstant(MulAmt1, DL, VT));
25275
25276     if (isPowerOf2_64(MulAmt2))
25277       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
25278                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
25279     else
25280       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
25281                            DAG.getConstant(MulAmt2, DL, VT));
25282   }
25283
25284   if (!NewMul) {
25285     assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
25286            && "Both cases that could cause potential overflows should have "
25287               "already been handled.");
25288     if (isPowerOf2_64(MulAmt - 1))
25289       // (mul x, 2^N + 1) => (add (shl x, N), x)
25290       NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
25291                                 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25292                                 DAG.getConstant(Log2_64(MulAmt - 1), DL,
25293                                 MVT::i8)));
25294
25295     else if (isPowerOf2_64(MulAmt + 1))
25296       // (mul x, 2^N - 1) => (sub (shl x, N), x)
25297       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
25298                                 N->getOperand(0),
25299                                 DAG.getConstant(Log2_64(MulAmt + 1),
25300                                 DL, MVT::i8)), N->getOperand(0));
25301   }
25302
25303   if (NewMul)
25304     // Do not add new nodes to DAG combiner worklist.
25305     DCI.CombineTo(N, NewMul, false);
25306
25307   return SDValue();
25308 }
25309
25310 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
25311   SDValue N0 = N->getOperand(0);
25312   SDValue N1 = N->getOperand(1);
25313   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
25314   EVT VT = N0.getValueType();
25315
25316   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
25317   // since the result of setcc_c is all zero's or all ones.
25318   if (VT.isInteger() && !VT.isVector() &&
25319       N1C && N0.getOpcode() == ISD::AND &&
25320       N0.getOperand(1).getOpcode() == ISD::Constant) {
25321     SDValue N00 = N0.getOperand(0);
25322     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
25323     APInt ShAmt = N1C->getAPIntValue();
25324     Mask = Mask.shl(ShAmt);
25325     bool MaskOK = false;
25326     // We can handle cases concerning bit-widening nodes containing setcc_c if
25327     // we carefully interrogate the mask to make sure we are semantics
25328     // preserving.
25329     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
25330     // of the underlying setcc_c operation if the setcc_c was zero extended.
25331     // Consider the following example:
25332     //   zext(setcc_c)                 -> i32 0x0000FFFF
25333     //   c1                            -> i32 0x0000FFFF
25334     //   c2                            -> i32 0x00000001
25335     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
25336     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
25337     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25338       MaskOK = true;
25339     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
25340                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25341       MaskOK = true;
25342     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
25343                 N00.getOpcode() == ISD::ANY_EXTEND) &&
25344                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25345       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
25346     }
25347     if (MaskOK && Mask != 0) {
25348       SDLoc DL(N);
25349       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
25350     }
25351   }
25352
25353   // Hardware support for vector shifts is sparse which makes us scalarize the
25354   // vector operations in many cases. Also, on sandybridge ADD is faster than
25355   // shl.
25356   // (shl V, 1) -> add V,V
25357   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
25358     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
25359       assert(N0.getValueType().isVector() && "Invalid vector shift type");
25360       // We shift all of the values by one. In many cases we do not have
25361       // hardware support for this operation. This is better expressed as an ADD
25362       // of two values.
25363       if (N1SplatC->getAPIntValue() == 1)
25364         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
25365     }
25366
25367   return SDValue();
25368 }
25369
25370 static SDValue PerformSRACombine(SDNode *N, SelectionDAG &DAG) {
25371   SDValue N0 = N->getOperand(0);
25372   SDValue N1 = N->getOperand(1);
25373   EVT VT = N0.getValueType();
25374   unsigned Size = VT.getSizeInBits();
25375
25376   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
25377   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
25378   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
25379   // depending on sign of (SarConst - [56,48,32,24,16])
25380
25381   // sexts in X86 are MOVs. The MOVs have the same code size
25382   // as above SHIFTs (only SHIFT on 1 has lower code size).
25383   // However the MOVs have 2 advantages to a SHIFT:
25384   // 1. MOVs can write to a register that differs from source
25385   // 2. MOVs accept memory operands
25386
25387   if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
25388       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
25389       N0.getOperand(1).getOpcode() != ISD::Constant)
25390     return SDValue();
25391
25392   SDValue N00 = N0.getOperand(0);
25393   SDValue N01 = N0.getOperand(1);
25394   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
25395   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
25396   EVT CVT = N1.getValueType();
25397
25398   if (SarConst.isNegative())
25399     return SDValue();
25400
25401   for (MVT SVT : MVT::integer_valuetypes()) {
25402     unsigned ShiftSize = SVT.getSizeInBits();
25403     // skipping types without corresponding sext/zext and
25404     // ShlConst that is not one of [56,48,32,24,16]
25405     if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
25406       continue;
25407     SDLoc DL(N);
25408     SDValue NN =
25409         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
25410     SarConst = SarConst - (Size - ShiftSize);
25411     if (SarConst == 0)
25412       return NN;
25413     else if (SarConst.isNegative())
25414       return DAG.getNode(ISD::SHL, DL, VT, NN,
25415                          DAG.getConstant(-SarConst, DL, CVT));
25416     else
25417       return DAG.getNode(ISD::SRA, DL, VT, NN,
25418                          DAG.getConstant(SarConst, DL, CVT));
25419   }
25420   return SDValue();
25421 }
25422
25423 /// \brief Returns a vector of 0s if the node in input is a vector logical
25424 /// shift by a constant amount which is known to be bigger than or equal
25425 /// to the vector element size in bits.
25426 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
25427                                       const X86Subtarget *Subtarget) {
25428   EVT VT = N->getValueType(0);
25429
25430   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
25431       (!Subtarget->hasInt256() ||
25432        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
25433     return SDValue();
25434
25435   SDValue Amt = N->getOperand(1);
25436   SDLoc DL(N);
25437   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
25438     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
25439       APInt ShiftAmt = AmtSplat->getAPIntValue();
25440       unsigned MaxAmount =
25441         VT.getSimpleVT().getVectorElementType().getSizeInBits();
25442
25443       // SSE2/AVX2 logical shifts always return a vector of 0s
25444       // if the shift amount is bigger than or equal to
25445       // the element size. The constant shift amount will be
25446       // encoded as a 8-bit immediate.
25447       if (ShiftAmt.trunc(8).uge(MaxAmount))
25448         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
25449     }
25450
25451   return SDValue();
25452 }
25453
25454 /// PerformShiftCombine - Combine shifts.
25455 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
25456                                    TargetLowering::DAGCombinerInfo &DCI,
25457                                    const X86Subtarget *Subtarget) {
25458   if (N->getOpcode() == ISD::SHL)
25459     if (SDValue V = PerformSHLCombine(N, DAG))
25460       return V;
25461
25462   if (N->getOpcode() == ISD::SRA)
25463     if (SDValue V = PerformSRACombine(N, DAG))
25464       return V;
25465
25466   // Try to fold this logical shift into a zero vector.
25467   if (N->getOpcode() != ISD::SRA)
25468     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
25469       return V;
25470
25471   return SDValue();
25472 }
25473
25474 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
25475 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
25476 // and friends.  Likewise for OR -> CMPNEQSS.
25477 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
25478                             TargetLowering::DAGCombinerInfo &DCI,
25479                             const X86Subtarget *Subtarget) {
25480   unsigned opcode;
25481
25482   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
25483   // we're requiring SSE2 for both.
25484   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
25485     SDValue N0 = N->getOperand(0);
25486     SDValue N1 = N->getOperand(1);
25487     SDValue CMP0 = N0->getOperand(1);
25488     SDValue CMP1 = N1->getOperand(1);
25489     SDLoc DL(N);
25490
25491     // The SETCCs should both refer to the same CMP.
25492     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
25493       return SDValue();
25494
25495     SDValue CMP00 = CMP0->getOperand(0);
25496     SDValue CMP01 = CMP0->getOperand(1);
25497     EVT     VT    = CMP00.getValueType();
25498
25499     if (VT == MVT::f32 || VT == MVT::f64) {
25500       bool ExpectingFlags = false;
25501       // Check for any users that want flags:
25502       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
25503            !ExpectingFlags && UI != UE; ++UI)
25504         switch (UI->getOpcode()) {
25505         default:
25506         case ISD::BR_CC:
25507         case ISD::BRCOND:
25508         case ISD::SELECT:
25509           ExpectingFlags = true;
25510           break;
25511         case ISD::CopyToReg:
25512         case ISD::SIGN_EXTEND:
25513         case ISD::ZERO_EXTEND:
25514         case ISD::ANY_EXTEND:
25515           break;
25516         }
25517
25518       if (!ExpectingFlags) {
25519         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
25520         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
25521
25522         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
25523           X86::CondCode tmp = cc0;
25524           cc0 = cc1;
25525           cc1 = tmp;
25526         }
25527
25528         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
25529             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
25530           // FIXME: need symbolic constants for these magic numbers.
25531           // See X86ATTInstPrinter.cpp:printSSECC().
25532           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
25533           if (Subtarget->hasAVX512()) {
25534             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
25535                                          CMP01,
25536                                          DAG.getConstant(x86cc, DL, MVT::i8));
25537             if (N->getValueType(0) != MVT::i1)
25538               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25539                                  FSetCC);
25540             return FSetCC;
25541           }
25542           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25543                                               CMP00.getValueType(), CMP00, CMP01,
25544                                               DAG.getConstant(x86cc, DL,
25545                                                               MVT::i8));
25546
25547           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25548           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25549
25550           if (is64BitFP && !Subtarget->is64Bit()) {
25551             // On a 32-bit target, we cannot bitcast the 64-bit float to a
25552             // 64-bit integer, since that's not a legal type. Since
25553             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25554             // bits, but can do this little dance to extract the lowest 32 bits
25555             // and work with those going forward.
25556             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25557                                            OnesOrZeroesF);
25558             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25559             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25560                                         Vector32, DAG.getIntPtrConstant(0, DL));
25561             IntVT = MVT::i32;
25562           }
25563
25564           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25565           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25566                                       DAG.getConstant(1, DL, IntVT));
25567           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25568                                               ANDed);
25569           return OneBitOfTruth;
25570         }
25571       }
25572     }
25573   }
25574   return SDValue();
25575 }
25576
25577 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25578 /// so it can be folded inside ANDNP.
25579 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25580   EVT VT = N->getValueType(0);
25581
25582   // Match direct AllOnes for 128 and 256-bit vectors
25583   if (ISD::isBuildVectorAllOnes(N))
25584     return true;
25585
25586   // Look through a bit convert.
25587   if (N->getOpcode() == ISD::BITCAST)
25588     N = N->getOperand(0).getNode();
25589
25590   // Sometimes the operand may come from a insert_subvector building a 256-bit
25591   // allones vector
25592   if (VT.is256BitVector() &&
25593       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25594     SDValue V1 = N->getOperand(0);
25595     SDValue V2 = N->getOperand(1);
25596
25597     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25598         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25599         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25600         ISD::isBuildVectorAllOnes(V2.getNode()))
25601       return true;
25602   }
25603
25604   return false;
25605 }
25606
25607 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25608 // register. In most cases we actually compare or select YMM-sized registers
25609 // and mixing the two types creates horrible code. This method optimizes
25610 // some of the transition sequences.
25611 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25612                                  TargetLowering::DAGCombinerInfo &DCI,
25613                                  const X86Subtarget *Subtarget) {
25614   EVT VT = N->getValueType(0);
25615   if (!VT.is256BitVector())
25616     return SDValue();
25617
25618   assert((N->getOpcode() == ISD::ANY_EXTEND ||
25619           N->getOpcode() == ISD::ZERO_EXTEND ||
25620           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25621
25622   SDValue Narrow = N->getOperand(0);
25623   EVT NarrowVT = Narrow->getValueType(0);
25624   if (!NarrowVT.is128BitVector())
25625     return SDValue();
25626
25627   if (Narrow->getOpcode() != ISD::XOR &&
25628       Narrow->getOpcode() != ISD::AND &&
25629       Narrow->getOpcode() != ISD::OR)
25630     return SDValue();
25631
25632   SDValue N0  = Narrow->getOperand(0);
25633   SDValue N1  = Narrow->getOperand(1);
25634   SDLoc DL(Narrow);
25635
25636   // The Left side has to be a trunc.
25637   if (N0.getOpcode() != ISD::TRUNCATE)
25638     return SDValue();
25639
25640   // The type of the truncated inputs.
25641   EVT WideVT = N0->getOperand(0)->getValueType(0);
25642   if (WideVT != VT)
25643     return SDValue();
25644
25645   // The right side has to be a 'trunc' or a constant vector.
25646   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25647   ConstantSDNode *RHSConstSplat = nullptr;
25648   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25649     RHSConstSplat = RHSBV->getConstantSplatNode();
25650   if (!RHSTrunc && !RHSConstSplat)
25651     return SDValue();
25652
25653   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25654
25655   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25656     return SDValue();
25657
25658   // Set N0 and N1 to hold the inputs to the new wide operation.
25659   N0 = N0->getOperand(0);
25660   if (RHSConstSplat) {
25661     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25662                      SDValue(RHSConstSplat, 0));
25663     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25664     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25665   } else if (RHSTrunc) {
25666     N1 = N1->getOperand(0);
25667   }
25668
25669   // Generate the wide operation.
25670   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25671   unsigned Opcode = N->getOpcode();
25672   switch (Opcode) {
25673   case ISD::ANY_EXTEND:
25674     return Op;
25675   case ISD::ZERO_EXTEND: {
25676     unsigned InBits = NarrowVT.getScalarSizeInBits();
25677     APInt Mask = APInt::getAllOnesValue(InBits);
25678     Mask = Mask.zext(VT.getScalarSizeInBits());
25679     return DAG.getNode(ISD::AND, DL, VT,
25680                        Op, DAG.getConstant(Mask, DL, VT));
25681   }
25682   case ISD::SIGN_EXTEND:
25683     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25684                        Op, DAG.getValueType(NarrowVT));
25685   default:
25686     llvm_unreachable("Unexpected opcode");
25687   }
25688 }
25689
25690 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25691                                  TargetLowering::DAGCombinerInfo &DCI,
25692                                  const X86Subtarget *Subtarget) {
25693   SDValue N0 = N->getOperand(0);
25694   SDValue N1 = N->getOperand(1);
25695   SDLoc DL(N);
25696
25697   // A vector zext_in_reg may be represented as a shuffle,
25698   // feeding into a bitcast (this represents anyext) feeding into
25699   // an and with a mask.
25700   // We'd like to try to combine that into a shuffle with zero
25701   // plus a bitcast, removing the and.
25702   if (N0.getOpcode() != ISD::BITCAST ||
25703       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25704     return SDValue();
25705
25706   // The other side of the AND should be a splat of 2^C, where C
25707   // is the number of bits in the source type.
25708   if (N1.getOpcode() == ISD::BITCAST)
25709     N1 = N1.getOperand(0);
25710   if (N1.getOpcode() != ISD::BUILD_VECTOR)
25711     return SDValue();
25712   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25713
25714   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25715   EVT SrcType = Shuffle->getValueType(0);
25716
25717   // We expect a single-source shuffle
25718   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25719     return SDValue();
25720
25721   unsigned SrcSize = SrcType.getScalarSizeInBits();
25722
25723   APInt SplatValue, SplatUndef;
25724   unsigned SplatBitSize;
25725   bool HasAnyUndefs;
25726   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25727                                 SplatBitSize, HasAnyUndefs))
25728     return SDValue();
25729
25730   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25731   // Make sure the splat matches the mask we expect
25732   if (SplatBitSize > ResSize ||
25733       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25734     return SDValue();
25735
25736   // Make sure the input and output size make sense
25737   if (SrcSize >= ResSize || ResSize % SrcSize)
25738     return SDValue();
25739
25740   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25741   // The number of u's between each two values depends on the ratio between
25742   // the source and dest type.
25743   unsigned ZextRatio = ResSize / SrcSize;
25744   bool IsZext = true;
25745   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25746     if (i % ZextRatio) {
25747       if (Shuffle->getMaskElt(i) > 0) {
25748         // Expected undef
25749         IsZext = false;
25750         break;
25751       }
25752     } else {
25753       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25754         // Expected element number
25755         IsZext = false;
25756         break;
25757       }
25758     }
25759   }
25760
25761   if (!IsZext)
25762     return SDValue();
25763
25764   // Ok, perform the transformation - replace the shuffle with
25765   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25766   // (instead of undef) where the k elements come from the zero vector.
25767   SmallVector<int, 8> Mask;
25768   unsigned NumElems = SrcType.getVectorNumElements();
25769   for (unsigned i = 0; i < NumElems; ++i)
25770     if (i % ZextRatio)
25771       Mask.push_back(NumElems);
25772     else
25773       Mask.push_back(i / ZextRatio);
25774
25775   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25776     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25777   return DAG.getBitcast(N0.getValueType(), NewShuffle);
25778 }
25779
25780 /// If both input operands of a logic op are being cast from floating point
25781 /// types, try to convert this into a floating point logic node to avoid
25782 /// unnecessary moves from SSE to integer registers.
25783 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25784                                         const X86Subtarget *Subtarget) {
25785   unsigned FPOpcode = ISD::DELETED_NODE;
25786   if (N->getOpcode() == ISD::AND)
25787     FPOpcode = X86ISD::FAND;
25788   else if (N->getOpcode() == ISD::OR)
25789     FPOpcode = X86ISD::FOR;
25790   else if (N->getOpcode() == ISD::XOR)
25791     FPOpcode = X86ISD::FXOR;
25792
25793   assert(FPOpcode != ISD::DELETED_NODE &&
25794          "Unexpected input node for FP logic conversion");
25795
25796   EVT VT = N->getValueType(0);
25797   SDValue N0 = N->getOperand(0);
25798   SDValue N1 = N->getOperand(1);
25799   SDLoc DL(N);
25800   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25801       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25802        (Subtarget->hasSSE2() && VT == MVT::i64))) {
25803     SDValue N00 = N0.getOperand(0);
25804     SDValue N10 = N1.getOperand(0);
25805     EVT N00Type = N00.getValueType();
25806     EVT N10Type = N10.getValueType();
25807     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25808       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25809       return DAG.getBitcast(VT, FPLogic);
25810     }
25811   }
25812   return SDValue();
25813 }
25814
25815 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25816                                  TargetLowering::DAGCombinerInfo &DCI,
25817                                  const X86Subtarget *Subtarget) {
25818   if (DCI.isBeforeLegalizeOps())
25819     return SDValue();
25820
25821   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25822     return Zext;
25823
25824   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25825     return R;
25826
25827   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25828     return FPLogic;
25829
25830   EVT VT = N->getValueType(0);
25831   SDValue N0 = N->getOperand(0);
25832   SDValue N1 = N->getOperand(1);
25833   SDLoc DL(N);
25834
25835   // Create BEXTR instructions
25836   // BEXTR is ((X >> imm) & (2**size-1))
25837   if (VT == MVT::i32 || VT == MVT::i64) {
25838     // Check for BEXTR.
25839     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25840         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25841       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25842       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25843       if (MaskNode && ShiftNode) {
25844         uint64_t Mask = MaskNode->getZExtValue();
25845         uint64_t Shift = ShiftNode->getZExtValue();
25846         if (isMask_64(Mask)) {
25847           uint64_t MaskSize = countPopulation(Mask);
25848           if (Shift + MaskSize <= VT.getSizeInBits())
25849             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25850                                DAG.getConstant(Shift | (MaskSize << 8), DL,
25851                                                VT));
25852         }
25853       }
25854     } // BEXTR
25855
25856     return SDValue();
25857   }
25858
25859   // Want to form ANDNP nodes:
25860   // 1) In the hopes of then easily combining them with OR and AND nodes
25861   //    to form PBLEND/PSIGN.
25862   // 2) To match ANDN packed intrinsics
25863   if (VT != MVT::v2i64 && VT != MVT::v4i64)
25864     return SDValue();
25865
25866   // Check LHS for vnot
25867   if (N0.getOpcode() == ISD::XOR &&
25868       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25869       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25870     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25871
25872   // Check RHS for vnot
25873   if (N1.getOpcode() == ISD::XOR &&
25874       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25875       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25876     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25877
25878   return SDValue();
25879 }
25880
25881 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25882                                 TargetLowering::DAGCombinerInfo &DCI,
25883                                 const X86Subtarget *Subtarget) {
25884   if (DCI.isBeforeLegalizeOps())
25885     return SDValue();
25886
25887   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25888     return R;
25889
25890   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25891     return FPLogic;
25892
25893   SDValue N0 = N->getOperand(0);
25894   SDValue N1 = N->getOperand(1);
25895   EVT VT = N->getValueType(0);
25896
25897   // look for psign/blend
25898   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25899     if (!Subtarget->hasSSSE3() ||
25900         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25901       return SDValue();
25902
25903     // Canonicalize pandn to RHS
25904     if (N0.getOpcode() == X86ISD::ANDNP)
25905       std::swap(N0, N1);
25906     // or (and (m, y), (pandn m, x))
25907     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25908       SDValue Mask = N1.getOperand(0);
25909       SDValue X    = N1.getOperand(1);
25910       SDValue Y;
25911       if (N0.getOperand(0) == Mask)
25912         Y = N0.getOperand(1);
25913       if (N0.getOperand(1) == Mask)
25914         Y = N0.getOperand(0);
25915
25916       // Check to see if the mask appeared in both the AND and ANDNP and
25917       if (!Y.getNode())
25918         return SDValue();
25919
25920       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25921       // Look through mask bitcast.
25922       if (Mask.getOpcode() == ISD::BITCAST)
25923         Mask = Mask.getOperand(0);
25924       if (X.getOpcode() == ISD::BITCAST)
25925         X = X.getOperand(0);
25926       if (Y.getOpcode() == ISD::BITCAST)
25927         Y = Y.getOperand(0);
25928
25929       EVT MaskVT = Mask.getValueType();
25930
25931       // Validate that the Mask operand is a vector sra node.
25932       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25933       // there is no psrai.b
25934       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25935       unsigned SraAmt = ~0;
25936       if (Mask.getOpcode() == ISD::SRA) {
25937         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25938           if (auto *AmtConst = AmtBV->getConstantSplatNode())
25939             SraAmt = AmtConst->getZExtValue();
25940       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25941         SDValue SraC = Mask.getOperand(1);
25942         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
25943       }
25944       if ((SraAmt + 1) != EltBits)
25945         return SDValue();
25946
25947       SDLoc DL(N);
25948
25949       // Now we know we at least have a plendvb with the mask val.  See if
25950       // we can form a psignb/w/d.
25951       // psign = x.type == y.type == mask.type && y = sub(0, x);
25952       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25953           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25954           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25955         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25956                "Unsupported VT for PSIGN");
25957         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25958         return DAG.getBitcast(VT, Mask);
25959       }
25960       // PBLENDVB only available on SSE 4.1
25961       if (!Subtarget->hasSSE41())
25962         return SDValue();
25963
25964       MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25965
25966       X = DAG.getBitcast(BlendVT, X);
25967       Y = DAG.getBitcast(BlendVT, Y);
25968       Mask = DAG.getBitcast(BlendVT, Mask);
25969       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25970       return DAG.getBitcast(VT, Mask);
25971     }
25972   }
25973
25974   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25975     return SDValue();
25976
25977   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25978   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25979
25980   // SHLD/SHRD instructions have lower register pressure, but on some
25981   // platforms they have higher latency than the equivalent
25982   // series of shifts/or that would otherwise be generated.
25983   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25984   // have higher latencies and we are not optimizing for size.
25985   if (!OptForSize && Subtarget->isSHLDSlow())
25986     return SDValue();
25987
25988   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25989     std::swap(N0, N1);
25990   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25991     return SDValue();
25992   if (!N0.hasOneUse() || !N1.hasOneUse())
25993     return SDValue();
25994
25995   SDValue ShAmt0 = N0.getOperand(1);
25996   if (ShAmt0.getValueType() != MVT::i8)
25997     return SDValue();
25998   SDValue ShAmt1 = N1.getOperand(1);
25999   if (ShAmt1.getValueType() != MVT::i8)
26000     return SDValue();
26001   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
26002     ShAmt0 = ShAmt0.getOperand(0);
26003   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
26004     ShAmt1 = ShAmt1.getOperand(0);
26005
26006   SDLoc DL(N);
26007   unsigned Opc = X86ISD::SHLD;
26008   SDValue Op0 = N0.getOperand(0);
26009   SDValue Op1 = N1.getOperand(0);
26010   if (ShAmt0.getOpcode() == ISD::SUB) {
26011     Opc = X86ISD::SHRD;
26012     std::swap(Op0, Op1);
26013     std::swap(ShAmt0, ShAmt1);
26014   }
26015
26016   unsigned Bits = VT.getSizeInBits();
26017   if (ShAmt1.getOpcode() == ISD::SUB) {
26018     SDValue Sum = ShAmt1.getOperand(0);
26019     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
26020       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
26021       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
26022         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
26023       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
26024         return DAG.getNode(Opc, DL, VT,
26025                            Op0, Op1,
26026                            DAG.getNode(ISD::TRUNCATE, DL,
26027                                        MVT::i8, ShAmt0));
26028     }
26029   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
26030     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
26031     if (ShAmt0C &&
26032         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
26033       return DAG.getNode(Opc, DL, VT,
26034                          N0.getOperand(0), N1.getOperand(0),
26035                          DAG.getNode(ISD::TRUNCATE, DL,
26036                                        MVT::i8, ShAmt0));
26037   }
26038
26039   return SDValue();
26040 }
26041
26042 // Generate NEG and CMOV for integer abs.
26043 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
26044   EVT VT = N->getValueType(0);
26045
26046   // Since X86 does not have CMOV for 8-bit integer, we don't convert
26047   // 8-bit integer abs to NEG and CMOV.
26048   if (VT.isInteger() && VT.getSizeInBits() == 8)
26049     return SDValue();
26050
26051   SDValue N0 = N->getOperand(0);
26052   SDValue N1 = N->getOperand(1);
26053   SDLoc DL(N);
26054
26055   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
26056   // and change it to SUB and CMOV.
26057   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
26058       N0.getOpcode() == ISD::ADD &&
26059       N0.getOperand(1) == N1 &&
26060       N1.getOpcode() == ISD::SRA &&
26061       N1.getOperand(0) == N0.getOperand(0))
26062     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
26063       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
26064         // Generate SUB & CMOV.
26065         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
26066                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
26067
26068         SDValue Ops[] = { N0.getOperand(0), Neg,
26069                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
26070                           SDValue(Neg.getNode(), 1) };
26071         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
26072       }
26073   return SDValue();
26074 }
26075
26076 // Try to turn tests against the signbit in the form of:
26077 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
26078 // into:
26079 //   SETGT(X, -1)
26080 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
26081   // This is only worth doing if the output type is i8.
26082   if (N->getValueType(0) != MVT::i8)
26083     return SDValue();
26084
26085   SDValue N0 = N->getOperand(0);
26086   SDValue N1 = N->getOperand(1);
26087
26088   // We should be performing an xor against a truncated shift.
26089   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
26090     return SDValue();
26091
26092   // Make sure we are performing an xor against one.
26093   if (!isOneConstant(N1))
26094     return SDValue();
26095
26096   // SetCC on x86 zero extends so only act on this if it's a logical shift.
26097   SDValue Shift = N0.getOperand(0);
26098   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
26099     return SDValue();
26100
26101   // Make sure we are truncating from one of i16, i32 or i64.
26102   EVT ShiftTy = Shift.getValueType();
26103   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
26104     return SDValue();
26105
26106   // Make sure the shift amount extracts the sign bit.
26107   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
26108       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
26109     return SDValue();
26110
26111   // Create a greater-than comparison against -1.
26112   // N.B. Using SETGE against 0 works but we want a canonical looking
26113   // comparison, using SETGT matches up with what TranslateX86CC.
26114   SDLoc DL(N);
26115   SDValue ShiftOp = Shift.getOperand(0);
26116   EVT ShiftOpTy = ShiftOp.getValueType();
26117   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
26118                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
26119   return Cond;
26120 }
26121
26122 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
26123                                  TargetLowering::DAGCombinerInfo &DCI,
26124                                  const X86Subtarget *Subtarget) {
26125   if (DCI.isBeforeLegalizeOps())
26126     return SDValue();
26127
26128   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
26129     return RV;
26130
26131   if (Subtarget->hasCMov())
26132     if (SDValue RV = performIntegerAbsCombine(N, DAG))
26133       return RV;
26134
26135   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
26136     return FPLogic;
26137
26138   return SDValue();
26139 }
26140
26141 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
26142 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
26143 /// X86ISD::AVG instruction.
26144 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
26145                                 const X86Subtarget *Subtarget, SDLoc DL) {
26146   if (!VT.isVector() || !VT.isSimple())
26147     return SDValue();
26148   EVT InVT = In.getValueType();
26149   unsigned NumElems = VT.getVectorNumElements();
26150
26151   EVT ScalarVT = VT.getVectorElementType();
26152   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
26153         isPowerOf2_32(NumElems)))
26154     return SDValue();
26155
26156   // InScalarVT is the intermediate type in AVG pattern and it should be greater
26157   // than the original input type (i8/i16).
26158   EVT InScalarVT = InVT.getVectorElementType();
26159   if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
26160     return SDValue();
26161
26162   if (Subtarget->hasAVX512()) {
26163     if (VT.getSizeInBits() > 512)
26164       return SDValue();
26165   } else if (Subtarget->hasAVX2()) {
26166     if (VT.getSizeInBits() > 256)
26167       return SDValue();
26168   } else {
26169     if (VT.getSizeInBits() > 128)
26170       return SDValue();
26171   }
26172
26173   // Detect the following pattern:
26174   //
26175   //   %1 = zext <N x i8> %a to <N x i32>
26176   //   %2 = zext <N x i8> %b to <N x i32>
26177   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
26178   //   %4 = add nuw nsw <N x i32> %3, %2
26179   //   %5 = lshr <N x i32> %N, <i32 1 x N>
26180   //   %6 = trunc <N x i32> %5 to <N x i8>
26181   //
26182   // In AVX512, the last instruction can also be a trunc store.
26183
26184   if (In.getOpcode() != ISD::SRL)
26185     return SDValue();
26186
26187   // A lambda checking the given SDValue is a constant vector and each element
26188   // is in the range [Min, Max].
26189   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
26190     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
26191     if (!BV || !BV->isConstant())
26192       return false;
26193     for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
26194       ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
26195       if (!C)
26196         return false;
26197       uint64_t Val = C->getZExtValue();
26198       if (Val < Min || Val > Max)
26199         return false;
26200     }
26201     return true;
26202   };
26203
26204   // Check if each element of the vector is left-shifted by one.
26205   auto LHS = In.getOperand(0);
26206   auto RHS = In.getOperand(1);
26207   if (!IsConstVectorInRange(RHS, 1, 1))
26208     return SDValue();
26209   if (LHS.getOpcode() != ISD::ADD)
26210     return SDValue();
26211
26212   // Detect a pattern of a + b + 1 where the order doesn't matter.
26213   SDValue Operands[3];
26214   Operands[0] = LHS.getOperand(0);
26215   Operands[1] = LHS.getOperand(1);
26216
26217   // Take care of the case when one of the operands is a constant vector whose
26218   // element is in the range [1, 256].
26219   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
26220       Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
26221       Operands[0].getOperand(0).getValueType() == VT) {
26222     // The pattern is detected. Subtract one from the constant vector, then
26223     // demote it and emit X86ISD::AVG instruction.
26224     SDValue One = DAG.getConstant(1, DL, InScalarVT);
26225     SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
26226                                SmallVector<SDValue, 8>(NumElems, One));
26227     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
26228     Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
26229     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26230                        Operands[1]);
26231   }
26232
26233   if (Operands[0].getOpcode() == ISD::ADD)
26234     std::swap(Operands[0], Operands[1]);
26235   else if (Operands[1].getOpcode() != ISD::ADD)
26236     return SDValue();
26237   Operands[2] = Operands[1].getOperand(0);
26238   Operands[1] = Operands[1].getOperand(1);
26239
26240   // Now we have three operands of two additions. Check that one of them is a
26241   // constant vector with ones, and the other two are promoted from i8/i16.
26242   for (int i = 0; i < 3; ++i) {
26243     if (!IsConstVectorInRange(Operands[i], 1, 1))
26244       continue;
26245     std::swap(Operands[i], Operands[2]);
26246
26247     // Check if Operands[0] and Operands[1] are results of type promotion.
26248     for (int j = 0; j < 2; ++j)
26249       if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
26250           Operands[j].getOperand(0).getValueType() != VT)
26251         return SDValue();
26252
26253     // The pattern is detected, emit X86ISD::AVG instruction.
26254     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26255                        Operands[1].getOperand(0));
26256   }
26257
26258   return SDValue();
26259 }
26260
26261 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
26262 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
26263                                   TargetLowering::DAGCombinerInfo &DCI,
26264                                   const X86Subtarget *Subtarget) {
26265   LoadSDNode *Ld = cast<LoadSDNode>(N);
26266   EVT RegVT = Ld->getValueType(0);
26267   EVT MemVT = Ld->getMemoryVT();
26268   SDLoc dl(Ld);
26269   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26270
26271   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
26272   // into two 16-byte operations.
26273   ISD::LoadExtType Ext = Ld->getExtensionType();
26274   bool Fast;
26275   unsigned AddressSpace = Ld->getAddressSpace();
26276   unsigned Alignment = Ld->getAlignment();
26277   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
26278       Ext == ISD::NON_EXTLOAD &&
26279       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
26280                              AddressSpace, Alignment, &Fast) && !Fast) {
26281     unsigned NumElems = RegVT.getVectorNumElements();
26282     if (NumElems < 2)
26283       return SDValue();
26284
26285     SDValue Ptr = Ld->getBasePtr();
26286     SDValue Increment =
26287         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26288
26289     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
26290                                   NumElems/2);
26291     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26292                                 Ld->getPointerInfo(), Ld->isVolatile(),
26293                                 Ld->isNonTemporal(), Ld->isInvariant(),
26294                                 Alignment);
26295     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26296     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26297                                 Ld->getPointerInfo(), Ld->isVolatile(),
26298                                 Ld->isNonTemporal(), Ld->isInvariant(),
26299                                 std::min(16U, Alignment));
26300     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
26301                              Load1.getValue(1),
26302                              Load2.getValue(1));
26303
26304     SDValue NewVec = DAG.getUNDEF(RegVT);
26305     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
26306     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
26307     return DCI.CombineTo(N, NewVec, TF, true);
26308   }
26309
26310   return SDValue();
26311 }
26312
26313 /// PerformMLOADCombine - Resolve extending loads
26314 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
26315                                    TargetLowering::DAGCombinerInfo &DCI,
26316                                    const X86Subtarget *Subtarget) {
26317   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
26318   if (Mld->getExtensionType() != ISD::SEXTLOAD)
26319     return SDValue();
26320
26321   EVT VT = Mld->getValueType(0);
26322   unsigned NumElems = VT.getVectorNumElements();
26323   EVT LdVT = Mld->getMemoryVT();
26324   SDLoc dl(Mld);
26325
26326   assert(LdVT != VT && "Cannot extend to the same type");
26327   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
26328   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
26329   // From, To sizes and ElemCount must be pow of two
26330   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26331     "Unexpected size for extending masked load");
26332
26333   unsigned SizeRatio  = ToSz / FromSz;
26334   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
26335
26336   // Create a type on which we perform the shuffle
26337   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26338           LdVT.getScalarType(), NumElems*SizeRatio);
26339   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26340
26341   // Convert Src0 value
26342   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
26343   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
26344     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26345     for (unsigned i = 0; i != NumElems; ++i)
26346       ShuffleVec[i] = i * SizeRatio;
26347
26348     // Can't shuffle using an illegal type.
26349     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26350            "WideVecVT should be legal");
26351     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
26352                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
26353   }
26354   // Prepare the new mask
26355   SDValue NewMask;
26356   SDValue Mask = Mld->getMask();
26357   if (Mask.getValueType() == VT) {
26358     // Mask and original value have the same type
26359     NewMask = DAG.getBitcast(WideVecVT, Mask);
26360     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26361     for (unsigned i = 0; i != NumElems; ++i)
26362       ShuffleVec[i] = i * SizeRatio;
26363     for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
26364       ShuffleVec[i] = NumElems * SizeRatio;
26365     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26366                                    DAG.getConstant(0, dl, WideVecVT),
26367                                    &ShuffleVec[0]);
26368   }
26369   else {
26370     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26371     unsigned WidenNumElts = NumElems*SizeRatio;
26372     unsigned MaskNumElts = VT.getVectorNumElements();
26373     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26374                                      WidenNumElts);
26375
26376     unsigned NumConcat = WidenNumElts / MaskNumElts;
26377     SmallVector<SDValue, 16> Ops(NumConcat);
26378     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26379     Ops[0] = Mask;
26380     for (unsigned i = 1; i != NumConcat; ++i)
26381       Ops[i] = ZeroVal;
26382
26383     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26384   }
26385
26386   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
26387                                      Mld->getBasePtr(), NewMask, WideSrc0,
26388                                      Mld->getMemoryVT(), Mld->getMemOperand(),
26389                                      ISD::NON_EXTLOAD);
26390   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
26391   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
26392 }
26393 /// PerformMSTORECombine - Resolve truncating stores
26394 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
26395                                     const X86Subtarget *Subtarget) {
26396   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
26397   if (!Mst->isTruncatingStore())
26398     return SDValue();
26399
26400   EVT VT = Mst->getValue().getValueType();
26401   unsigned NumElems = VT.getVectorNumElements();
26402   EVT StVT = Mst->getMemoryVT();
26403   SDLoc dl(Mst);
26404
26405   assert(StVT != VT && "Cannot truncate to the same type");
26406   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26407   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26408
26409   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26410
26411   // The truncating store is legal in some cases. For example
26412   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26413   // are designated for truncate store.
26414   // In this case we don't need any further transformations.
26415   if (TLI.isTruncStoreLegal(VT, StVT))
26416     return SDValue();
26417
26418   // From, To sizes and ElemCount must be pow of two
26419   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26420     "Unexpected size for truncating masked store");
26421   // We are going to use the original vector elt for storing.
26422   // Accumulated smaller vector elements must be a multiple of the store size.
26423   assert (((NumElems * FromSz) % ToSz) == 0 &&
26424           "Unexpected ratio for truncating masked store");
26425
26426   unsigned SizeRatio  = FromSz / ToSz;
26427   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26428
26429   // Create a type on which we perform the shuffle
26430   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26431           StVT.getScalarType(), NumElems*SizeRatio);
26432
26433   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26434
26435   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
26436   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26437   for (unsigned i = 0; i != NumElems; ++i)
26438     ShuffleVec[i] = i * SizeRatio;
26439
26440   // Can't shuffle using an illegal type.
26441   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26442          "WideVecVT should be legal");
26443
26444   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26445                                               DAG.getUNDEF(WideVecVT),
26446                                               &ShuffleVec[0]);
26447
26448   SDValue NewMask;
26449   SDValue Mask = Mst->getMask();
26450   if (Mask.getValueType() == VT) {
26451     // Mask and original value have the same type
26452     NewMask = DAG.getBitcast(WideVecVT, Mask);
26453     for (unsigned i = 0; i != NumElems; ++i)
26454       ShuffleVec[i] = i * SizeRatio;
26455     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
26456       ShuffleVec[i] = NumElems*SizeRatio;
26457     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26458                                    DAG.getConstant(0, dl, WideVecVT),
26459                                    &ShuffleVec[0]);
26460   }
26461   else {
26462     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26463     unsigned WidenNumElts = NumElems*SizeRatio;
26464     unsigned MaskNumElts = VT.getVectorNumElements();
26465     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26466                                      WidenNumElts);
26467
26468     unsigned NumConcat = WidenNumElts / MaskNumElts;
26469     SmallVector<SDValue, 16> Ops(NumConcat);
26470     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26471     Ops[0] = Mask;
26472     for (unsigned i = 1; i != NumConcat; ++i)
26473       Ops[i] = ZeroVal;
26474
26475     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26476   }
26477
26478   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
26479                             Mst->getBasePtr(), NewMask, StVT,
26480                             Mst->getMemOperand(), false);
26481 }
26482 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
26483 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
26484                                    const X86Subtarget *Subtarget) {
26485   StoreSDNode *St = cast<StoreSDNode>(N);
26486   EVT VT = St->getValue().getValueType();
26487   EVT StVT = St->getMemoryVT();
26488   SDLoc dl(St);
26489   SDValue StoredVal = St->getOperand(1);
26490   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26491
26492   // If we are saving a concatenation of two XMM registers and 32-byte stores
26493   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
26494   bool Fast;
26495   unsigned AddressSpace = St->getAddressSpace();
26496   unsigned Alignment = St->getAlignment();
26497   if (VT.is256BitVector() && StVT == VT &&
26498       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
26499                              AddressSpace, Alignment, &Fast) && !Fast) {
26500     unsigned NumElems = VT.getVectorNumElements();
26501     if (NumElems < 2)
26502       return SDValue();
26503
26504     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
26505     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
26506
26507     SDValue Stride =
26508         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26509     SDValue Ptr0 = St->getBasePtr();
26510     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
26511
26512     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
26513                                 St->getPointerInfo(), St->isVolatile(),
26514                                 St->isNonTemporal(), Alignment);
26515     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
26516                                 St->getPointerInfo(), St->isVolatile(),
26517                                 St->isNonTemporal(),
26518                                 std::min(16U, Alignment));
26519     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
26520   }
26521
26522   // Optimize trunc store (of multiple scalars) to shuffle and store.
26523   // First, pack all of the elements in one place. Next, store to memory
26524   // in fewer chunks.
26525   if (St->isTruncatingStore() && VT.isVector()) {
26526     // Check if we can detect an AVG pattern from the truncation. If yes,
26527     // replace the trunc store by a normal store with the result of X86ISD::AVG
26528     // instruction.
26529     SDValue Avg =
26530         detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
26531     if (Avg.getNode())
26532       return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
26533                           St->getPointerInfo(), St->isVolatile(),
26534                           St->isNonTemporal(), St->getAlignment());
26535
26536     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26537     unsigned NumElems = VT.getVectorNumElements();
26538     assert(StVT != VT && "Cannot truncate to the same type");
26539     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26540     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26541
26542     // The truncating store is legal in some cases. For example
26543     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26544     // are designated for truncate store.
26545     // In this case we don't need any further transformations.
26546     if (TLI.isTruncStoreLegal(VT, StVT))
26547       return SDValue();
26548
26549     // From, To sizes and ElemCount must be pow of two
26550     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26551     // We are going to use the original vector elt for storing.
26552     // Accumulated smaller vector elements must be a multiple of the store size.
26553     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26554
26555     unsigned SizeRatio  = FromSz / ToSz;
26556
26557     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26558
26559     // Create a type on which we perform the shuffle
26560     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26561             StVT.getScalarType(), NumElems*SizeRatio);
26562
26563     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26564
26565     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26566     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26567     for (unsigned i = 0; i != NumElems; ++i)
26568       ShuffleVec[i] = i * SizeRatio;
26569
26570     // Can't shuffle using an illegal type.
26571     if (!TLI.isTypeLegal(WideVecVT))
26572       return SDValue();
26573
26574     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26575                                          DAG.getUNDEF(WideVecVT),
26576                                          &ShuffleVec[0]);
26577     // At this point all of the data is stored at the bottom of the
26578     // register. We now need to save it to mem.
26579
26580     // Find the largest store unit
26581     MVT StoreType = MVT::i8;
26582     for (MVT Tp : MVT::integer_valuetypes()) {
26583       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26584         StoreType = Tp;
26585     }
26586
26587     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26588     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26589         (64 <= NumElems * ToSz))
26590       StoreType = MVT::f64;
26591
26592     // Bitcast the original vector into a vector of store-size units
26593     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26594             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26595     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26596     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26597     SmallVector<SDValue, 8> Chains;
26598     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26599                                         TLI.getPointerTy(DAG.getDataLayout()));
26600     SDValue Ptr = St->getBasePtr();
26601
26602     // Perform one or more big stores into memory.
26603     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26604       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26605                                    StoreType, ShuffWide,
26606                                    DAG.getIntPtrConstant(i, dl));
26607       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26608                                 St->getPointerInfo(), St->isVolatile(),
26609                                 St->isNonTemporal(), St->getAlignment());
26610       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26611       Chains.push_back(Ch);
26612     }
26613
26614     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26615   }
26616
26617   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
26618   // the FP state in cases where an emms may be missing.
26619   // A preferable solution to the general problem is to figure out the right
26620   // places to insert EMMS.  This qualifies as a quick hack.
26621
26622   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26623   if (VT.getSizeInBits() != 64)
26624     return SDValue();
26625
26626   const Function *F = DAG.getMachineFunction().getFunction();
26627   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26628   bool F64IsLegal =
26629       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26630   if ((VT.isVector() ||
26631        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26632       isa<LoadSDNode>(St->getValue()) &&
26633       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26634       St->getChain().hasOneUse() && !St->isVolatile()) {
26635     SDNode* LdVal = St->getValue().getNode();
26636     LoadSDNode *Ld = nullptr;
26637     int TokenFactorIndex = -1;
26638     SmallVector<SDValue, 8> Ops;
26639     SDNode* ChainVal = St->getChain().getNode();
26640     // Must be a store of a load.  We currently handle two cases:  the load
26641     // is a direct child, and it's under an intervening TokenFactor.  It is
26642     // possible to dig deeper under nested TokenFactors.
26643     if (ChainVal == LdVal)
26644       Ld = cast<LoadSDNode>(St->getChain());
26645     else if (St->getValue().hasOneUse() &&
26646              ChainVal->getOpcode() == ISD::TokenFactor) {
26647       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26648         if (ChainVal->getOperand(i).getNode() == LdVal) {
26649           TokenFactorIndex = i;
26650           Ld = cast<LoadSDNode>(St->getValue());
26651         } else
26652           Ops.push_back(ChainVal->getOperand(i));
26653       }
26654     }
26655
26656     if (!Ld || !ISD::isNormalLoad(Ld))
26657       return SDValue();
26658
26659     // If this is not the MMX case, i.e. we are just turning i64 load/store
26660     // into f64 load/store, avoid the transformation if there are multiple
26661     // uses of the loaded value.
26662     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26663       return SDValue();
26664
26665     SDLoc LdDL(Ld);
26666     SDLoc StDL(N);
26667     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26668     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26669     // pair instead.
26670     if (Subtarget->is64Bit() || F64IsLegal) {
26671       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26672       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26673                                   Ld->getPointerInfo(), Ld->isVolatile(),
26674                                   Ld->isNonTemporal(), Ld->isInvariant(),
26675                                   Ld->getAlignment());
26676       SDValue NewChain = NewLd.getValue(1);
26677       if (TokenFactorIndex != -1) {
26678         Ops.push_back(NewChain);
26679         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26680       }
26681       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26682                           St->getPointerInfo(),
26683                           St->isVolatile(), St->isNonTemporal(),
26684                           St->getAlignment());
26685     }
26686
26687     // Otherwise, lower to two pairs of 32-bit loads / stores.
26688     SDValue LoAddr = Ld->getBasePtr();
26689     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26690                                  DAG.getConstant(4, LdDL, MVT::i32));
26691
26692     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26693                                Ld->getPointerInfo(),
26694                                Ld->isVolatile(), Ld->isNonTemporal(),
26695                                Ld->isInvariant(), Ld->getAlignment());
26696     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26697                                Ld->getPointerInfo().getWithOffset(4),
26698                                Ld->isVolatile(), Ld->isNonTemporal(),
26699                                Ld->isInvariant(),
26700                                MinAlign(Ld->getAlignment(), 4));
26701
26702     SDValue NewChain = LoLd.getValue(1);
26703     if (TokenFactorIndex != -1) {
26704       Ops.push_back(LoLd);
26705       Ops.push_back(HiLd);
26706       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26707     }
26708
26709     LoAddr = St->getBasePtr();
26710     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26711                          DAG.getConstant(4, StDL, MVT::i32));
26712
26713     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26714                                 St->getPointerInfo(),
26715                                 St->isVolatile(), St->isNonTemporal(),
26716                                 St->getAlignment());
26717     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26718                                 St->getPointerInfo().getWithOffset(4),
26719                                 St->isVolatile(),
26720                                 St->isNonTemporal(),
26721                                 MinAlign(St->getAlignment(), 4));
26722     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26723   }
26724
26725   // This is similar to the above case, but here we handle a scalar 64-bit
26726   // integer store that is extracted from a vector on a 32-bit target.
26727   // If we have SSE2, then we can treat it like a floating-point double
26728   // to get past legalization. The execution dependencies fixup pass will
26729   // choose the optimal machine instruction for the store if this really is
26730   // an integer or v2f32 rather than an f64.
26731   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26732       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26733     SDValue OldExtract = St->getOperand(1);
26734     SDValue ExtOp0 = OldExtract.getOperand(0);
26735     unsigned VecSize = ExtOp0.getValueSizeInBits();
26736     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26737     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26738     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26739                                      BitCast, OldExtract.getOperand(1));
26740     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26741                         St->getPointerInfo(), St->isVolatile(),
26742                         St->isNonTemporal(), St->getAlignment());
26743   }
26744
26745   return SDValue();
26746 }
26747
26748 /// Return 'true' if this vector operation is "horizontal"
26749 /// and return the operands for the horizontal operation in LHS and RHS.  A
26750 /// horizontal operation performs the binary operation on successive elements
26751 /// of its first operand, then on successive elements of its second operand,
26752 /// returning the resulting values in a vector.  For example, if
26753 ///   A = < float a0, float a1, float a2, float a3 >
26754 /// and
26755 ///   B = < float b0, float b1, float b2, float b3 >
26756 /// then the result of doing a horizontal operation on A and B is
26757 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26758 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26759 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26760 /// set to A, RHS to B, and the routine returns 'true'.
26761 /// Note that the binary operation should have the property that if one of the
26762 /// operands is UNDEF then the result is UNDEF.
26763 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26764   // Look for the following pattern: if
26765   //   A = < float a0, float a1, float a2, float a3 >
26766   //   B = < float b0, float b1, float b2, float b3 >
26767   // and
26768   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26769   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26770   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26771   // which is A horizontal-op B.
26772
26773   // At least one of the operands should be a vector shuffle.
26774   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26775       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26776     return false;
26777
26778   MVT VT = LHS.getSimpleValueType();
26779
26780   assert((VT.is128BitVector() || VT.is256BitVector()) &&
26781          "Unsupported vector type for horizontal add/sub");
26782
26783   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26784   // operate independently on 128-bit lanes.
26785   unsigned NumElts = VT.getVectorNumElements();
26786   unsigned NumLanes = VT.getSizeInBits()/128;
26787   unsigned NumLaneElts = NumElts / NumLanes;
26788   assert((NumLaneElts % 2 == 0) &&
26789          "Vector type should have an even number of elements in each lane");
26790   unsigned HalfLaneElts = NumLaneElts/2;
26791
26792   // View LHS in the form
26793   //   LHS = VECTOR_SHUFFLE A, B, LMask
26794   // If LHS is not a shuffle then pretend it is the shuffle
26795   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26796   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26797   // type VT.
26798   SDValue A, B;
26799   SmallVector<int, 16> LMask(NumElts);
26800   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26801     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26802       A = LHS.getOperand(0);
26803     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26804       B = LHS.getOperand(1);
26805     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26806     std::copy(Mask.begin(), Mask.end(), LMask.begin());
26807   } else {
26808     if (LHS.getOpcode() != ISD::UNDEF)
26809       A = LHS;
26810     for (unsigned i = 0; i != NumElts; ++i)
26811       LMask[i] = i;
26812   }
26813
26814   // Likewise, view RHS in the form
26815   //   RHS = VECTOR_SHUFFLE C, D, RMask
26816   SDValue C, D;
26817   SmallVector<int, 16> RMask(NumElts);
26818   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26819     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26820       C = RHS.getOperand(0);
26821     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26822       D = RHS.getOperand(1);
26823     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26824     std::copy(Mask.begin(), Mask.end(), RMask.begin());
26825   } else {
26826     if (RHS.getOpcode() != ISD::UNDEF)
26827       C = RHS;
26828     for (unsigned i = 0; i != NumElts; ++i)
26829       RMask[i] = i;
26830   }
26831
26832   // Check that the shuffles are both shuffling the same vectors.
26833   if (!(A == C && B == D) && !(A == D && B == C))
26834     return false;
26835
26836   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26837   if (!A.getNode() && !B.getNode())
26838     return false;
26839
26840   // If A and B occur in reverse order in RHS, then "swap" them (which means
26841   // rewriting the mask).
26842   if (A != C)
26843     ShuffleVectorSDNode::commuteMask(RMask);
26844
26845   // At this point LHS and RHS are equivalent to
26846   //   LHS = VECTOR_SHUFFLE A, B, LMask
26847   //   RHS = VECTOR_SHUFFLE A, B, RMask
26848   // Check that the masks correspond to performing a horizontal operation.
26849   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26850     for (unsigned i = 0; i != NumLaneElts; ++i) {
26851       int LIdx = LMask[i+l], RIdx = RMask[i+l];
26852
26853       // Ignore any UNDEF components.
26854       if (LIdx < 0 || RIdx < 0 ||
26855           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26856           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26857         continue;
26858
26859       // Check that successive elements are being operated on.  If not, this is
26860       // not a horizontal operation.
26861       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26862       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26863       if (!(LIdx == Index && RIdx == Index + 1) &&
26864           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26865         return false;
26866     }
26867   }
26868
26869   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26870   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26871   return true;
26872 }
26873
26874 /// Do target-specific dag combines on floating point adds.
26875 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26876                                   const X86Subtarget *Subtarget) {
26877   EVT VT = N->getValueType(0);
26878   SDValue LHS = N->getOperand(0);
26879   SDValue RHS = N->getOperand(1);
26880
26881   // Try to synthesize horizontal adds from adds of shuffles.
26882   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26883        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26884       isHorizontalBinOp(LHS, RHS, true))
26885     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26886   return SDValue();
26887 }
26888
26889 /// Do target-specific dag combines on floating point subs.
26890 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26891                                   const X86Subtarget *Subtarget) {
26892   EVT VT = N->getValueType(0);
26893   SDValue LHS = N->getOperand(0);
26894   SDValue RHS = N->getOperand(1);
26895
26896   // Try to synthesize horizontal subs from subs of shuffles.
26897   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26898        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26899       isHorizontalBinOp(LHS, RHS, false))
26900     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26901   return SDValue();
26902 }
26903
26904 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
26905 static SDValue
26906 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
26907                                   SmallVector<SDValue, 8> &Regs) {
26908   assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
26909                              Regs[0].getValueType() == MVT::v2i64));
26910   EVT OutVT = N->getValueType(0);
26911   EVT OutSVT = OutVT.getVectorElementType();
26912   EVT InVT = Regs[0].getValueType();
26913   EVT InSVT = InVT.getVectorElementType();
26914   SDLoc DL(N);
26915
26916   // First, use mask to unset all bits that won't appear in the result.
26917   assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
26918          "OutSVT can only be either i8 or i16.");
26919   SDValue MaskVal =
26920       DAG.getConstant(OutSVT == MVT::i8 ? 0xFF : 0xFFFF, DL, InSVT);
26921   SDValue MaskVec = DAG.getNode(
26922       ISD::BUILD_VECTOR, DL, InVT,
26923       SmallVector<SDValue, 8>(InVT.getVectorNumElements(), MaskVal));
26924   for (auto &Reg : Regs)
26925     Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVec, Reg);
26926
26927   MVT UnpackedVT, PackedVT;
26928   if (OutSVT == MVT::i8) {
26929     UnpackedVT = MVT::v8i16;
26930     PackedVT = MVT::v16i8;
26931   } else {
26932     UnpackedVT = MVT::v4i32;
26933     PackedVT = MVT::v8i16;
26934   }
26935
26936   // In each iteration, truncate the type by a half size.
26937   auto RegNum = Regs.size();
26938   for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
26939        j < e; j *= 2, RegNum /= 2) {
26940     for (unsigned i = 0; i < RegNum; i++)
26941       Regs[i] = DAG.getNode(ISD::BITCAST, DL, UnpackedVT, Regs[i]);
26942     for (unsigned i = 0; i < RegNum / 2; i++)
26943       Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
26944                             Regs[i * 2 + 1]);
26945   }
26946
26947   // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
26948   // then extract a subvector as the result since v8i8 is not a legal type.
26949   if (OutVT == MVT::v8i8) {
26950     Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
26951     Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
26952                           DAG.getIntPtrConstant(0, DL));
26953     return Regs[0];
26954   } else if (RegNum > 1) {
26955     Regs.resize(RegNum);
26956     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26957   } else
26958     return Regs[0];
26959 }
26960
26961 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
26962 static SDValue
26963 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
26964                                   SmallVector<SDValue, 8> &Regs) {
26965   assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
26966   EVT OutVT = N->getValueType(0);
26967   SDLoc DL(N);
26968
26969   // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
26970   SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
26971   for (auto &Reg : Regs) {
26972     Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26973     Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26974   }
26975
26976   for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
26977     Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
26978                           Regs[i * 2 + 1]);
26979
26980   if (Regs.size() > 2) {
26981     Regs.resize(Regs.size() / 2);
26982     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26983   } else
26984     return Regs[0];
26985 }
26986
26987 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
26988 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
26989 /// legalization the truncation will be translated into a BUILD_VECTOR with each
26990 /// element that is extracted from a vector and then truncated, and it is
26991 /// diffcult to do this optimization based on them.
26992 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
26993                                        const X86Subtarget *Subtarget) {
26994   EVT OutVT = N->getValueType(0);
26995   if (!OutVT.isVector())
26996     return SDValue();
26997
26998   SDValue In = N->getOperand(0);
26999   if (!In.getValueType().isSimple())
27000     return SDValue();
27001
27002   EVT InVT = In.getValueType();
27003   unsigned NumElems = OutVT.getVectorNumElements();
27004
27005   // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
27006   // SSE2, and we need to take care of it specially.
27007   // AVX512 provides vpmovdb.
27008   if (!Subtarget->hasSSE2() || Subtarget->hasAVX2())
27009     return SDValue();
27010
27011   EVT OutSVT = OutVT.getVectorElementType();
27012   EVT InSVT = InVT.getVectorElementType();
27013   if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
27014         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
27015         NumElems >= 8))
27016     return SDValue();
27017
27018   // SSSE3's pshufb results in less instructions in the cases below.
27019   if (Subtarget->hasSSSE3() && NumElems == 8 &&
27020       ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
27021        (InSVT == MVT::i32 && OutSVT == MVT::i16)))
27022     return SDValue();
27023
27024   SDLoc DL(N);
27025
27026   // Split a long vector into vectors of legal type.
27027   unsigned RegNum = InVT.getSizeInBits() / 128;
27028   SmallVector<SDValue, 8> SubVec(RegNum);
27029   if (InSVT == MVT::i32) {
27030     for (unsigned i = 0; i < RegNum; i++)
27031       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
27032                               DAG.getIntPtrConstant(i * 4, DL));
27033   } else {
27034     for (unsigned i = 0; i < RegNum; i++)
27035       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
27036                               DAG.getIntPtrConstant(i * 2, DL));
27037   }
27038
27039   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PAKCUS
27040   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
27041   // truncate 2 x v4i32 to v8i16.
27042   if (Subtarget->hasSSE41() || OutSVT == MVT::i8)
27043     return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
27044   else if (InSVT == MVT::i32)
27045     return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
27046   else
27047     return SDValue();
27048 }
27049
27050 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
27051                                       const X86Subtarget *Subtarget) {
27052   // Try to detect AVG pattern first.
27053   SDValue Avg = detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG,
27054                                  Subtarget, SDLoc(N));
27055   if (Avg.getNode())
27056     return Avg;
27057
27058   return combineVectorTruncation(N, DAG, Subtarget);
27059 }
27060
27061 /// Do target-specific dag combines on floating point negations.
27062 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
27063                                   const X86Subtarget *Subtarget) {
27064   EVT VT = N->getValueType(0);
27065   EVT SVT = VT.getScalarType();
27066   SDValue Arg = N->getOperand(0);
27067   SDLoc DL(N);
27068
27069   // Let legalize expand this if it isn't a legal type yet.
27070   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27071     return SDValue();
27072
27073   // If we're negating a FMUL node on a target with FMA, then we can avoid the
27074   // use of a constant by performing (-0 - A*B) instead.
27075   // FIXME: Check rounding control flags as well once it becomes available.
27076   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
27077       Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
27078     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
27079     return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
27080                        Arg.getOperand(1), Zero);
27081   }
27082
27083   // If we're negating a FMA node, then we can adjust the
27084   // instruction to include the extra negation.
27085   if (Arg.hasOneUse()) {
27086     switch (Arg.getOpcode()) {
27087     case X86ISD::FMADD:
27088       return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
27089                          Arg.getOperand(1), Arg.getOperand(2));
27090     case X86ISD::FMSUB:
27091       return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
27092                          Arg.getOperand(1), Arg.getOperand(2));
27093     case X86ISD::FNMADD:
27094       return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
27095                          Arg.getOperand(1), Arg.getOperand(2));
27096     case X86ISD::FNMSUB:
27097       return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
27098                          Arg.getOperand(1), Arg.getOperand(2));
27099     }
27100   }
27101   return SDValue();
27102 }
27103
27104 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
27105                               const X86Subtarget *Subtarget) {
27106   EVT VT = N->getValueType(0);
27107   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
27108     // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
27109     // These logic operations may be executed in the integer domain.
27110     SDLoc dl(N);
27111     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
27112     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
27113
27114     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
27115     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
27116     unsigned IntOpcode = 0;
27117     switch (N->getOpcode()) {
27118       default: llvm_unreachable("Unexpected FP logic op");
27119       case X86ISD::FOR: IntOpcode = ISD::OR; break;
27120       case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
27121       case X86ISD::FAND: IntOpcode = ISD::AND; break;
27122       case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
27123     }
27124     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
27125     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
27126   }
27127   return SDValue();
27128 }
27129 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
27130 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
27131                                  const X86Subtarget *Subtarget) {
27132   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
27133
27134   // F[X]OR(0.0, x) -> x
27135   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27136     if (C->getValueAPF().isPosZero())
27137       return N->getOperand(1);
27138
27139   // F[X]OR(x, 0.0) -> x
27140   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27141     if (C->getValueAPF().isPosZero())
27142       return N->getOperand(0);
27143
27144   return lowerX86FPLogicOp(N, DAG, Subtarget);
27145 }
27146
27147 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
27148 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
27149   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
27150
27151   // Only perform optimizations if UnsafeMath is used.
27152   if (!DAG.getTarget().Options.UnsafeFPMath)
27153     return SDValue();
27154
27155   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
27156   // into FMINC and FMAXC, which are Commutative operations.
27157   unsigned NewOp = 0;
27158   switch (N->getOpcode()) {
27159     default: llvm_unreachable("unknown opcode");
27160     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
27161     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
27162   }
27163
27164   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
27165                      N->getOperand(0), N->getOperand(1));
27166 }
27167
27168 static SDValue performFMinNumFMaxNumCombine(SDNode *N, SelectionDAG &DAG,
27169                                             const X86Subtarget *Subtarget) {
27170   if (Subtarget->useSoftFloat())
27171     return SDValue();
27172
27173   // TODO: Check for global or instruction-level "nnan". In that case, we
27174   //       should be able to lower to FMAX/FMIN alone.
27175   // TODO: If an operand is already known to be a NaN or not a NaN, this
27176   //       should be an optional swap and FMAX/FMIN.
27177
27178   EVT VT = N->getValueType(0);
27179   if (!((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
27180         (Subtarget->hasSSE2() && (VT == MVT::f64 || VT == MVT::v2f64)) ||
27181         (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))))
27182     return SDValue();
27183
27184   // This takes at least 3 instructions, so favor a library call when operating
27185   // on a scalar and minimizing code size.
27186   if (!VT.isVector() && DAG.getMachineFunction().getFunction()->optForMinSize())
27187     return SDValue();
27188
27189   SDValue Op0 = N->getOperand(0);
27190   SDValue Op1 = N->getOperand(1);
27191   SDLoc DL(N);
27192   EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
27193       DAG.getDataLayout(), *DAG.getContext(), VT);
27194
27195   // There are 4 possibilities involving NaN inputs, and these are the required
27196   // outputs:
27197   //                   Op1
27198   //               Num     NaN
27199   //            ----------------
27200   //       Num  |  Max  |  Op0 |
27201   // Op0        ----------------
27202   //       NaN  |  Op1  |  NaN |
27203   //            ----------------
27204   //
27205   // The SSE FP max/min instructions were not designed for this case, but rather
27206   // to implement:
27207   //   Min = Op1 < Op0 ? Op1 : Op0
27208   //   Max = Op1 > Op0 ? Op1 : Op0
27209   //
27210   // So they always return Op0 if either input is a NaN. However, we can still
27211   // use those instructions for fmaxnum by selecting away a NaN input.
27212
27213   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
27214   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
27215   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
27216   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
27217
27218   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
27219   // are NaN, the NaN value of Op1 is the result.
27220   auto SelectOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
27221   return DAG.getNode(SelectOpcode, DL, VT, IsOp0Nan, Op1, MinOrMax);
27222 }
27223
27224 /// Do target-specific dag combines on X86ISD::FAND nodes.
27225 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
27226                                   const X86Subtarget *Subtarget) {
27227   // FAND(0.0, x) -> 0.0
27228   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27229     if (C->getValueAPF().isPosZero())
27230       return N->getOperand(0);
27231
27232   // FAND(x, 0.0) -> 0.0
27233   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27234     if (C->getValueAPF().isPosZero())
27235       return N->getOperand(1);
27236
27237   return lowerX86FPLogicOp(N, DAG, Subtarget);
27238 }
27239
27240 /// Do target-specific dag combines on X86ISD::FANDN nodes
27241 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
27242                                    const X86Subtarget *Subtarget) {
27243   // FANDN(0.0, x) -> x
27244   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27245     if (C->getValueAPF().isPosZero())
27246       return N->getOperand(1);
27247
27248   // FANDN(x, 0.0) -> 0.0
27249   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27250     if (C->getValueAPF().isPosZero())
27251       return N->getOperand(1);
27252
27253   return lowerX86FPLogicOp(N, DAG, Subtarget);
27254 }
27255
27256 static SDValue PerformBTCombine(SDNode *N,
27257                                 SelectionDAG &DAG,
27258                                 TargetLowering::DAGCombinerInfo &DCI) {
27259   // BT ignores high bits in the bit index operand.
27260   SDValue Op1 = N->getOperand(1);
27261   if (Op1.hasOneUse()) {
27262     unsigned BitWidth = Op1.getValueSizeInBits();
27263     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
27264     APInt KnownZero, KnownOne;
27265     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
27266                                           !DCI.isBeforeLegalizeOps());
27267     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27268     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
27269         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
27270       DCI.CommitTargetLoweringOpt(TLO);
27271   }
27272   return SDValue();
27273 }
27274
27275 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
27276   SDValue Op = N->getOperand(0);
27277   if (Op.getOpcode() == ISD::BITCAST)
27278     Op = Op.getOperand(0);
27279   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
27280   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
27281       VT.getVectorElementType().getSizeInBits() ==
27282       OpVT.getVectorElementType().getSizeInBits()) {
27283     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
27284   }
27285   return SDValue();
27286 }
27287
27288 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
27289                                                const X86Subtarget *Subtarget) {
27290   EVT VT = N->getValueType(0);
27291   if (!VT.isVector())
27292     return SDValue();
27293
27294   SDValue N0 = N->getOperand(0);
27295   SDValue N1 = N->getOperand(1);
27296   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
27297   SDLoc dl(N);
27298
27299   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
27300   // both SSE and AVX2 since there is no sign-extended shift right
27301   // operation on a vector with 64-bit elements.
27302   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
27303   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
27304   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
27305       N0.getOpcode() == ISD::SIGN_EXTEND)) {
27306     SDValue N00 = N0.getOperand(0);
27307
27308     // EXTLOAD has a better solution on AVX2,
27309     // it may be replaced with X86ISD::VSEXT node.
27310     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
27311       if (!ISD::isNormalLoad(N00.getNode()))
27312         return SDValue();
27313
27314     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
27315         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
27316                                   N00, N1);
27317       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
27318     }
27319   }
27320   return SDValue();
27321 }
27322
27323 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
27324 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
27325 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
27326 /// eliminate extend, add, and shift instructions.
27327 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
27328                                        const X86Subtarget *Subtarget) {
27329   // TODO: This should be valid for other integer types.
27330   EVT VT = Sext->getValueType(0);
27331   if (VT != MVT::i64)
27332     return SDValue();
27333
27334   // We need an 'add nsw' feeding into the 'sext'.
27335   SDValue Add = Sext->getOperand(0);
27336   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
27337     return SDValue();
27338
27339   // Having a constant operand to the 'add' ensures that we are not increasing
27340   // the instruction count because the constant is extended for free below.
27341   // A constant operand can also become the displacement field of an LEA.
27342   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
27343   if (!AddOp1)
27344     return SDValue();
27345
27346   // Don't make the 'add' bigger if there's no hope of combining it with some
27347   // other 'add' or 'shl' instruction.
27348   // TODO: It may be profitable to generate simpler LEA instructions in place
27349   // of single 'add' instructions, but the cost model for selecting an LEA
27350   // currently has a high threshold.
27351   bool HasLEAPotential = false;
27352   for (auto *User : Sext->uses()) {
27353     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
27354       HasLEAPotential = true;
27355       break;
27356     }
27357   }
27358   if (!HasLEAPotential)
27359     return SDValue();
27360
27361   // Everything looks good, so pull the 'sext' ahead of the 'add'.
27362   int64_t AddConstant = AddOp1->getSExtValue();
27363   SDValue AddOp0 = Add.getOperand(0);
27364   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
27365   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
27366
27367   // The wider add is guaranteed to not wrap because both operands are
27368   // sign-extended.
27369   SDNodeFlags Flags;
27370   Flags.setNoSignedWrap(true);
27371   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
27372 }
27373
27374 /// (i8,i32 {s/z}ext ({s/u}divrem (i8 x, i8 y)) ->
27375 /// (i8,i32 ({s/u}divrem_sext_hreg (i8 x, i8 y)
27376 /// This exposes the {s/z}ext to the sdivrem lowering, so that it directly
27377 /// extends from AH (which we otherwise need to do contortions to access).
27378 static SDValue getDivRem8(SDNode *N, SelectionDAG &DAG) {
27379   SDValue N0 = N->getOperand(0);
27380   auto OpcodeN = N->getOpcode();
27381   auto OpcodeN0 = N0.getOpcode();
27382   if (!((OpcodeN == ISD::SIGN_EXTEND && OpcodeN0 == ISD::SDIVREM) ||
27383         (OpcodeN == ISD::ZERO_EXTEND && OpcodeN0 == ISD::UDIVREM)))
27384     return SDValue();
27385
27386   EVT VT = N->getValueType(0);
27387   EVT InVT = N0.getValueType();
27388   if (N0.getResNo() != 1 || InVT != MVT::i8 || VT != MVT::i32)
27389     return SDValue();
27390
27391   SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27392   auto DivRemOpcode = OpcodeN0 == ISD::SDIVREM ? X86ISD::SDIVREM8_SEXT_HREG
27393                                                : X86ISD::UDIVREM8_ZEXT_HREG;
27394   SDValue R = DAG.getNode(DivRemOpcode, SDLoc(N), NodeTys, N0.getOperand(0),
27395                           N0.getOperand(1));
27396   DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27397   return R.getValue(1);
27398 }
27399
27400 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
27401                                   TargetLowering::DAGCombinerInfo &DCI,
27402                                   const X86Subtarget *Subtarget) {
27403   SDValue N0 = N->getOperand(0);
27404   EVT VT = N->getValueType(0);
27405   EVT SVT = VT.getScalarType();
27406   EVT InVT = N0.getValueType();
27407   EVT InSVT = InVT.getScalarType();
27408   SDLoc DL(N);
27409
27410   if (SDValue DivRem8 = getDivRem8(N, DAG))
27411     return DivRem8;
27412
27413   if (!DCI.isBeforeLegalizeOps()) {
27414     if (InVT == MVT::i1) {
27415       SDValue Zero = DAG.getConstant(0, DL, VT);
27416       SDValue AllOnes =
27417         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
27418       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
27419     }
27420     return SDValue();
27421   }
27422
27423   if (VT.isVector() && Subtarget->hasSSE2()) {
27424     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
27425       EVT InVT = N.getValueType();
27426       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
27427                                    Size / InVT.getScalarSizeInBits());
27428       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
27429                                     DAG.getUNDEF(InVT));
27430       Opnds[0] = N;
27431       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
27432     };
27433
27434     // If target-size is less than 128-bits, extend to a type that would extend
27435     // to 128 bits, extend that and extract the original target vector.
27436     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
27437         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27438         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27439       unsigned Scale = 128 / VT.getSizeInBits();
27440       EVT ExVT =
27441           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
27442       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
27443       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
27444       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
27445                          DAG.getIntPtrConstant(0, DL));
27446     }
27447
27448     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
27449     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
27450     if (VT.getSizeInBits() == 128 &&
27451         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27452         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27453       SDValue ExOp = ExtendVecSize(DL, N0, 128);
27454       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
27455     }
27456
27457     // On pre-AVX2 targets, split into 128-bit nodes of
27458     // ISD::SIGN_EXTEND_VECTOR_INREG.
27459     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
27460         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27461         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27462       unsigned NumVecs = VT.getSizeInBits() / 128;
27463       unsigned NumSubElts = 128 / SVT.getSizeInBits();
27464       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
27465       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
27466
27467       SmallVector<SDValue, 8> Opnds;
27468       for (unsigned i = 0, Offset = 0; i != NumVecs;
27469            ++i, Offset += NumSubElts) {
27470         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
27471                                      DAG.getIntPtrConstant(Offset, DL));
27472         SrcVec = ExtendVecSize(DL, SrcVec, 128);
27473         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
27474         Opnds.push_back(SrcVec);
27475       }
27476       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
27477     }
27478   }
27479
27480   if (Subtarget->hasAVX() && VT.is256BitVector())
27481     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27482       return R;
27483
27484   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
27485     return NewAdd;
27486
27487   return SDValue();
27488 }
27489
27490 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
27491                                  const X86Subtarget* Subtarget) {
27492   SDLoc dl(N);
27493   EVT VT = N->getValueType(0);
27494
27495   // Let legalize expand this if it isn't a legal type yet.
27496   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27497     return SDValue();
27498
27499   EVT ScalarVT = VT.getScalarType();
27500   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
27501     return SDValue();
27502
27503   SDValue A = N->getOperand(0);
27504   SDValue B = N->getOperand(1);
27505   SDValue C = N->getOperand(2);
27506
27507   bool NegA = (A.getOpcode() == ISD::FNEG);
27508   bool NegB = (B.getOpcode() == ISD::FNEG);
27509   bool NegC = (C.getOpcode() == ISD::FNEG);
27510
27511   // Negative multiplication when NegA xor NegB
27512   bool NegMul = (NegA != NegB);
27513   if (NegA)
27514     A = A.getOperand(0);
27515   if (NegB)
27516     B = B.getOperand(0);
27517   if (NegC)
27518     C = C.getOperand(0);
27519
27520   unsigned Opcode;
27521   if (!NegMul)
27522     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
27523   else
27524     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
27525
27526   return DAG.getNode(Opcode, dl, VT, A, B, C);
27527 }
27528
27529 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
27530                                   TargetLowering::DAGCombinerInfo &DCI,
27531                                   const X86Subtarget *Subtarget) {
27532   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
27533   //           (and (i32 x86isd::setcc_carry), 1)
27534   // This eliminates the zext. This transformation is necessary because
27535   // ISD::SETCC is always legalized to i8.
27536   SDLoc dl(N);
27537   SDValue N0 = N->getOperand(0);
27538   EVT VT = N->getValueType(0);
27539
27540   if (N0.getOpcode() == ISD::AND &&
27541       N0.hasOneUse() &&
27542       N0.getOperand(0).hasOneUse()) {
27543     SDValue N00 = N0.getOperand(0);
27544     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27545       if (!isOneConstant(N0.getOperand(1)))
27546         return SDValue();
27547       return DAG.getNode(ISD::AND, dl, VT,
27548                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27549                                      N00.getOperand(0), N00.getOperand(1)),
27550                          DAG.getConstant(1, dl, VT));
27551     }
27552   }
27553
27554   if (N0.getOpcode() == ISD::TRUNCATE &&
27555       N0.hasOneUse() &&
27556       N0.getOperand(0).hasOneUse()) {
27557     SDValue N00 = N0.getOperand(0);
27558     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27559       return DAG.getNode(ISD::AND, dl, VT,
27560                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27561                                      N00.getOperand(0), N00.getOperand(1)),
27562                          DAG.getConstant(1, dl, VT));
27563     }
27564   }
27565
27566   if (VT.is256BitVector())
27567     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27568       return R;
27569
27570   if (SDValue DivRem8 = getDivRem8(N, DAG))
27571     return DivRem8;
27572
27573   return SDValue();
27574 }
27575
27576 // Optimize x == -y --> x+y == 0
27577 //          x != -y --> x+y != 0
27578 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
27579                                       const X86Subtarget* Subtarget) {
27580   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
27581   SDValue LHS = N->getOperand(0);
27582   SDValue RHS = N->getOperand(1);
27583   EVT VT = N->getValueType(0);
27584   SDLoc DL(N);
27585
27586   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
27587     if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
27588       SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
27589                                  LHS.getOperand(1));
27590       return DAG.getSetCC(DL, N->getValueType(0), addV,
27591                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27592     }
27593   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
27594     if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
27595       SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
27596                                  RHS.getOperand(1));
27597       return DAG.getSetCC(DL, N->getValueType(0), addV,
27598                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27599     }
27600
27601   if (VT.getScalarType() == MVT::i1 &&
27602       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
27603     bool IsSEXT0 =
27604         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27605         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27606     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27607
27608     if (!IsSEXT0 || !IsVZero1) {
27609       // Swap the operands and update the condition code.
27610       std::swap(LHS, RHS);
27611       CC = ISD::getSetCCSwappedOperands(CC);
27612
27613       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27614                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27615       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27616     }
27617
27618     if (IsSEXT0 && IsVZero1) {
27619       assert(VT == LHS.getOperand(0).getValueType() &&
27620              "Uexpected operand type");
27621       if (CC == ISD::SETGT)
27622         return DAG.getConstant(0, DL, VT);
27623       if (CC == ISD::SETLE)
27624         return DAG.getConstant(1, DL, VT);
27625       if (CC == ISD::SETEQ || CC == ISD::SETGE)
27626         return DAG.getNOT(DL, LHS.getOperand(0), VT);
27627
27628       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
27629              "Unexpected condition code!");
27630       return LHS.getOperand(0);
27631     }
27632   }
27633
27634   return SDValue();
27635 }
27636
27637 static SDValue PerformGatherScatterCombine(SDNode *N, SelectionDAG &DAG) {
27638   SDLoc DL(N);
27639   // Gather and Scatter instructions use k-registers for masks. The type of
27640   // the masks is v*i1. So the mask will be truncated anyway.
27641   // The SIGN_EXTEND_INREG my be dropped.
27642   SDValue Mask = N->getOperand(2);
27643   if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
27644     SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
27645     NewOps[2] = Mask.getOperand(0);
27646     DAG.UpdateNodeOperands(N, NewOps);
27647   }
27648   return SDValue();
27649 }
27650
27651 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
27652 // as "sbb reg,reg", since it can be extended without zext and produces
27653 // an all-ones bit which is more useful than 0/1 in some cases.
27654 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
27655                                MVT VT) {
27656   if (VT == MVT::i8)
27657     return DAG.getNode(ISD::AND, DL, VT,
27658                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27659                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
27660                                    EFLAGS),
27661                        DAG.getConstant(1, DL, VT));
27662   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
27663   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
27664                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27665                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
27666                                  EFLAGS));
27667 }
27668
27669 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
27670 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
27671                                    TargetLowering::DAGCombinerInfo &DCI,
27672                                    const X86Subtarget *Subtarget) {
27673   SDLoc DL(N);
27674   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
27675   SDValue EFLAGS = N->getOperand(1);
27676
27677   if (CC == X86::COND_A) {
27678     // Try to convert COND_A into COND_B in an attempt to facilitate
27679     // materializing "setb reg".
27680     //
27681     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
27682     // cannot take an immediate as its first operand.
27683     //
27684     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
27685         EFLAGS.getValueType().isInteger() &&
27686         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
27687       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
27688                                    EFLAGS.getNode()->getVTList(),
27689                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
27690       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
27691       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
27692     }
27693   }
27694
27695   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
27696   // a zext and produces an all-ones bit which is more useful than 0/1 in some
27697   // cases.
27698   if (CC == X86::COND_B)
27699     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
27700
27701   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27702     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27703     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
27704   }
27705
27706   return SDValue();
27707 }
27708
27709 // Optimize branch condition evaluation.
27710 //
27711 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
27712                                     TargetLowering::DAGCombinerInfo &DCI,
27713                                     const X86Subtarget *Subtarget) {
27714   SDLoc DL(N);
27715   SDValue Chain = N->getOperand(0);
27716   SDValue Dest = N->getOperand(1);
27717   SDValue EFLAGS = N->getOperand(3);
27718   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
27719
27720   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27721     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27722     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
27723                        Flags);
27724   }
27725
27726   return SDValue();
27727 }
27728
27729 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
27730                                                          SelectionDAG &DAG) {
27731   // Take advantage of vector comparisons producing 0 or -1 in each lane to
27732   // optimize away operation when it's from a constant.
27733   //
27734   // The general transformation is:
27735   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
27736   //       AND(VECTOR_CMP(x,y), constant2)
27737   //    constant2 = UNARYOP(constant)
27738
27739   // Early exit if this isn't a vector operation, the operand of the
27740   // unary operation isn't a bitwise AND, or if the sizes of the operations
27741   // aren't the same.
27742   EVT VT = N->getValueType(0);
27743   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27744       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27745       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27746     return SDValue();
27747
27748   // Now check that the other operand of the AND is a constant. We could
27749   // make the transformation for non-constant splats as well, but it's unclear
27750   // that would be a benefit as it would not eliminate any operations, just
27751   // perform one more step in scalar code before moving to the vector unit.
27752   if (BuildVectorSDNode *BV =
27753           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27754     // Bail out if the vector isn't a constant.
27755     if (!BV->isConstant())
27756       return SDValue();
27757
27758     // Everything checks out. Build up the new and improved node.
27759     SDLoc DL(N);
27760     EVT IntVT = BV->getValueType(0);
27761     // Create a new constant of the appropriate type for the transformed
27762     // DAG.
27763     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27764     // The AND node needs bitcasts to/from an integer vector type around it.
27765     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27766     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27767                                  N->getOperand(0)->getOperand(0), MaskConst);
27768     SDValue Res = DAG.getBitcast(VT, NewAnd);
27769     return Res;
27770   }
27771
27772   return SDValue();
27773 }
27774
27775 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27776                                         const X86Subtarget *Subtarget) {
27777   SDValue Op0 = N->getOperand(0);
27778   EVT VT = N->getValueType(0);
27779   EVT InVT = Op0.getValueType();
27780   EVT InSVT = InVT.getScalarType();
27781   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27782
27783   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27784   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27785   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27786     SDLoc dl(N);
27787     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27788                                  InVT.getVectorNumElements());
27789     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27790
27791     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27792       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27793
27794     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27795   }
27796
27797   return SDValue();
27798 }
27799
27800 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27801                                         const X86Subtarget *Subtarget) {
27802   // First try to optimize away the conversion entirely when it's
27803   // conditionally from a constant. Vectors only.
27804   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27805     return Res;
27806
27807   // Now move on to more general possibilities.
27808   SDValue Op0 = N->getOperand(0);
27809   EVT VT = N->getValueType(0);
27810   EVT InVT = Op0.getValueType();
27811   EVT InSVT = InVT.getScalarType();
27812
27813   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27814   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27815   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27816     SDLoc dl(N);
27817     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27818                                  InVT.getVectorNumElements());
27819     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27820     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27821   }
27822
27823   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27824   // a 32-bit target where SSE doesn't support i64->FP operations.
27825   if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27826     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27827     EVT LdVT = Ld->getValueType(0);
27828
27829     // This transformation is not supported if the result type is f16
27830     if (VT == MVT::f16)
27831       return SDValue();
27832
27833     if (!Ld->isVolatile() && !VT.isVector() &&
27834         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27835         !Subtarget->is64Bit() && LdVT == MVT::i64) {
27836       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27837           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27838       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27839       return FILDChain;
27840     }
27841   }
27842   return SDValue();
27843 }
27844
27845 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27846 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27847                                  X86TargetLowering::DAGCombinerInfo &DCI) {
27848   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27849   // the result is either zero or one (depending on the input carry bit).
27850   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27851   if (X86::isZeroNode(N->getOperand(0)) &&
27852       X86::isZeroNode(N->getOperand(1)) &&
27853       // We don't have a good way to replace an EFLAGS use, so only do this when
27854       // dead right now.
27855       SDValue(N, 1).use_empty()) {
27856     SDLoc DL(N);
27857     EVT VT = N->getValueType(0);
27858     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27859     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27860                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27861                                            DAG.getConstant(X86::COND_B, DL,
27862                                                            MVT::i8),
27863                                            N->getOperand(2)),
27864                                DAG.getConstant(1, DL, VT));
27865     return DCI.CombineTo(N, Res1, CarryOut);
27866   }
27867
27868   return SDValue();
27869 }
27870
27871 // fold (add Y, (sete  X, 0)) -> adc  0, Y
27872 //      (add Y, (setne X, 0)) -> sbb -1, Y
27873 //      (sub (sete  X, 0), Y) -> sbb  0, Y
27874 //      (sub (setne X, 0), Y) -> adc -1, Y
27875 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27876   SDLoc DL(N);
27877
27878   // Look through ZExts.
27879   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27880   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27881     return SDValue();
27882
27883   SDValue SetCC = Ext.getOperand(0);
27884   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27885     return SDValue();
27886
27887   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27888   if (CC != X86::COND_E && CC != X86::COND_NE)
27889     return SDValue();
27890
27891   SDValue Cmp = SetCC.getOperand(1);
27892   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27893       !X86::isZeroNode(Cmp.getOperand(1)) ||
27894       !Cmp.getOperand(0).getValueType().isInteger())
27895     return SDValue();
27896
27897   SDValue CmpOp0 = Cmp.getOperand(0);
27898   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27899                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
27900
27901   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27902   if (CC == X86::COND_NE)
27903     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27904                        DL, OtherVal.getValueType(), OtherVal,
27905                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27906                        NewCmp);
27907   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27908                      DL, OtherVal.getValueType(), OtherVal,
27909                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27910 }
27911
27912 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27913 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27914                                  const X86Subtarget *Subtarget) {
27915   EVT VT = N->getValueType(0);
27916   SDValue Op0 = N->getOperand(0);
27917   SDValue Op1 = N->getOperand(1);
27918
27919   // Try to synthesize horizontal adds from adds of shuffles.
27920   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27921        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27922       isHorizontalBinOp(Op0, Op1, true))
27923     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27924
27925   return OptimizeConditionalInDecrement(N, DAG);
27926 }
27927
27928 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27929                                  const X86Subtarget *Subtarget) {
27930   SDValue Op0 = N->getOperand(0);
27931   SDValue Op1 = N->getOperand(1);
27932
27933   // X86 can't encode an immediate LHS of a sub. See if we can push the
27934   // negation into a preceding instruction.
27935   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27936     // If the RHS of the sub is a XOR with one use and a constant, invert the
27937     // immediate. Then add one to the LHS of the sub so we can turn
27938     // X-Y -> X+~Y+1, saving one register.
27939     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27940         isa<ConstantSDNode>(Op1.getOperand(1))) {
27941       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27942       EVT VT = Op0.getValueType();
27943       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27944                                    Op1.getOperand(0),
27945                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
27946       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27947                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27948     }
27949   }
27950
27951   // Try to synthesize horizontal adds from adds of shuffles.
27952   EVT VT = N->getValueType(0);
27953   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27954        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27955       isHorizontalBinOp(Op0, Op1, true))
27956     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27957
27958   return OptimizeConditionalInDecrement(N, DAG);
27959 }
27960
27961 /// performVZEXTCombine - Performs build vector combines
27962 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27963                                    TargetLowering::DAGCombinerInfo &DCI,
27964                                    const X86Subtarget *Subtarget) {
27965   SDLoc DL(N);
27966   MVT VT = N->getSimpleValueType(0);
27967   SDValue Op = N->getOperand(0);
27968   MVT OpVT = Op.getSimpleValueType();
27969   MVT OpEltVT = OpVT.getVectorElementType();
27970   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27971
27972   // (vzext (bitcast (vzext (x)) -> (vzext x)
27973   SDValue V = Op;
27974   while (V.getOpcode() == ISD::BITCAST)
27975     V = V.getOperand(0);
27976
27977   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27978     MVT InnerVT = V.getSimpleValueType();
27979     MVT InnerEltVT = InnerVT.getVectorElementType();
27980
27981     // If the element sizes match exactly, we can just do one larger vzext. This
27982     // is always an exact type match as vzext operates on integer types.
27983     if (OpEltVT == InnerEltVT) {
27984       assert(OpVT == InnerVT && "Types must match for vzext!");
27985       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27986     }
27987
27988     // The only other way we can combine them is if only a single element of the
27989     // inner vzext is used in the input to the outer vzext.
27990     if (InnerEltVT.getSizeInBits() < InputBits)
27991       return SDValue();
27992
27993     // In this case, the inner vzext is completely dead because we're going to
27994     // only look at bits inside of the low element. Just do the outer vzext on
27995     // a bitcast of the input to the inner.
27996     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27997   }
27998
27999   // Check if we can bypass extracting and re-inserting an element of an input
28000   // vector. Essentially:
28001   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
28002   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
28003       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
28004       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
28005     SDValue ExtractedV = V.getOperand(0);
28006     SDValue OrigV = ExtractedV.getOperand(0);
28007     if (isNullConstant(ExtractedV.getOperand(1))) {
28008         MVT OrigVT = OrigV.getSimpleValueType();
28009         // Extract a subvector if necessary...
28010         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
28011           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
28012           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
28013                                     OrigVT.getVectorNumElements() / Ratio);
28014           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
28015                               DAG.getIntPtrConstant(0, DL));
28016         }
28017         Op = DAG.getBitcast(OpVT, OrigV);
28018         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
28019       }
28020   }
28021
28022   return SDValue();
28023 }
28024
28025 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
28026                                              DAGCombinerInfo &DCI) const {
28027   SelectionDAG &DAG = DCI.DAG;
28028   switch (N->getOpcode()) {
28029   default: break;
28030   case ISD::EXTRACT_VECTOR_ELT:
28031     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
28032   case ISD::VSELECT:
28033   case ISD::SELECT:
28034   case X86ISD::SHRUNKBLEND:
28035     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
28036   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
28037   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
28038   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
28039   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
28040   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
28041   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
28042   case ISD::SHL:
28043   case ISD::SRA:
28044   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
28045   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
28046   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
28047   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
28048   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
28049   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
28050   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
28051   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
28052   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
28053   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
28054   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
28055   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
28056   case ISD::FNEG:           return PerformFNEGCombine(N, DAG, Subtarget);
28057   case ISD::TRUNCATE:       return PerformTRUNCATECombine(N, DAG, Subtarget);
28058   case X86ISD::FXOR:
28059   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
28060   case X86ISD::FMIN:
28061   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
28062   case ISD::FMINNUM:
28063   case ISD::FMAXNUM:        return performFMinNumFMaxNumCombine(N, DAG,
28064                                                                 Subtarget);
28065   case X86ISD::FAND:        return PerformFANDCombine(N, DAG, Subtarget);
28066   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG, Subtarget);
28067   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
28068   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
28069   case ISD::ANY_EXTEND:
28070   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
28071   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
28072   case ISD::SIGN_EXTEND_INREG:
28073     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
28074   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
28075   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
28076   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
28077   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
28078   case X86ISD::SHUFP:       // Handle all target specific shuffles
28079   case X86ISD::PALIGNR:
28080   case X86ISD::BLENDI:
28081   case X86ISD::UNPCKH:
28082   case X86ISD::UNPCKL:
28083   case X86ISD::MOVHLPS:
28084   case X86ISD::MOVLHPS:
28085   case X86ISD::PSHUFB:
28086   case X86ISD::PSHUFD:
28087   case X86ISD::PSHUFHW:
28088   case X86ISD::PSHUFLW:
28089   case X86ISD::MOVSS:
28090   case X86ISD::MOVSD:
28091   case X86ISD::VPERMILPI:
28092   case X86ISD::VPERM2X128:
28093   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
28094   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
28095   case ISD::MGATHER:
28096   case ISD::MSCATTER:       return PerformGatherScatterCombine(N, DAG);
28097   }
28098
28099   return SDValue();
28100 }
28101
28102 /// isTypeDesirableForOp - Return true if the target has native support for
28103 /// the specified value type and it is 'desirable' to use the type for the
28104 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
28105 /// instruction encodings are longer and some i16 instructions are slow.
28106 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
28107   if (!isTypeLegal(VT))
28108     return false;
28109   if (VT != MVT::i16)
28110     return true;
28111
28112   switch (Opc) {
28113   default:
28114     return true;
28115   case ISD::LOAD:
28116   case ISD::SIGN_EXTEND:
28117   case ISD::ZERO_EXTEND:
28118   case ISD::ANY_EXTEND:
28119   case ISD::SHL:
28120   case ISD::SRL:
28121   case ISD::SUB:
28122   case ISD::ADD:
28123   case ISD::MUL:
28124   case ISD::AND:
28125   case ISD::OR:
28126   case ISD::XOR:
28127     return false;
28128   }
28129 }
28130
28131 /// This function checks if any of the users of EFLAGS copies the EFLAGS. We
28132 /// know that the code that lowers COPY of EFLAGS has to use the stack, and if
28133 /// we don't adjust the stack we clobber the first frame index.
28134 /// See X86InstrInfo::copyPhysReg.
28135 bool X86TargetLowering::hasCopyImplyingStackAdjustment(
28136     MachineFunction *MF) const {
28137   const MachineRegisterInfo &MRI = MF->getRegInfo();
28138
28139   return any_of(MRI.reg_instructions(X86::EFLAGS),
28140                 [](const MachineInstr &RI) { return RI.isCopy(); });
28141 }
28142
28143 /// IsDesirableToPromoteOp - This method query the target whether it is
28144 /// beneficial for dag combiner to promote the specified node. If true, it
28145 /// should return the desired promotion type by reference.
28146 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
28147   EVT VT = Op.getValueType();
28148   if (VT != MVT::i16)
28149     return false;
28150
28151   bool Promote = false;
28152   bool Commute = false;
28153   switch (Op.getOpcode()) {
28154   default: break;
28155   case ISD::LOAD: {
28156     LoadSDNode *LD = cast<LoadSDNode>(Op);
28157     // If the non-extending load has a single use and it's not live out, then it
28158     // might be folded.
28159     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
28160                                                      Op.hasOneUse()*/) {
28161       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
28162              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
28163         // The only case where we'd want to promote LOAD (rather then it being
28164         // promoted as an operand is when it's only use is liveout.
28165         if (UI->getOpcode() != ISD::CopyToReg)
28166           return false;
28167       }
28168     }
28169     Promote = true;
28170     break;
28171   }
28172   case ISD::SIGN_EXTEND:
28173   case ISD::ZERO_EXTEND:
28174   case ISD::ANY_EXTEND:
28175     Promote = true;
28176     break;
28177   case ISD::SHL:
28178   case ISD::SRL: {
28179     SDValue N0 = Op.getOperand(0);
28180     // Look out for (store (shl (load), x)).
28181     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
28182       return false;
28183     Promote = true;
28184     break;
28185   }
28186   case ISD::ADD:
28187   case ISD::MUL:
28188   case ISD::AND:
28189   case ISD::OR:
28190   case ISD::XOR:
28191     Commute = true;
28192     // fallthrough
28193   case ISD::SUB: {
28194     SDValue N0 = Op.getOperand(0);
28195     SDValue N1 = Op.getOperand(1);
28196     if (!Commute && MayFoldLoad(N1))
28197       return false;
28198     // Avoid disabling potential load folding opportunities.
28199     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
28200       return false;
28201     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
28202       return false;
28203     Promote = true;
28204   }
28205   }
28206
28207   PVT = MVT::i32;
28208   return Promote;
28209 }
28210
28211 //===----------------------------------------------------------------------===//
28212 //                           X86 Inline Assembly Support
28213 //===----------------------------------------------------------------------===//
28214
28215 // Helper to match a string separated by whitespace.
28216 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
28217   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
28218
28219   for (StringRef Piece : Pieces) {
28220     if (!S.startswith(Piece)) // Check if the piece matches.
28221       return false;
28222
28223     S = S.substr(Piece.size());
28224     StringRef::size_type Pos = S.find_first_not_of(" \t");
28225     if (Pos == 0) // We matched a prefix.
28226       return false;
28227
28228     S = S.substr(Pos);
28229   }
28230
28231   return S.empty();
28232 }
28233
28234 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
28235
28236   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
28237     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
28238         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
28239         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
28240
28241       if (AsmPieces.size() == 3)
28242         return true;
28243       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
28244         return true;
28245     }
28246   }
28247   return false;
28248 }
28249
28250 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
28251   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
28252
28253   std::string AsmStr = IA->getAsmString();
28254
28255   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
28256   if (!Ty || Ty->getBitWidth() % 16 != 0)
28257     return false;
28258
28259   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
28260   SmallVector<StringRef, 4> AsmPieces;
28261   SplitString(AsmStr, AsmPieces, ";\n");
28262
28263   switch (AsmPieces.size()) {
28264   default: return false;
28265   case 1:
28266     // FIXME: this should verify that we are targeting a 486 or better.  If not,
28267     // we will turn this bswap into something that will be lowered to logical
28268     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
28269     // lower so don't worry about this.
28270     // bswap $0
28271     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
28272         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
28273         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
28274         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
28275         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
28276         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
28277       // No need to check constraints, nothing other than the equivalent of
28278       // "=r,0" would be valid here.
28279       return IntrinsicLowering::LowerToByteSwap(CI);
28280     }
28281
28282     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
28283     if (CI->getType()->isIntegerTy(16) &&
28284         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28285         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
28286          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
28287       AsmPieces.clear();
28288       StringRef ConstraintsStr = IA->getConstraintString();
28289       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28290       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28291       if (clobbersFlagRegisters(AsmPieces))
28292         return IntrinsicLowering::LowerToByteSwap(CI);
28293     }
28294     break;
28295   case 3:
28296     if (CI->getType()->isIntegerTy(32) &&
28297         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28298         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
28299         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
28300         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
28301       AsmPieces.clear();
28302       StringRef ConstraintsStr = IA->getConstraintString();
28303       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28304       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28305       if (clobbersFlagRegisters(AsmPieces))
28306         return IntrinsicLowering::LowerToByteSwap(CI);
28307     }
28308
28309     if (CI->getType()->isIntegerTy(64)) {
28310       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
28311       if (Constraints.size() >= 2 &&
28312           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
28313           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
28314         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
28315         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
28316             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
28317             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
28318           return IntrinsicLowering::LowerToByteSwap(CI);
28319       }
28320     }
28321     break;
28322   }
28323   return false;
28324 }
28325
28326 /// getConstraintType - Given a constraint letter, return the type of
28327 /// constraint it is for this target.
28328 X86TargetLowering::ConstraintType
28329 X86TargetLowering::getConstraintType(StringRef Constraint) const {
28330   if (Constraint.size() == 1) {
28331     switch (Constraint[0]) {
28332     case 'R':
28333     case 'q':
28334     case 'Q':
28335     case 'f':
28336     case 't':
28337     case 'u':
28338     case 'y':
28339     case 'x':
28340     case 'Y':
28341     case 'l':
28342       return C_RegisterClass;
28343     case 'a':
28344     case 'b':
28345     case 'c':
28346     case 'd':
28347     case 'S':
28348     case 'D':
28349     case 'A':
28350       return C_Register;
28351     case 'I':
28352     case 'J':
28353     case 'K':
28354     case 'L':
28355     case 'M':
28356     case 'N':
28357     case 'G':
28358     case 'C':
28359     case 'e':
28360     case 'Z':
28361       return C_Other;
28362     default:
28363       break;
28364     }
28365   }
28366   return TargetLowering::getConstraintType(Constraint);
28367 }
28368
28369 /// Examine constraint type and operand type and determine a weight value.
28370 /// This object must already have been set up with the operand type
28371 /// and the current alternative constraint selected.
28372 TargetLowering::ConstraintWeight
28373   X86TargetLowering::getSingleConstraintMatchWeight(
28374     AsmOperandInfo &info, const char *constraint) const {
28375   ConstraintWeight weight = CW_Invalid;
28376   Value *CallOperandVal = info.CallOperandVal;
28377     // If we don't have a value, we can't do a match,
28378     // but allow it at the lowest weight.
28379   if (!CallOperandVal)
28380     return CW_Default;
28381   Type *type = CallOperandVal->getType();
28382   // Look at the constraint type.
28383   switch (*constraint) {
28384   default:
28385     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
28386   case 'R':
28387   case 'q':
28388   case 'Q':
28389   case 'a':
28390   case 'b':
28391   case 'c':
28392   case 'd':
28393   case 'S':
28394   case 'D':
28395   case 'A':
28396     if (CallOperandVal->getType()->isIntegerTy())
28397       weight = CW_SpecificReg;
28398     break;
28399   case 'f':
28400   case 't':
28401   case 'u':
28402     if (type->isFloatingPointTy())
28403       weight = CW_SpecificReg;
28404     break;
28405   case 'y':
28406     if (type->isX86_MMXTy() && Subtarget->hasMMX())
28407       weight = CW_SpecificReg;
28408     break;
28409   case 'x':
28410   case 'Y':
28411     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
28412         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
28413       weight = CW_Register;
28414     break;
28415   case 'I':
28416     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
28417       if (C->getZExtValue() <= 31)
28418         weight = CW_Constant;
28419     }
28420     break;
28421   case 'J':
28422     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28423       if (C->getZExtValue() <= 63)
28424         weight = CW_Constant;
28425     }
28426     break;
28427   case 'K':
28428     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28429       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
28430         weight = CW_Constant;
28431     }
28432     break;
28433   case 'L':
28434     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28435       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
28436         weight = CW_Constant;
28437     }
28438     break;
28439   case 'M':
28440     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28441       if (C->getZExtValue() <= 3)
28442         weight = CW_Constant;
28443     }
28444     break;
28445   case 'N':
28446     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28447       if (C->getZExtValue() <= 0xff)
28448         weight = CW_Constant;
28449     }
28450     break;
28451   case 'G':
28452   case 'C':
28453     if (isa<ConstantFP>(CallOperandVal)) {
28454       weight = CW_Constant;
28455     }
28456     break;
28457   case 'e':
28458     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28459       if ((C->getSExtValue() >= -0x80000000LL) &&
28460           (C->getSExtValue() <= 0x7fffffffLL))
28461         weight = CW_Constant;
28462     }
28463     break;
28464   case 'Z':
28465     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28466       if (C->getZExtValue() <= 0xffffffff)
28467         weight = CW_Constant;
28468     }
28469     break;
28470   }
28471   return weight;
28472 }
28473
28474 /// LowerXConstraint - try to replace an X constraint, which matches anything,
28475 /// with another that has more specific requirements based on the type of the
28476 /// corresponding operand.
28477 const char *X86TargetLowering::
28478 LowerXConstraint(EVT ConstraintVT) const {
28479   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
28480   // 'f' like normal targets.
28481   if (ConstraintVT.isFloatingPoint()) {
28482     if (Subtarget->hasSSE2())
28483       return "Y";
28484     if (Subtarget->hasSSE1())
28485       return "x";
28486   }
28487
28488   return TargetLowering::LowerXConstraint(ConstraintVT);
28489 }
28490
28491 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
28492 /// vector.  If it is invalid, don't add anything to Ops.
28493 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
28494                                                      std::string &Constraint,
28495                                                      std::vector<SDValue>&Ops,
28496                                                      SelectionDAG &DAG) const {
28497   SDValue Result;
28498
28499   // Only support length 1 constraints for now.
28500   if (Constraint.length() > 1) return;
28501
28502   char ConstraintLetter = Constraint[0];
28503   switch (ConstraintLetter) {
28504   default: break;
28505   case 'I':
28506     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28507       if (C->getZExtValue() <= 31) {
28508         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28509                                        Op.getValueType());
28510         break;
28511       }
28512     }
28513     return;
28514   case 'J':
28515     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28516       if (C->getZExtValue() <= 63) {
28517         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28518                                        Op.getValueType());
28519         break;
28520       }
28521     }
28522     return;
28523   case 'K':
28524     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28525       if (isInt<8>(C->getSExtValue())) {
28526         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28527                                        Op.getValueType());
28528         break;
28529       }
28530     }
28531     return;
28532   case 'L':
28533     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28534       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
28535           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
28536         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
28537                                        Op.getValueType());
28538         break;
28539       }
28540     }
28541     return;
28542   case 'M':
28543     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28544       if (C->getZExtValue() <= 3) {
28545         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28546                                        Op.getValueType());
28547         break;
28548       }
28549     }
28550     return;
28551   case 'N':
28552     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28553       if (C->getZExtValue() <= 255) {
28554         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28555                                        Op.getValueType());
28556         break;
28557       }
28558     }
28559     return;
28560   case 'O':
28561     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28562       if (C->getZExtValue() <= 127) {
28563         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28564                                        Op.getValueType());
28565         break;
28566       }
28567     }
28568     return;
28569   case 'e': {
28570     // 32-bit signed value
28571     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28572       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28573                                            C->getSExtValue())) {
28574         // Widen to 64 bits here to get it sign extended.
28575         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
28576         break;
28577       }
28578     // FIXME gcc accepts some relocatable values here too, but only in certain
28579     // memory models; it's complicated.
28580     }
28581     return;
28582   }
28583   case 'Z': {
28584     // 32-bit unsigned value
28585     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28586       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28587                                            C->getZExtValue())) {
28588         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28589                                        Op.getValueType());
28590         break;
28591       }
28592     }
28593     // FIXME gcc accepts some relocatable values here too, but only in certain
28594     // memory models; it's complicated.
28595     return;
28596   }
28597   case 'i': {
28598     // Literal immediates are always ok.
28599     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
28600       // Widen to 64 bits here to get it sign extended.
28601       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
28602       break;
28603     }
28604
28605     // In any sort of PIC mode addresses need to be computed at runtime by
28606     // adding in a register or some sort of table lookup.  These can't
28607     // be used as immediates.
28608     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
28609       return;
28610
28611     // If we are in non-pic codegen mode, we allow the address of a global (with
28612     // an optional displacement) to be used with 'i'.
28613     GlobalAddressSDNode *GA = nullptr;
28614     int64_t Offset = 0;
28615
28616     // Match either (GA), (GA+C), (GA+C1+C2), etc.
28617     while (1) {
28618       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
28619         Offset += GA->getOffset();
28620         break;
28621       } else if (Op.getOpcode() == ISD::ADD) {
28622         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28623           Offset += C->getZExtValue();
28624           Op = Op.getOperand(0);
28625           continue;
28626         }
28627       } else if (Op.getOpcode() == ISD::SUB) {
28628         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28629           Offset += -C->getZExtValue();
28630           Op = Op.getOperand(0);
28631           continue;
28632         }
28633       }
28634
28635       // Otherwise, this isn't something we can handle, reject it.
28636       return;
28637     }
28638
28639     const GlobalValue *GV = GA->getGlobal();
28640     // If we require an extra load to get this address, as in PIC mode, we
28641     // can't accept it.
28642     if (isGlobalStubReference(
28643             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
28644       return;
28645
28646     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
28647                                         GA->getValueType(0), Offset);
28648     break;
28649   }
28650   }
28651
28652   if (Result.getNode()) {
28653     Ops.push_back(Result);
28654     return;
28655   }
28656   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
28657 }
28658
28659 std::pair<unsigned, const TargetRegisterClass *>
28660 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
28661                                                 StringRef Constraint,
28662                                                 MVT VT) const {
28663   // First, see if this is a constraint that directly corresponds to an LLVM
28664   // register class.
28665   if (Constraint.size() == 1) {
28666     // GCC Constraint Letters
28667     switch (Constraint[0]) {
28668     default: break;
28669       // TODO: Slight differences here in allocation order and leaving
28670       // RIP in the class. Do they matter any more here than they do
28671       // in the normal allocation?
28672     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
28673       if (Subtarget->is64Bit()) {
28674         if (VT == MVT::i32 || VT == MVT::f32)
28675           return std::make_pair(0U, &X86::GR32RegClass);
28676         if (VT == MVT::i16)
28677           return std::make_pair(0U, &X86::GR16RegClass);
28678         if (VT == MVT::i8 || VT == MVT::i1)
28679           return std::make_pair(0U, &X86::GR8RegClass);
28680         if (VT == MVT::i64 || VT == MVT::f64)
28681           return std::make_pair(0U, &X86::GR64RegClass);
28682         break;
28683       }
28684       // 32-bit fallthrough
28685     case 'Q':   // Q_REGS
28686       if (VT == MVT::i32 || VT == MVT::f32)
28687         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
28688       if (VT == MVT::i16)
28689         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
28690       if (VT == MVT::i8 || VT == MVT::i1)
28691         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
28692       if (VT == MVT::i64)
28693         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
28694       break;
28695     case 'r':   // GENERAL_REGS
28696     case 'l':   // INDEX_REGS
28697       if (VT == MVT::i8 || VT == MVT::i1)
28698         return std::make_pair(0U, &X86::GR8RegClass);
28699       if (VT == MVT::i16)
28700         return std::make_pair(0U, &X86::GR16RegClass);
28701       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
28702         return std::make_pair(0U, &X86::GR32RegClass);
28703       return std::make_pair(0U, &X86::GR64RegClass);
28704     case 'R':   // LEGACY_REGS
28705       if (VT == MVT::i8 || VT == MVT::i1)
28706         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
28707       if (VT == MVT::i16)
28708         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
28709       if (VT == MVT::i32 || !Subtarget->is64Bit())
28710         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
28711       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
28712     case 'f':  // FP Stack registers.
28713       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
28714       // value to the correct fpstack register class.
28715       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
28716         return std::make_pair(0U, &X86::RFP32RegClass);
28717       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
28718         return std::make_pair(0U, &X86::RFP64RegClass);
28719       return std::make_pair(0U, &X86::RFP80RegClass);
28720     case 'y':   // MMX_REGS if MMX allowed.
28721       if (!Subtarget->hasMMX()) break;
28722       return std::make_pair(0U, &X86::VR64RegClass);
28723     case 'Y':   // SSE_REGS if SSE2 allowed
28724       if (!Subtarget->hasSSE2()) break;
28725       // FALL THROUGH.
28726     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
28727       if (!Subtarget->hasSSE1()) break;
28728
28729       switch (VT.SimpleTy) {
28730       default: break;
28731       // Scalar SSE types.
28732       case MVT::f32:
28733       case MVT::i32:
28734         return std::make_pair(0U, &X86::FR32RegClass);
28735       case MVT::f64:
28736       case MVT::i64:
28737         return std::make_pair(0U, &X86::FR64RegClass);
28738       // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28739       // Vector types.
28740       case MVT::v16i8:
28741       case MVT::v8i16:
28742       case MVT::v4i32:
28743       case MVT::v2i64:
28744       case MVT::v4f32:
28745       case MVT::v2f64:
28746         return std::make_pair(0U, &X86::VR128RegClass);
28747       // AVX types.
28748       case MVT::v32i8:
28749       case MVT::v16i16:
28750       case MVT::v8i32:
28751       case MVT::v4i64:
28752       case MVT::v8f32:
28753       case MVT::v4f64:
28754         return std::make_pair(0U, &X86::VR256RegClass);
28755       case MVT::v8f64:
28756       case MVT::v16f32:
28757       case MVT::v16i32:
28758       case MVT::v8i64:
28759         return std::make_pair(0U, &X86::VR512RegClass);
28760       }
28761       break;
28762     }
28763   }
28764
28765   // Use the default implementation in TargetLowering to convert the register
28766   // constraint into a member of a register class.
28767   std::pair<unsigned, const TargetRegisterClass*> Res;
28768   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28769
28770   // Not found as a standard register?
28771   if (!Res.second) {
28772     // Map st(0) -> st(7) -> ST0
28773     if (Constraint.size() == 7 && Constraint[0] == '{' &&
28774         tolower(Constraint[1]) == 's' &&
28775         tolower(Constraint[2]) == 't' &&
28776         Constraint[3] == '(' &&
28777         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28778         Constraint[5] == ')' &&
28779         Constraint[6] == '}') {
28780
28781       Res.first = X86::FP0+Constraint[4]-'0';
28782       Res.second = &X86::RFP80RegClass;
28783       return Res;
28784     }
28785
28786     // GCC allows "st(0)" to be called just plain "st".
28787     if (StringRef("{st}").equals_lower(Constraint)) {
28788       Res.first = X86::FP0;
28789       Res.second = &X86::RFP80RegClass;
28790       return Res;
28791     }
28792
28793     // flags -> EFLAGS
28794     if (StringRef("{flags}").equals_lower(Constraint)) {
28795       Res.first = X86::EFLAGS;
28796       Res.second = &X86::CCRRegClass;
28797       return Res;
28798     }
28799
28800     // 'A' means EAX + EDX.
28801     if (Constraint == "A") {
28802       Res.first = X86::EAX;
28803       Res.second = &X86::GR32_ADRegClass;
28804       return Res;
28805     }
28806     return Res;
28807   }
28808
28809   // Otherwise, check to see if this is a register class of the wrong value
28810   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28811   // turn into {ax},{dx}.
28812   // MVT::Other is used to specify clobber names.
28813   if (Res.second->hasType(VT) || VT == MVT::Other)
28814     return Res;   // Correct type already, nothing to do.
28815
28816   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28817   // return "eax". This should even work for things like getting 64bit integer
28818   // registers when given an f64 type.
28819   const TargetRegisterClass *Class = Res.second;
28820   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28821       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28822     unsigned Size = VT.getSizeInBits();
28823     if (Size == 1) Size = 8;
28824     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
28825     if (DestReg > 0) {
28826       Res.first = DestReg;
28827       Res.second = Size == 8 ? &X86::GR8RegClass
28828                  : Size == 16 ? &X86::GR16RegClass
28829                  : Size == 32 ? &X86::GR32RegClass
28830                  : &X86::GR64RegClass;
28831       assert(Res.second->contains(Res.first) && "Register in register class");
28832     } else {
28833       // No register found/type mismatch.
28834       Res.first = 0;
28835       Res.second = nullptr;
28836     }
28837   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28838              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28839              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28840              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28841              Class == &X86::VR512RegClass) {
28842     // Handle references to XMM physical registers that got mapped into the
28843     // wrong class.  This can happen with constraints like {xmm0} where the
28844     // target independent register mapper will just pick the first match it can
28845     // find, ignoring the required type.
28846
28847     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28848     if (VT == MVT::f32 || VT == MVT::i32)
28849       Res.second = &X86::FR32RegClass;
28850     else if (VT == MVT::f64 || VT == MVT::i64)
28851       Res.second = &X86::FR64RegClass;
28852     else if (X86::VR128RegClass.hasType(VT))
28853       Res.second = &X86::VR128RegClass;
28854     else if (X86::VR256RegClass.hasType(VT))
28855       Res.second = &X86::VR256RegClass;
28856     else if (X86::VR512RegClass.hasType(VT))
28857       Res.second = &X86::VR512RegClass;
28858     else {
28859       // Type mismatch and not a clobber: Return an error;
28860       Res.first = 0;
28861       Res.second = nullptr;
28862     }
28863   }
28864
28865   return Res;
28866 }
28867
28868 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28869                                             const AddrMode &AM, Type *Ty,
28870                                             unsigned AS) const {
28871   // Scaling factors are not free at all.
28872   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28873   // will take 2 allocations in the out of order engine instead of 1
28874   // for plain addressing mode, i.e. inst (reg1).
28875   // E.g.,
28876   // vaddps (%rsi,%drx), %ymm0, %ymm1
28877   // Requires two allocations (one for the load, one for the computation)
28878   // whereas:
28879   // vaddps (%rsi), %ymm0, %ymm1
28880   // Requires just 1 allocation, i.e., freeing allocations for other operations
28881   // and having less micro operations to execute.
28882   //
28883   // For some X86 architectures, this is even worse because for instance for
28884   // stores, the complex addressing mode forces the instruction to use the
28885   // "load" ports instead of the dedicated "store" port.
28886   // E.g., on Haswell:
28887   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28888   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28889   if (isLegalAddressingMode(DL, AM, Ty, AS))
28890     // Scale represents reg2 * scale, thus account for 1
28891     // as soon as we use a second register.
28892     return AM.Scale != 0;
28893   return -1;
28894 }
28895
28896 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28897   // Integer division on x86 is expensive. However, when aggressively optimizing
28898   // for code size, we prefer to use a div instruction, as it is usually smaller
28899   // than the alternative sequence.
28900   // The exception to this is vector division. Since x86 doesn't have vector
28901   // integer division, leaving the division as-is is a loss even in terms of
28902   // size, because it will have to be scalarized, while the alternative code
28903   // sequence can be performed in vector form.
28904   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28905                                    Attribute::MinSize);
28906   return OptSize && !VT.isVector();
28907 }
28908
28909 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
28910   if (!Subtarget->is64Bit())
28911     return;
28912
28913   // Update IsSplitCSR in X86MachineFunctionInfo.
28914   X86MachineFunctionInfo *AFI =
28915     Entry->getParent()->getInfo<X86MachineFunctionInfo>();
28916   AFI->setIsSplitCSR(true);
28917 }
28918
28919 void X86TargetLowering::insertCopiesSplitCSR(
28920     MachineBasicBlock *Entry,
28921     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
28922   const X86RegisterInfo *TRI = Subtarget->getRegisterInfo();
28923   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
28924   if (!IStart)
28925     return;
28926
28927   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
28928   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
28929   MachineBasicBlock::iterator MBBI = Entry->begin();
28930   for (const MCPhysReg *I = IStart; *I; ++I) {
28931     const TargetRegisterClass *RC = nullptr;
28932     if (X86::GR64RegClass.contains(*I))
28933       RC = &X86::GR64RegClass;
28934     else
28935       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
28936
28937     unsigned NewVR = MRI->createVirtualRegister(RC);
28938     // Create copy from CSR to a virtual register.
28939     // FIXME: this currently does not emit CFI pseudo-instructions, it works
28940     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
28941     // nounwind. If we want to generalize this later, we may need to emit
28942     // CFI pseudo-instructions.
28943     assert(Entry->getParent()->getFunction()->hasFnAttribute(
28944                Attribute::NoUnwind) &&
28945            "Function should be nounwind in insertCopiesSplitCSR!");
28946     Entry->addLiveIn(*I);
28947     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
28948         .addReg(*I);
28949
28950     // Insert the copy-back instructions right before the terminator.
28951     for (auto *Exit : Exits)
28952       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
28953               TII->get(TargetOpcode::COPY), *I)
28954           .addReg(NewVR);
28955   }
28956 }