[X86] Determine if we have an OpaqueSPAdjustment earlier
[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   }
269
270   // Scalar integer divide and remainder are lowered to use operations that
271   // produce two results, to match the available instructions. This exposes
272   // the two-result form to trivial CSE, which is able to combine x/y and x%y
273   // into a single instruction.
274   //
275   // Scalar integer multiply-high is also lowered to use two-result
276   // operations, to match the available instructions. However, plain multiply
277   // (low) operations are left as Legal, as there are single-result
278   // instructions for this in x86. Using the two-result multiply instructions
279   // when both high and low results are needed must be arranged by dagcombine.
280   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
281     setOperationAction(ISD::MULHS, VT, Expand);
282     setOperationAction(ISD::MULHU, VT, Expand);
283     setOperationAction(ISD::SDIV, VT, Expand);
284     setOperationAction(ISD::UDIV, VT, Expand);
285     setOperationAction(ISD::SREM, VT, Expand);
286     setOperationAction(ISD::UREM, VT, Expand);
287
288     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
289     setOperationAction(ISD::ADDC, VT, Custom);
290     setOperationAction(ISD::ADDE, VT, Custom);
291     setOperationAction(ISD::SUBC, VT, Custom);
292     setOperationAction(ISD::SUBE, VT, Custom);
293   }
294
295   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
296   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
297   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
299   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::f128,  Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
302   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
303   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f128,  Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
313   if (Subtarget->is64Bit())
314     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
315   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
316   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
318   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
319
320   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
321     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
322     // is. We should promote the value to 64-bits to solve this.
323     // This is what the CRT headers do - `fmodf` is an inline header
324     // function casting to f64 and calling `fmod`.
325     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
326   } else {
327     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
328   }
329
330   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
331   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
332   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
333
334   // Promote the i8 variants and force them on up to i32 which has a shorter
335   // encoding.
336   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
337   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
338   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
339   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
340   if (Subtarget->hasBMI()) {
341     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
342     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
343     if (Subtarget->is64Bit())
344       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
345   } else {
346     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
347     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
348     if (Subtarget->is64Bit())
349       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
350   }
351
352   if (Subtarget->hasLZCNT()) {
353     // When promoting the i8 variants, force them to i32 for a shorter
354     // encoding.
355     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
356     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
357     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
358     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
361     if (Subtarget->is64Bit())
362       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
363   } else {
364     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
365     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
366     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
367     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
368     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
369     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
370     if (Subtarget->is64Bit()) {
371       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
372       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
373     }
374   }
375
376   // Special handling for half-precision floating point conversions.
377   // If we don't have F16C support, then lower half float conversions
378   // into library calls.
379   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
380     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
381     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
382   }
383
384   // There's never any support for operations beyond MVT::f32.
385   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
386   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
387   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
388   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
389
390   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
391   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
392   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
393   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
394   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
395   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
396
397   if (Subtarget->hasPOPCNT()) {
398     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
399   } else {
400     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
401     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
402     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
403     if (Subtarget->is64Bit())
404       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
405   }
406
407   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
408
409   if (!Subtarget->hasMOVBE())
410     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
411
412   // These should be promoted to a larger select which is supported.
413   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
414   // X86 wants to expand cmov itself.
415   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
416   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
417   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
418   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
419   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
420   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
421   setOperationAction(ISD::SELECT          , MVT::f128 , Custom);
422   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
423   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
424   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
425   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
427   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
428   setOperationAction(ISD::SETCC           , MVT::f128 , Custom);
429   setOperationAction(ISD::SETCCE          , MVT::i8   , Custom);
430   setOperationAction(ISD::SETCCE          , MVT::i16  , Custom);
431   setOperationAction(ISD::SETCCE          , MVT::i32  , Custom);
432   if (Subtarget->is64Bit()) {
433     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
434     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
435     setOperationAction(ISD::SETCCE        , MVT::i64  , Custom);
436   }
437   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
438   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
439   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
440   // support continuation, user-level threading, and etc.. As a result, no
441   // other SjLj exception interfaces are implemented and please don't build
442   // your own exception handling based on them.
443   // LLVM/Clang supports zero-cost DWARF exception handling.
444   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
445   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
446
447   // Darwin ABI issue.
448   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
449   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
450   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
451   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
452   if (Subtarget->is64Bit())
453     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
454   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
455   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
456   if (Subtarget->is64Bit()) {
457     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
458     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
459     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
460     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
461     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
462   }
463   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
464   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
465   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
466   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
467   if (Subtarget->is64Bit()) {
468     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
469     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
470     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
471   }
472
473   if (Subtarget->hasSSE1())
474     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
475
476   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
477
478   // Expand certain atomics
479   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
480     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
481     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
482     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
483   }
484
485   if (Subtarget->hasCmpxchg16b()) {
486     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
487   }
488
489   // FIXME - use subtarget debug flags
490   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
491       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
492     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
493   }
494
495   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
496   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
497
498   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
499   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
500
501   setOperationAction(ISD::TRAP, MVT::Other, Legal);
502   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
503
504   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
505   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
506   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
507   if (Subtarget->is64Bit()) {
508     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
509     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
510   } else {
511     // TargetInfo::CharPtrBuiltinVaList
512     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
513     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
514   }
515
516   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
517   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
518
519   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
520
521   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
522   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
523   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
524
525   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
526     // f32 and f64 use SSE.
527     // Set up the FP register classes.
528     addRegisterClass(MVT::f32, &X86::FR32RegClass);
529     addRegisterClass(MVT::f64, &X86::FR64RegClass);
530
531     // Use ANDPD to simulate FABS.
532     setOperationAction(ISD::FABS , MVT::f64, Custom);
533     setOperationAction(ISD::FABS , MVT::f32, Custom);
534
535     // Use XORP to simulate FNEG.
536     setOperationAction(ISD::FNEG , MVT::f64, Custom);
537     setOperationAction(ISD::FNEG , MVT::f32, Custom);
538
539     // Use ANDPD and ORPD to simulate FCOPYSIGN.
540     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
541     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
542
543     // Lower this to FGETSIGNx86 plus an AND.
544     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
545     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
546
547     // We don't support sin/cos/fmod
548     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
549     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
550     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
551     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
552     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
553     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
554
555     // Expand FP immediates into loads from the stack, except for the special
556     // cases we handle.
557     addLegalFPImmediate(APFloat(+0.0)); // xorpd
558     addLegalFPImmediate(APFloat(+0.0f)); // xorps
559   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
560     // Use SSE for f32, x87 for f64.
561     // Set up the FP register classes.
562     addRegisterClass(MVT::f32, &X86::FR32RegClass);
563     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
564
565     // Use ANDPS to simulate FABS.
566     setOperationAction(ISD::FABS , MVT::f32, Custom);
567
568     // Use XORP to simulate FNEG.
569     setOperationAction(ISD::FNEG , MVT::f32, Custom);
570
571     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
572
573     // Use ANDPS and ORPS to simulate FCOPYSIGN.
574     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
575     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
576
577     // We don't support sin/cos/fmod
578     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
579     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
580     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
581
582     // Special cases we handle for FP constants.
583     addLegalFPImmediate(APFloat(+0.0f)); // xorps
584     addLegalFPImmediate(APFloat(+0.0)); // FLD0
585     addLegalFPImmediate(APFloat(+1.0)); // FLD1
586     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
587     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
588
589     if (!TM.Options.UnsafeFPMath) {
590       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
591       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
592       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
593     }
594   } else if (!Subtarget->useSoftFloat()) {
595     // f32 and f64 in x87.
596     // Set up the FP register classes.
597     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
598     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
599
600     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
601     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
602     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
604
605     if (!TM.Options.UnsafeFPMath) {
606       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
607       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
608       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
609       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
610       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
611       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
612     }
613     addLegalFPImmediate(APFloat(+0.0)); // FLD0
614     addLegalFPImmediate(APFloat(+1.0)); // FLD1
615     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
616     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
617     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
618     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
619     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
620     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
621   }
622
623   // We don't support FMA.
624   setOperationAction(ISD::FMA, MVT::f64, Expand);
625   setOperationAction(ISD::FMA, MVT::f32, Expand);
626
627   // Long double always uses X87, except f128 in MMX.
628   if (!Subtarget->useSoftFloat()) {
629     if (Subtarget->is64Bit() && Subtarget->hasMMX()) {
630       addRegisterClass(MVT::f128, &X86::FR128RegClass);
631       ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
632       setOperationAction(ISD::FABS , MVT::f128, Custom);
633       setOperationAction(ISD::FNEG , MVT::f128, Custom);
634       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
635     }
636
637     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
638     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
639     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
640     {
641       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
642       addLegalFPImmediate(TmpFlt);  // FLD0
643       TmpFlt.changeSign();
644       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
645
646       bool ignored;
647       APFloat TmpFlt2(+1.0);
648       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
649                       &ignored);
650       addLegalFPImmediate(TmpFlt2);  // FLD1
651       TmpFlt2.changeSign();
652       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
653     }
654
655     if (!TM.Options.UnsafeFPMath) {
656       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
657       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
658       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
659     }
660
661     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
662     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
663     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
664     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
665     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
666     setOperationAction(ISD::FMA, MVT::f80, Expand);
667   }
668
669   // Always use a library call for pow.
670   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
671   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
672   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
673
674   setOperationAction(ISD::FLOG, MVT::f80, Expand);
675   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
676   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
677   setOperationAction(ISD::FEXP, MVT::f80, Expand);
678   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
679   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
680   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
681
682   // First set operation action for all vector types to either promote
683   // (for widening) or expand (for scalarization). Then we will selectively
684   // turn on ones that can be effectively codegen'd.
685   for (MVT VT : MVT::vector_valuetypes()) {
686     setOperationAction(ISD::ADD , VT, Expand);
687     setOperationAction(ISD::SUB , VT, Expand);
688     setOperationAction(ISD::FADD, VT, Expand);
689     setOperationAction(ISD::FNEG, VT, Expand);
690     setOperationAction(ISD::FSUB, VT, Expand);
691     setOperationAction(ISD::MUL , VT, Expand);
692     setOperationAction(ISD::FMUL, VT, Expand);
693     setOperationAction(ISD::SDIV, VT, Expand);
694     setOperationAction(ISD::UDIV, VT, Expand);
695     setOperationAction(ISD::FDIV, VT, Expand);
696     setOperationAction(ISD::SREM, VT, Expand);
697     setOperationAction(ISD::UREM, VT, Expand);
698     setOperationAction(ISD::LOAD, VT, Expand);
699     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
700     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
701     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
702     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
703     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
704     setOperationAction(ISD::FABS, VT, Expand);
705     setOperationAction(ISD::FSIN, VT, Expand);
706     setOperationAction(ISD::FSINCOS, VT, Expand);
707     setOperationAction(ISD::FCOS, VT, Expand);
708     setOperationAction(ISD::FSINCOS, VT, Expand);
709     setOperationAction(ISD::FREM, VT, Expand);
710     setOperationAction(ISD::FMA,  VT, Expand);
711     setOperationAction(ISD::FPOWI, VT, Expand);
712     setOperationAction(ISD::FSQRT, VT, Expand);
713     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
714     setOperationAction(ISD::FFLOOR, VT, Expand);
715     setOperationAction(ISD::FCEIL, VT, Expand);
716     setOperationAction(ISD::FTRUNC, VT, Expand);
717     setOperationAction(ISD::FRINT, VT, Expand);
718     setOperationAction(ISD::FNEARBYINT, VT, Expand);
719     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
720     setOperationAction(ISD::MULHS, VT, Expand);
721     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
722     setOperationAction(ISD::MULHU, VT, Expand);
723     setOperationAction(ISD::SDIVREM, VT, Expand);
724     setOperationAction(ISD::UDIVREM, VT, Expand);
725     setOperationAction(ISD::FPOW, VT, Expand);
726     setOperationAction(ISD::CTPOP, VT, Expand);
727     setOperationAction(ISD::CTTZ, VT, Expand);
728     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
729     setOperationAction(ISD::CTLZ, VT, Expand);
730     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
731     setOperationAction(ISD::SHL, VT, Expand);
732     setOperationAction(ISD::SRA, VT, Expand);
733     setOperationAction(ISD::SRL, VT, Expand);
734     setOperationAction(ISD::ROTL, VT, Expand);
735     setOperationAction(ISD::ROTR, VT, Expand);
736     setOperationAction(ISD::BSWAP, VT, Expand);
737     setOperationAction(ISD::SETCC, VT, Expand);
738     setOperationAction(ISD::FLOG, VT, Expand);
739     setOperationAction(ISD::FLOG2, VT, Expand);
740     setOperationAction(ISD::FLOG10, VT, Expand);
741     setOperationAction(ISD::FEXP, VT, Expand);
742     setOperationAction(ISD::FEXP2, VT, Expand);
743     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
744     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
745     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
746     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
747     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
748     setOperationAction(ISD::TRUNCATE, VT, Expand);
749     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
750     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
751     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
752     setOperationAction(ISD::VSELECT, VT, Expand);
753     setOperationAction(ISD::SELECT_CC, VT, Expand);
754     for (MVT InnerVT : MVT::vector_valuetypes()) {
755       setTruncStoreAction(InnerVT, VT, Expand);
756
757       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
758       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
759
760       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
761       // types, we have to deal with them whether we ask for Expansion or not.
762       // Setting Expand causes its own optimisation problems though, so leave
763       // them legal.
764       if (VT.getVectorElementType() == MVT::i1)
765         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
766
767       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
768       // split/scalarized right now.
769       if (VT.getVectorElementType() == MVT::f16)
770         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
771     }
772   }
773
774   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
775   // with -msoft-float, disable use of MMX as well.
776   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
777     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
778     // No operations on x86mmx supported, everything uses intrinsics.
779   }
780
781   // MMX-sized vectors (other than x86mmx) are expected to be expanded
782   // into smaller operations.
783   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
784     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
785     setOperationAction(ISD::AND,                MMXTy,      Expand);
786     setOperationAction(ISD::OR,                 MMXTy,      Expand);
787     setOperationAction(ISD::XOR,                MMXTy,      Expand);
788     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
789     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
790     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
791   }
792   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
793
794   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
795     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
796
797     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
798     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
801     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
802     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
803     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
804     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
805     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
806     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
807     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
808     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
809     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
810     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
811   }
812
813   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
814     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
815
816     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
817     // registers cannot be used even for integer operations.
818     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
819     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
820     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
821     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
822
823     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
824     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
825     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
826     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
827     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
828     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
829     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
830     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
831     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
832     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
833     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
834     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
835     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
836     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
837     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
838     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
839     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
840     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
841     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
842     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
843     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
844     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
845     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
846
847     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
848     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
849     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
850     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
851
852     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
853     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
854     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
855     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
856
857     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
858     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
859     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
860     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
861     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
862
863     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
864     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
865     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
866     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
867
868     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
869     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
870     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
871     // ISD::CTTZ v2i64 - scalarization is faster.
872     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
873     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
874     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
875     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
876
877     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
878     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
879       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
880       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
881       setOperationAction(ISD::VSELECT,            VT, Custom);
882       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
883     }
884
885     // We support custom legalizing of sext and anyext loads for specific
886     // memory vector types which we can load as a scalar (or sequence of
887     // scalars) and extend in-register to a legal 128-bit vector type. For sext
888     // loads these must work with a single scalar load.
889     for (MVT VT : MVT::integer_vector_valuetypes()) {
890       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
891       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
892       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
893       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
894       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
895       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
896       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
897       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
898       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
899     }
900
901     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
902     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
903     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
904     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
905     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
906     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
907     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
908     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
909
910     if (Subtarget->is64Bit()) {
911       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
912       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
913     }
914
915     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
916     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
917       setOperationAction(ISD::AND,    VT, Promote);
918       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
919       setOperationAction(ISD::OR,     VT, Promote);
920       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
921       setOperationAction(ISD::XOR,    VT, Promote);
922       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
923       setOperationAction(ISD::LOAD,   VT, Promote);
924       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
925       setOperationAction(ISD::SELECT, VT, Promote);
926       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
927     }
928
929     // Custom lower v2i64 and v2f64 selects.
930     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
931     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
932     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
933     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
934
935     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
936     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
937
938     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
939
940     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
941     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
942     // As there is no 64-bit GPR available, we need build a special custom
943     // sequence to convert from v2i32 to v2f32.
944     if (!Subtarget->is64Bit())
945       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
946
947     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
948     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
949
950     for (MVT VT : MVT::fp_vector_valuetypes())
951       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
952
953     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
954     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
955     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
956   }
957
958   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
959     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
960       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
961       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
962       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
963       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
964       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
965     }
966
967     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
968     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
969     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
970     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
971     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
972     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
973     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
974     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
975
976     // FIXME: Do we need to handle scalar-to-vector here?
977     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
978
979     // We directly match byte blends in the backend as they match the VSELECT
980     // condition form.
981     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
982
983     // SSE41 brings specific instructions for doing vector sign extend even in
984     // cases where we don't have SRA.
985     for (MVT VT : MVT::integer_vector_valuetypes()) {
986       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
987       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
988       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
989     }
990
991     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
992     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
993     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
994     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
995     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
996     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
997     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
998
999     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1000     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1001     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1002     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1003     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1004     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1005
1006     // i8 and i16 vectors are custom because the source register and source
1007     // source memory operand types are not the same width.  f32 vectors are
1008     // custom since the immediate controlling the insert encodes additional
1009     // information.
1010     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1011     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1012     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1013     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1014
1015     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1016     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1017     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1018     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1019
1020     // FIXME: these should be Legal, but that's only for the case where
1021     // the index is constant.  For now custom expand to deal with that.
1022     if (Subtarget->is64Bit()) {
1023       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1024       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1025     }
1026   }
1027
1028   if (Subtarget->hasSSE2()) {
1029     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1030     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1031     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1032
1033     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1034     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1035
1036     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1037     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1038
1039     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1040     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1041
1042     // In the customized shift lowering, the legal cases in AVX2 will be
1043     // recognized.
1044     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1045     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1046
1047     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1048     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1049
1050     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1051     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1052   }
1053
1054   if (Subtarget->hasXOP()) {
1055     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1056     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1057     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1058     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1059     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1060     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1061     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1062     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1063   }
1064
1065   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1066     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1067     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1068     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1069     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1070     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1071     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1072
1073     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1074     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1075     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1076
1077     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1078     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1079     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1080     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1081     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1082     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1083     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1084     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1085     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1086     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1087     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1088     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1089
1090     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1091     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1092     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1093     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1094     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1095     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1096     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1097     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1098     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1099     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1100     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1101     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1102
1103     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1104     // even though v8i16 is a legal type.
1105     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1106     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1107     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1108
1109     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1110     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1111     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1112
1113     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1114     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1115
1116     for (MVT VT : MVT::fp_vector_valuetypes())
1117       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1118
1119     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1120     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1121
1122     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1123     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1124
1125     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1126     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1127
1128     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1129     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1130     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1131     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1132
1133     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1134     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1135     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1136
1137     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1138     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1139     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1140     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1141     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1142     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1143     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1144     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1145     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1146     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1147     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1148     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1149
1150     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1151     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1152     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1153     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1154
1155     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1156     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1157     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1158     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1159     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1160     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1161     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1162     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1163
1164     if (Subtarget->hasAnyFMA()) {
1165       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1166       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1167       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1168       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1169       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1170       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1171     }
1172
1173     if (Subtarget->hasInt256()) {
1174       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1175       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1176       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1177       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1178
1179       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1180       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1181       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1182       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1183
1184       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1185       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1186       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1187       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1188
1189       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1190       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1191       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1192       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1193
1194       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1195       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1196       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1197       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1198       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1199       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1200       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1201       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1202       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1203       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1204       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1205       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1206
1207       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1208       // when we have a 256bit-wide blend with immediate.
1209       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1210
1211       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1212       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1213       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1214       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1215       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1216       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1217       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1218
1219       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1220       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1221       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1222       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1223       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1224       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1225     } else {
1226       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1227       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1228       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1229       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1230
1231       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1232       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1233       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1234       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1235
1236       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1237       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1238       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1239       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1240
1241       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1242       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1243       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1244       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1245       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1246       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1247       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1248       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1249       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1250       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1251       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1252       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1253     }
1254
1255     // In the customized shift lowering, the legal cases in AVX2 will be
1256     // recognized.
1257     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1258     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1259
1260     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1261     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1262
1263     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1264     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1265
1266     // Custom lower several nodes for 256-bit types.
1267     for (MVT VT : MVT::vector_valuetypes()) {
1268       if (VT.getScalarSizeInBits() >= 32) {
1269         setOperationAction(ISD::MLOAD,  VT, Legal);
1270         setOperationAction(ISD::MSTORE, VT, Legal);
1271       }
1272       // Extract subvector is special because the value type
1273       // (result) is 128-bit but the source is 256-bit wide.
1274       if (VT.is128BitVector()) {
1275         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1276       }
1277       // Do not attempt to custom lower other non-256-bit vectors
1278       if (!VT.is256BitVector())
1279         continue;
1280
1281       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1282       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1283       setOperationAction(ISD::VSELECT,            VT, Custom);
1284       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1285       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1286       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1287       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1288       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1289     }
1290
1291     if (Subtarget->hasInt256())
1292       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1293
1294     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1295     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1296       setOperationAction(ISD::AND,    VT, Promote);
1297       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1298       setOperationAction(ISD::OR,     VT, Promote);
1299       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1300       setOperationAction(ISD::XOR,    VT, Promote);
1301       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1302       setOperationAction(ISD::LOAD,   VT, Promote);
1303       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1304       setOperationAction(ISD::SELECT, VT, Promote);
1305       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1306     }
1307   }
1308
1309   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1310     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1311     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1312     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1313     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1314
1315     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1316     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1317     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1318
1319     for (MVT VT : MVT::fp_vector_valuetypes())
1320       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1321
1322     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1323     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1324     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1325     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1326     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1327     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1328     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1329     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1330     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1331     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1332     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1333     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1334
1335     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1336     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1337     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1338     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1339     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1340     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1341     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1342     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1343     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1344     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1345     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1346     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1347     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1348     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1349
1350     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1351     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1352     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1353     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1354     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1355     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1356     setOperationAction(ISD::FABS,               MVT::v16f32, Custom);
1357
1358     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1359     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1360     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1361     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1362     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1363     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1364     setOperationAction(ISD::FABS,               MVT::v8f64, Custom);
1365     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1366     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1367
1368     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1369     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1370     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1371     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1372     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1373     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1374     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1375     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1376     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1377     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1378     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1379     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1380     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1381     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1382     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1383     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1384
1385     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1386     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1387     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1388     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1389     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1390     if (Subtarget->hasVLX()){
1391       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1392       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1393       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1394       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1395       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1396
1397       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1398       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1399       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1400       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1401       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1402     } else {
1403       setOperationAction(ISD::MLOAD,    MVT::v8i32, Custom);
1404       setOperationAction(ISD::MLOAD,    MVT::v8f32, Custom);
1405       setOperationAction(ISD::MSTORE,   MVT::v8i32, Custom);
1406       setOperationAction(ISD::MSTORE,   MVT::v8f32, Custom);
1407     }
1408     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1409     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1410     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1411     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1412     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1413     if (Subtarget->hasDQI()) {
1414       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1415       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1416
1417       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1418       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1419       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1420       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1421       if (Subtarget->hasVLX()) {
1422         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1423         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1424         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1425         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1426         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1427         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1428         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1429         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1430       }
1431     }
1432     if (Subtarget->hasVLX()) {
1433       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1434       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1435       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1436       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1437       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1438       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1439       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1440       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1441     }
1442     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1443     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1444     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1445     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1446     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1447     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1448     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1449     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1450     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1451     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1452     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1453     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1454     if (Subtarget->hasDQI()) {
1455       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1456       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1457     }
1458     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1459     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1460     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1461     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1462     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1463     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1464     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1465     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1466     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1467     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1468
1469     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1470     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1471     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1472     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1473     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1,   Custom);
1474
1475     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1476     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1477
1478     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1479
1480     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1481     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1482     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v16i1, Custom);
1483     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1484     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1485     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1486     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1487     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1488     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1489     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1490     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1491     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1492
1493     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1494     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1495     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1496     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1497     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1498     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1499     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1500     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1501
1502     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1503     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1504
1505     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1506     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1507
1508     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1509
1510     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1511     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1512
1513     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1514     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1515
1516     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1517     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1518
1519     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1520     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1521     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1522     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1523     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1524     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1525
1526     if (Subtarget->hasCDI()) {
1527       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1528       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1529       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Expand);
1530       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Expand);
1531
1532       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1533       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1534       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1535       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1536       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Expand);
1537       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Expand);
1538       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Expand);
1539       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Expand);
1540
1541       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1542       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1543
1544       if (Subtarget->hasVLX()) {
1545         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1546         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1547         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1548         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1549         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Expand);
1550         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Expand);
1551         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Expand);
1552         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Expand);
1553
1554         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1555         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1556         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1557         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1558       } else {
1559         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1560         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1561         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1562         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1563         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Expand);
1564         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Expand);
1565         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Expand);
1566         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Expand);
1567       }
1568     } // Subtarget->hasCDI()
1569
1570     if (Subtarget->hasDQI()) {
1571       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1572       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1573       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1574     }
1575     // Custom lower several nodes.
1576     for (MVT VT : MVT::vector_valuetypes()) {
1577       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1578       if (EltSize == 1) {
1579         setOperationAction(ISD::AND, VT, Legal);
1580         setOperationAction(ISD::OR,  VT, Legal);
1581         setOperationAction(ISD::XOR,  VT, Legal);
1582       }
1583       if ((VT.is128BitVector() || VT.is256BitVector()) && EltSize >= 32) {
1584         setOperationAction(ISD::MGATHER,  VT, Custom);
1585         setOperationAction(ISD::MSCATTER, VT, Custom);
1586       }
1587       // Extract subvector is special because the value type
1588       // (result) is 256/128-bit but the source is 512-bit wide.
1589       if (VT.is128BitVector() || VT.is256BitVector()) {
1590         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1591       }
1592       if (VT.getVectorElementType() == MVT::i1)
1593         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1594
1595       // Do not attempt to custom lower other non-512-bit vectors
1596       if (!VT.is512BitVector())
1597         continue;
1598
1599       if (EltSize >= 32) {
1600         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1601         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1602         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1603         setOperationAction(ISD::VSELECT,             VT, Legal);
1604         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1605         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1606         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1607         setOperationAction(ISD::MLOAD,               VT, Legal);
1608         setOperationAction(ISD::MSTORE,              VT, Legal);
1609         setOperationAction(ISD::MGATHER,  VT, Legal);
1610         setOperationAction(ISD::MSCATTER, VT, Custom);
1611       }
1612     }
1613     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1614       setOperationAction(ISD::SELECT, VT, Promote);
1615       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1616     }
1617   }// has  AVX-512
1618
1619   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1620     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1621     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1622
1623     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1624     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1625
1626     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1627     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1628     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1629     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1630     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1631     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1632     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1633     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1634     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1635     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1636     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1637     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1638     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1639     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1640     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1641     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1642     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1643     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1644     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1645     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1646     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1647     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1648     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1649     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1650     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1651     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1652     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1653     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1654     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1655     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1656     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1657     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1658     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1659     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1660     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1661     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1662     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1663     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1664     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1665     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1666     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1667     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1668
1669     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1670     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1671     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1672     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1673     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1674     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1675     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1676     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1677
1678     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1679     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1680     if (Subtarget->hasVLX())
1681       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1682
1683     if (Subtarget->hasCDI()) {
1684       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1685       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1686       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Expand);
1687       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Expand);
1688     }
1689
1690     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1691       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1692       setOperationAction(ISD::VSELECT,             VT, Legal);
1693       setOperationAction(ISD::SRL,                 VT, Custom);
1694       setOperationAction(ISD::SHL,                 VT, Custom);
1695       setOperationAction(ISD::SRA,                 VT, Custom);
1696
1697       setOperationAction(ISD::AND,    VT, Promote);
1698       AddPromotedToType (ISD::AND,    VT, MVT::v8i64);
1699       setOperationAction(ISD::OR,     VT, Promote);
1700       AddPromotedToType (ISD::OR,     VT, MVT::v8i64);
1701       setOperationAction(ISD::XOR,    VT, Promote);
1702       AddPromotedToType (ISD::XOR,    VT, MVT::v8i64);
1703     }
1704   }
1705
1706   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1707     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1708     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1709
1710     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1711     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1712     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1713     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1714     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1715     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1716     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1717     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1718     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1719     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1720     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1721     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1722
1723     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1724     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1725     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1726     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1727     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1728     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1729     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1730     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1731
1732     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1733     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1734     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1735     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1736     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1737     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1738     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1739     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1740   }
1741
1742   // We want to custom lower some of our intrinsics.
1743   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1744   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1745   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1746   if (!Subtarget->is64Bit()) {
1747     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1748     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1749   }
1750
1751   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1752   // handle type legalization for these operations here.
1753   //
1754   // FIXME: We really should do custom legalization for addition and
1755   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1756   // than generic legalization for 64-bit multiplication-with-overflow, though.
1757   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1758     if (VT == MVT::i64 && !Subtarget->is64Bit())
1759       continue;
1760     // Add/Sub/Mul with overflow operations are custom lowered.
1761     setOperationAction(ISD::SADDO, VT, Custom);
1762     setOperationAction(ISD::UADDO, VT, Custom);
1763     setOperationAction(ISD::SSUBO, VT, Custom);
1764     setOperationAction(ISD::USUBO, VT, Custom);
1765     setOperationAction(ISD::SMULO, VT, Custom);
1766     setOperationAction(ISD::UMULO, VT, Custom);
1767   }
1768
1769   if (!Subtarget->is64Bit()) {
1770     // These libcalls are not available in 32-bit.
1771     setLibcallName(RTLIB::SHL_I128, nullptr);
1772     setLibcallName(RTLIB::SRL_I128, nullptr);
1773     setLibcallName(RTLIB::SRA_I128, nullptr);
1774   }
1775
1776   // Combine sin / cos into one node or libcall if possible.
1777   if (Subtarget->hasSinCos()) {
1778     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1779     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1780     if (Subtarget->isTargetDarwin()) {
1781       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1782       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1783       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1784       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1785     }
1786   }
1787
1788   if (Subtarget->isTargetWin64()) {
1789     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1790     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1791     setOperationAction(ISD::SREM, MVT::i128, Custom);
1792     setOperationAction(ISD::UREM, MVT::i128, Custom);
1793     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1794     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1795   }
1796
1797   // We have target-specific dag combine patterns for the following nodes:
1798   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1799   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1800   setTargetDAGCombine(ISD::BITCAST);
1801   setTargetDAGCombine(ISD::VSELECT);
1802   setTargetDAGCombine(ISD::SELECT);
1803   setTargetDAGCombine(ISD::SHL);
1804   setTargetDAGCombine(ISD::SRA);
1805   setTargetDAGCombine(ISD::SRL);
1806   setTargetDAGCombine(ISD::OR);
1807   setTargetDAGCombine(ISD::AND);
1808   setTargetDAGCombine(ISD::ADD);
1809   setTargetDAGCombine(ISD::FADD);
1810   setTargetDAGCombine(ISD::FSUB);
1811   setTargetDAGCombine(ISD::FNEG);
1812   setTargetDAGCombine(ISD::FMA);
1813   setTargetDAGCombine(ISD::FMINNUM);
1814   setTargetDAGCombine(ISD::FMAXNUM);
1815   setTargetDAGCombine(ISD::SUB);
1816   setTargetDAGCombine(ISD::LOAD);
1817   setTargetDAGCombine(ISD::MLOAD);
1818   setTargetDAGCombine(ISD::STORE);
1819   setTargetDAGCombine(ISD::MSTORE);
1820   setTargetDAGCombine(ISD::TRUNCATE);
1821   setTargetDAGCombine(ISD::ZERO_EXTEND);
1822   setTargetDAGCombine(ISD::ANY_EXTEND);
1823   setTargetDAGCombine(ISD::SIGN_EXTEND);
1824   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1825   setTargetDAGCombine(ISD::SINT_TO_FP);
1826   setTargetDAGCombine(ISD::UINT_TO_FP);
1827   setTargetDAGCombine(ISD::SETCC);
1828   setTargetDAGCombine(ISD::BUILD_VECTOR);
1829   setTargetDAGCombine(ISD::MUL);
1830   setTargetDAGCombine(ISD::XOR);
1831   setTargetDAGCombine(ISD::MSCATTER);
1832   setTargetDAGCombine(ISD::MGATHER);
1833
1834   computeRegisterProperties(Subtarget->getRegisterInfo());
1835
1836   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1837   MaxStoresPerMemsetOptSize = 8;
1838   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1839   MaxStoresPerMemcpyOptSize = 4;
1840   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1841   MaxStoresPerMemmoveOptSize = 4;
1842   setPrefLoopAlignment(4); // 2^4 bytes.
1843
1844   // A predictable cmov does not hurt on an in-order CPU.
1845   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1846   PredictableSelectIsExpensive = !Subtarget->isAtom();
1847   EnableExtLdPromotion = true;
1848   setPrefFunctionAlignment(4); // 2^4 bytes.
1849
1850   verifyIntrinsicTables();
1851 }
1852
1853 // This has so far only been implemented for 64-bit MachO.
1854 bool X86TargetLowering::useLoadStackGuardNode() const {
1855   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1856 }
1857
1858 TargetLoweringBase::LegalizeTypeAction
1859 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1860   if (ExperimentalVectorWideningLegalization &&
1861       VT.getVectorNumElements() != 1 &&
1862       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1863     return TypeWidenVector;
1864
1865   return TargetLoweringBase::getPreferredVectorAction(VT);
1866 }
1867
1868 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1869                                           EVT VT) const {
1870   if (!VT.isVector())
1871     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1872
1873   if (VT.isSimple()) {
1874     MVT VVT = VT.getSimpleVT();
1875     const unsigned NumElts = VVT.getVectorNumElements();
1876     const MVT EltVT = VVT.getVectorElementType();
1877     if (VVT.is512BitVector()) {
1878       if (Subtarget->hasAVX512())
1879         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1880             EltVT == MVT::f32 || EltVT == MVT::f64)
1881           switch(NumElts) {
1882           case  8: return MVT::v8i1;
1883           case 16: return MVT::v16i1;
1884         }
1885       if (Subtarget->hasBWI())
1886         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1887           switch(NumElts) {
1888           case 32: return MVT::v32i1;
1889           case 64: return MVT::v64i1;
1890         }
1891     }
1892
1893     if (VVT.is256BitVector() || VVT.is128BitVector()) {
1894       if (Subtarget->hasVLX())
1895         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1896             EltVT == MVT::f32 || EltVT == MVT::f64)
1897           switch(NumElts) {
1898           case 2: return MVT::v2i1;
1899           case 4: return MVT::v4i1;
1900           case 8: return MVT::v8i1;
1901         }
1902       if (Subtarget->hasBWI() && Subtarget->hasVLX())
1903         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1904           switch(NumElts) {
1905           case  8: return MVT::v8i1;
1906           case 16: return MVT::v16i1;
1907           case 32: return MVT::v32i1;
1908         }
1909     }
1910   }
1911
1912   return VT.changeVectorElementTypeToInteger();
1913 }
1914
1915 /// Helper for getByValTypeAlignment to determine
1916 /// the desired ByVal argument alignment.
1917 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1918   if (MaxAlign == 16)
1919     return;
1920   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1921     if (VTy->getBitWidth() == 128)
1922       MaxAlign = 16;
1923   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1924     unsigned EltAlign = 0;
1925     getMaxByValAlign(ATy->getElementType(), EltAlign);
1926     if (EltAlign > MaxAlign)
1927       MaxAlign = EltAlign;
1928   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1929     for (auto *EltTy : STy->elements()) {
1930       unsigned EltAlign = 0;
1931       getMaxByValAlign(EltTy, EltAlign);
1932       if (EltAlign > MaxAlign)
1933         MaxAlign = EltAlign;
1934       if (MaxAlign == 16)
1935         break;
1936     }
1937   }
1938 }
1939
1940 /// Return the desired alignment for ByVal aggregate
1941 /// function arguments in the caller parameter area. For X86, aggregates
1942 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1943 /// are at 4-byte boundaries.
1944 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1945                                                   const DataLayout &DL) const {
1946   if (Subtarget->is64Bit()) {
1947     // Max of 8 and alignment of type.
1948     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1949     if (TyAlign > 8)
1950       return TyAlign;
1951     return 8;
1952   }
1953
1954   unsigned Align = 4;
1955   if (Subtarget->hasSSE1())
1956     getMaxByValAlign(Ty, Align);
1957   return Align;
1958 }
1959
1960 /// Returns the target specific optimal type for load
1961 /// and store operations as a result of memset, memcpy, and memmove
1962 /// lowering. If DstAlign is zero that means it's safe to destination
1963 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1964 /// means there isn't a need to check it against alignment requirement,
1965 /// probably because the source does not need to be loaded. If 'IsMemset' is
1966 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1967 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1968 /// source is constant so it does not need to be loaded.
1969 /// It returns EVT::Other if the type should be determined using generic
1970 /// target-independent logic.
1971 EVT
1972 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1973                                        unsigned DstAlign, unsigned SrcAlign,
1974                                        bool IsMemset, bool ZeroMemset,
1975                                        bool MemcpyStrSrc,
1976                                        MachineFunction &MF) const {
1977   const Function *F = MF.getFunction();
1978   if ((!IsMemset || ZeroMemset) &&
1979       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1980     if (Size >= 16 &&
1981         (!Subtarget->isUnalignedMem16Slow() ||
1982          ((DstAlign == 0 || DstAlign >= 16) &&
1983           (SrcAlign == 0 || SrcAlign >= 16)))) {
1984       if (Size >= 32) {
1985         // FIXME: Check if unaligned 32-byte accesses are slow.
1986         if (Subtarget->hasInt256())
1987           return MVT::v8i32;
1988         if (Subtarget->hasFp256())
1989           return MVT::v8f32;
1990       }
1991       if (Subtarget->hasSSE2())
1992         return MVT::v4i32;
1993       if (Subtarget->hasSSE1())
1994         return MVT::v4f32;
1995     } else if (!MemcpyStrSrc && Size >= 8 &&
1996                !Subtarget->is64Bit() &&
1997                Subtarget->hasSSE2()) {
1998       // Do not use f64 to lower memcpy if source is string constant. It's
1999       // better to use i32 to avoid the loads.
2000       return MVT::f64;
2001     }
2002   }
2003   // This is a compromise. If we reach here, unaligned accesses may be slow on
2004   // this target. However, creating smaller, aligned accesses could be even
2005   // slower and would certainly be a lot more code.
2006   if (Subtarget->is64Bit() && Size >= 8)
2007     return MVT::i64;
2008   return MVT::i32;
2009 }
2010
2011 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2012   if (VT == MVT::f32)
2013     return X86ScalarSSEf32;
2014   else if (VT == MVT::f64)
2015     return X86ScalarSSEf64;
2016   return true;
2017 }
2018
2019 bool
2020 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2021                                                   unsigned,
2022                                                   unsigned,
2023                                                   bool *Fast) const {
2024   if (Fast) {
2025     switch (VT.getSizeInBits()) {
2026     default:
2027       // 8-byte and under are always assumed to be fast.
2028       *Fast = true;
2029       break;
2030     case 128:
2031       *Fast = !Subtarget->isUnalignedMem16Slow();
2032       break;
2033     case 256:
2034       *Fast = !Subtarget->isUnalignedMem32Slow();
2035       break;
2036     // TODO: What about AVX-512 (512-bit) accesses?
2037     }
2038   }
2039   // Misaligned accesses of any size are always allowed.
2040   return true;
2041 }
2042
2043 /// Return the entry encoding for a jump table in the
2044 /// current function.  The returned value is a member of the
2045 /// MachineJumpTableInfo::JTEntryKind enum.
2046 unsigned X86TargetLowering::getJumpTableEncoding() const {
2047   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2048   // symbol.
2049   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2050       Subtarget->isPICStyleGOT())
2051     return MachineJumpTableInfo::EK_Custom32;
2052
2053   // Otherwise, use the normal jump table encoding heuristics.
2054   return TargetLowering::getJumpTableEncoding();
2055 }
2056
2057 bool X86TargetLowering::useSoftFloat() const {
2058   return Subtarget->useSoftFloat();
2059 }
2060
2061 const MCExpr *
2062 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2063                                              const MachineBasicBlock *MBB,
2064                                              unsigned uid,MCContext &Ctx) const{
2065   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2066          Subtarget->isPICStyleGOT());
2067   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2068   // entries.
2069   return MCSymbolRefExpr::create(MBB->getSymbol(),
2070                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2071 }
2072
2073 /// Returns relocation base for the given PIC jumptable.
2074 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2075                                                     SelectionDAG &DAG) const {
2076   if (!Subtarget->is64Bit())
2077     // This doesn't have SDLoc associated with it, but is not really the
2078     // same as a Register.
2079     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2080                        getPointerTy(DAG.getDataLayout()));
2081   return Table;
2082 }
2083
2084 /// This returns the relocation base for the given PIC jumptable,
2085 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2086 const MCExpr *X86TargetLowering::
2087 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2088                              MCContext &Ctx) const {
2089   // X86-64 uses RIP relative addressing based on the jump table label.
2090   if (Subtarget->isPICStyleRIPRel())
2091     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2092
2093   // Otherwise, the reference is relative to the PIC base.
2094   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2095 }
2096
2097 std::pair<const TargetRegisterClass *, uint8_t>
2098 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2099                                            MVT VT) const {
2100   const TargetRegisterClass *RRC = nullptr;
2101   uint8_t Cost = 1;
2102   switch (VT.SimpleTy) {
2103   default:
2104     return TargetLowering::findRepresentativeClass(TRI, VT);
2105   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2106     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2107     break;
2108   case MVT::x86mmx:
2109     RRC = &X86::VR64RegClass;
2110     break;
2111   case MVT::f32: case MVT::f64:
2112   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2113   case MVT::v4f32: case MVT::v2f64:
2114   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2115   case MVT::v4f64:
2116     RRC = &X86::VR128RegClass;
2117     break;
2118   }
2119   return std::make_pair(RRC, Cost);
2120 }
2121
2122 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2123                                                unsigned &Offset) const {
2124   if (!Subtarget->isTargetLinux())
2125     return false;
2126
2127   if (Subtarget->is64Bit()) {
2128     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2129     Offset = 0x28;
2130     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2131       AddressSpace = 256;
2132     else
2133       AddressSpace = 257;
2134   } else {
2135     // %gs:0x14 on i386
2136     Offset = 0x14;
2137     AddressSpace = 256;
2138   }
2139   return true;
2140 }
2141
2142 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2143   if (!Subtarget->isTargetAndroid())
2144     return TargetLowering::getSafeStackPointerLocation(IRB);
2145
2146   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2147   // definition of TLS_SLOT_SAFESTACK in
2148   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2149   unsigned AddressSpace, Offset;
2150   if (Subtarget->is64Bit()) {
2151     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2152     Offset = 0x48;
2153     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2154       AddressSpace = 256;
2155     else
2156       AddressSpace = 257;
2157   } else {
2158     // %gs:0x24 on i386
2159     Offset = 0x24;
2160     AddressSpace = 256;
2161   }
2162
2163   return ConstantExpr::getIntToPtr(
2164       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2165       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2166 }
2167
2168 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2169                                             unsigned DestAS) const {
2170   assert(SrcAS != DestAS && "Expected different address spaces!");
2171
2172   return SrcAS < 256 && DestAS < 256;
2173 }
2174
2175 //===----------------------------------------------------------------------===//
2176 //               Return Value Calling Convention Implementation
2177 //===----------------------------------------------------------------------===//
2178
2179 #include "X86GenCallingConv.inc"
2180
2181 bool X86TargetLowering::CanLowerReturn(
2182     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2183     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2184   SmallVector<CCValAssign, 16> RVLocs;
2185   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2186   return CCInfo.CheckReturn(Outs, RetCC_X86);
2187 }
2188
2189 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2190   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2191   return ScratchRegs;
2192 }
2193
2194 SDValue
2195 X86TargetLowering::LowerReturn(SDValue Chain,
2196                                CallingConv::ID CallConv, bool isVarArg,
2197                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2198                                const SmallVectorImpl<SDValue> &OutVals,
2199                                SDLoc dl, SelectionDAG &DAG) const {
2200   MachineFunction &MF = DAG.getMachineFunction();
2201   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2202
2203   if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2204     report_fatal_error("X86 interrupts may not return any value");
2205
2206   SmallVector<CCValAssign, 16> RVLocs;
2207   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2208   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2209
2210   SDValue Flag;
2211   SmallVector<SDValue, 6> RetOps;
2212   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2213   // Operand #1 = Bytes To Pop
2214   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2215                    MVT::i16));
2216
2217   // Copy the result values into the output registers.
2218   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2219     CCValAssign &VA = RVLocs[i];
2220     assert(VA.isRegLoc() && "Can only return in registers!");
2221     SDValue ValToCopy = OutVals[i];
2222     EVT ValVT = ValToCopy.getValueType();
2223
2224     // Promote values to the appropriate types.
2225     if (VA.getLocInfo() == CCValAssign::SExt)
2226       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2227     else if (VA.getLocInfo() == CCValAssign::ZExt)
2228       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2229     else if (VA.getLocInfo() == CCValAssign::AExt) {
2230       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2231         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2232       else
2233         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2234     }
2235     else if (VA.getLocInfo() == CCValAssign::BCvt)
2236       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2237
2238     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2239            "Unexpected FP-extend for return value.");
2240
2241     // If this is x86-64, and we disabled SSE, we can't return FP values,
2242     // or SSE or MMX vectors.
2243     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2244          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2245           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2246       report_fatal_error("SSE register return with SSE disabled");
2247     }
2248     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2249     // llvm-gcc has never done it right and no one has noticed, so this
2250     // should be OK for now.
2251     if (ValVT == MVT::f64 &&
2252         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2253       report_fatal_error("SSE2 register return with SSE2 disabled");
2254
2255     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2256     // the RET instruction and handled by the FP Stackifier.
2257     if (VA.getLocReg() == X86::FP0 ||
2258         VA.getLocReg() == X86::FP1) {
2259       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2260       // change the value to the FP stack register class.
2261       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2262         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2263       RetOps.push_back(ValToCopy);
2264       // Don't emit a copytoreg.
2265       continue;
2266     }
2267
2268     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2269     // which is returned in RAX / RDX.
2270     if (Subtarget->is64Bit()) {
2271       if (ValVT == MVT::x86mmx) {
2272         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2273           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2274           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2275                                   ValToCopy);
2276           // If we don't have SSE2 available, convert to v4f32 so the generated
2277           // register is legal.
2278           if (!Subtarget->hasSSE2())
2279             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2280         }
2281       }
2282     }
2283
2284     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2285     Flag = Chain.getValue(1);
2286     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2287   }
2288
2289   // All x86 ABIs require that for returning structs by value we copy
2290   // the sret argument into %rax/%eax (depending on ABI) for the return.
2291   // We saved the argument into a virtual register in the entry block,
2292   // so now we copy the value out and into %rax/%eax.
2293   //
2294   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2295   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2296   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2297   // either case FuncInfo->setSRetReturnReg() will have been called.
2298   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2299     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2300                                      getPointerTy(MF.getDataLayout()));
2301
2302     unsigned RetValReg
2303         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2304           X86::RAX : X86::EAX;
2305     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2306     Flag = Chain.getValue(1);
2307
2308     // RAX/EAX now acts like a return value.
2309     RetOps.push_back(
2310         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2311   }
2312
2313   RetOps[0] = Chain;  // Update chain.
2314
2315   // Add the flag if we have it.
2316   if (Flag.getNode())
2317     RetOps.push_back(Flag);
2318
2319   X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2320   if (CallConv == CallingConv::X86_INTR)
2321     opcode = X86ISD::IRET;
2322   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2323 }
2324
2325 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2326   if (N->getNumValues() != 1)
2327     return false;
2328   if (!N->hasNUsesOfValue(1, 0))
2329     return false;
2330
2331   SDValue TCChain = Chain;
2332   SDNode *Copy = *N->use_begin();
2333   if (Copy->getOpcode() == ISD::CopyToReg) {
2334     // If the copy has a glue operand, we conservatively assume it isn't safe to
2335     // perform a tail call.
2336     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2337       return false;
2338     TCChain = Copy->getOperand(0);
2339   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2340     return false;
2341
2342   bool HasRet = false;
2343   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2344        UI != UE; ++UI) {
2345     if (UI->getOpcode() != X86ISD::RET_FLAG)
2346       return false;
2347     // If we are returning more than one value, we can definitely
2348     // not make a tail call see PR19530
2349     if (UI->getNumOperands() > 4)
2350       return false;
2351     if (UI->getNumOperands() == 4 &&
2352         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2353       return false;
2354     HasRet = true;
2355   }
2356
2357   if (!HasRet)
2358     return false;
2359
2360   Chain = TCChain;
2361   return true;
2362 }
2363
2364 EVT
2365 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2366                                             ISD::NodeType ExtendKind) const {
2367   MVT ReturnMVT;
2368   // TODO: Is this also valid on 32-bit?
2369   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2370     ReturnMVT = MVT::i8;
2371   else
2372     ReturnMVT = MVT::i32;
2373
2374   EVT MinVT = getRegisterType(Context, ReturnMVT);
2375   return VT.bitsLT(MinVT) ? MinVT : VT;
2376 }
2377
2378 /// Lower the result values of a call into the
2379 /// appropriate copies out of appropriate physical registers.
2380 ///
2381 SDValue
2382 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2383                                    CallingConv::ID CallConv, bool isVarArg,
2384                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2385                                    SDLoc dl, SelectionDAG &DAG,
2386                                    SmallVectorImpl<SDValue> &InVals) const {
2387
2388   // Assign locations to each value returned by this call.
2389   SmallVector<CCValAssign, 16> RVLocs;
2390   bool Is64Bit = Subtarget->is64Bit();
2391   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2392                  *DAG.getContext());
2393   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2394
2395   // Copy all of the result registers out of their specified physreg.
2396   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2397     CCValAssign &VA = RVLocs[i];
2398     EVT CopyVT = VA.getLocVT();
2399
2400     // If this is x86-64, and we disabled SSE, we can't return FP values
2401     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2402         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2403       report_fatal_error("SSE register return with SSE disabled");
2404     }
2405
2406     // If we prefer to use the value in xmm registers, copy it out as f80 and
2407     // use a truncate to move it from fp stack reg to xmm reg.
2408     bool RoundAfterCopy = false;
2409     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2410         isScalarFPTypeInSSEReg(VA.getValVT())) {
2411       CopyVT = MVT::f80;
2412       RoundAfterCopy = (CopyVT != VA.getLocVT());
2413     }
2414
2415     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2416                                CopyVT, InFlag).getValue(1);
2417     SDValue Val = Chain.getValue(0);
2418
2419     if (RoundAfterCopy)
2420       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2421                         // This truncation won't change the value.
2422                         DAG.getIntPtrConstant(1, dl));
2423
2424     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2425       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2426
2427     InFlag = Chain.getValue(2);
2428     InVals.push_back(Val);
2429   }
2430
2431   return Chain;
2432 }
2433
2434 //===----------------------------------------------------------------------===//
2435 //                C & StdCall & Fast Calling Convention implementation
2436 //===----------------------------------------------------------------------===//
2437 //  StdCall calling convention seems to be standard for many Windows' API
2438 //  routines and around. It differs from C calling convention just a little:
2439 //  callee should clean up the stack, not caller. Symbols should be also
2440 //  decorated in some fancy way :) It doesn't support any vector arguments.
2441 //  For info on fast calling convention see Fast Calling Convention (tail call)
2442 //  implementation LowerX86_32FastCCCallTo.
2443
2444 /// CallIsStructReturn - Determines whether a call uses struct return
2445 /// semantics.
2446 enum StructReturnType {
2447   NotStructReturn,
2448   RegStructReturn,
2449   StackStructReturn
2450 };
2451 static StructReturnType
2452 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsMCU) {
2453   if (Outs.empty())
2454     return NotStructReturn;
2455
2456   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2457   if (!Flags.isSRet())
2458     return NotStructReturn;
2459   if (Flags.isInReg() || IsMCU)
2460     return RegStructReturn;
2461   return StackStructReturn;
2462 }
2463
2464 /// Determines whether a function uses struct return semantics.
2465 static StructReturnType
2466 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsMCU) {
2467   if (Ins.empty())
2468     return NotStructReturn;
2469
2470   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2471   if (!Flags.isSRet())
2472     return NotStructReturn;
2473   if (Flags.isInReg() || IsMCU)
2474     return RegStructReturn;
2475   return StackStructReturn;
2476 }
2477
2478 /// Make a copy of an aggregate at address specified by "Src" to address
2479 /// "Dst" with size and alignment information specified by the specific
2480 /// parameter attribute. The copy will be passed as a byval function parameter.
2481 static SDValue
2482 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2483                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2484                           SDLoc dl) {
2485   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2486
2487   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2488                        /*isVolatile*/false, /*AlwaysInline=*/true,
2489                        /*isTailCall*/false,
2490                        MachinePointerInfo(), MachinePointerInfo());
2491 }
2492
2493 /// Return true if the calling convention is one that we can guarantee TCO for.
2494 static bool canGuaranteeTCO(CallingConv::ID CC) {
2495   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2496           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2497 }
2498
2499 /// Return true if we might ever do TCO for calls with this calling convention.
2500 static bool mayTailCallThisCC(CallingConv::ID CC) {
2501   switch (CC) {
2502   // C calling conventions:
2503   case CallingConv::C:
2504   case CallingConv::X86_64_Win64:
2505   case CallingConv::X86_64_SysV:
2506   // Callee pop conventions:
2507   case CallingConv::X86_ThisCall:
2508   case CallingConv::X86_StdCall:
2509   case CallingConv::X86_VectorCall:
2510   case CallingConv::X86_FastCall:
2511     return true;
2512   default:
2513     return canGuaranteeTCO(CC);
2514   }
2515 }
2516
2517 /// Return true if the function is being made into a tailcall target by
2518 /// changing its ABI.
2519 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2520   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2521 }
2522
2523 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2524   auto Attr =
2525       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2526   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2527     return false;
2528
2529   CallSite CS(CI);
2530   CallingConv::ID CalleeCC = CS.getCallingConv();
2531   if (!mayTailCallThisCC(CalleeCC))
2532     return false;
2533
2534   return true;
2535 }
2536
2537 SDValue
2538 X86TargetLowering::LowerMemArgument(SDValue Chain,
2539                                     CallingConv::ID CallConv,
2540                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2541                                     SDLoc dl, SelectionDAG &DAG,
2542                                     const CCValAssign &VA,
2543                                     MachineFrameInfo *MFI,
2544                                     unsigned i) const {
2545   // Create the nodes corresponding to a load from this parameter slot.
2546   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2547   bool AlwaysUseMutable = shouldGuaranteeTCO(
2548       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2549   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2550   EVT ValVT;
2551
2552   // If value is passed by pointer we have address passed instead of the value
2553   // itself.
2554   bool ExtendedInMem = VA.isExtInLoc() &&
2555     VA.getValVT().getScalarType() == MVT::i1;
2556
2557   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2558     ValVT = VA.getLocVT();
2559   else
2560     ValVT = VA.getValVT();
2561
2562   // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2563   // taken by a return address.
2564   int Offset = 0;
2565   if (CallConv == CallingConv::X86_INTR) {
2566     const X86Subtarget& Subtarget =
2567         static_cast<const X86Subtarget&>(DAG.getSubtarget());
2568     // X86 interrupts may take one or two arguments.
2569     // On the stack there will be no return address as in regular call.
2570     // Offset of last argument need to be set to -4/-8 bytes.
2571     // Where offset of the first argument out of two, should be set to 0 bytes.
2572     Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2573   }
2574
2575   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2576   // changed with more analysis.
2577   // In case of tail call optimization mark all arguments mutable. Since they
2578   // could be overwritten by lowering of arguments in case of a tail call.
2579   if (Flags.isByVal()) {
2580     unsigned Bytes = Flags.getByValSize();
2581     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2582     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2583     // Adjust SP offset of interrupt parameter.
2584     if (CallConv == CallingConv::X86_INTR) {
2585       MFI->setObjectOffset(FI, Offset);
2586     }
2587     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2588   } else {
2589     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2590                                     VA.getLocMemOffset(), isImmutable);
2591     // Adjust SP offset of interrupt parameter.
2592     if (CallConv == CallingConv::X86_INTR) {
2593       MFI->setObjectOffset(FI, Offset);
2594     }
2595
2596     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2597     SDValue Val = DAG.getLoad(
2598         ValVT, dl, Chain, FIN,
2599         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2600         false, false, 0);
2601     return ExtendedInMem ?
2602       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2603   }
2604 }
2605
2606 // FIXME: Get this from tablegen.
2607 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2608                                                 const X86Subtarget *Subtarget) {
2609   assert(Subtarget->is64Bit());
2610
2611   if (Subtarget->isCallingConvWin64(CallConv)) {
2612     static const MCPhysReg GPR64ArgRegsWin64[] = {
2613       X86::RCX, X86::RDX, X86::R8,  X86::R9
2614     };
2615     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2616   }
2617
2618   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2619     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2620   };
2621   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2622 }
2623
2624 // FIXME: Get this from tablegen.
2625 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2626                                                 CallingConv::ID CallConv,
2627                                                 const X86Subtarget *Subtarget) {
2628   assert(Subtarget->is64Bit());
2629   if (Subtarget->isCallingConvWin64(CallConv)) {
2630     // The XMM registers which might contain var arg parameters are shadowed
2631     // in their paired GPR.  So we only need to save the GPR to their home
2632     // slots.
2633     // TODO: __vectorcall will change this.
2634     return None;
2635   }
2636
2637   const Function *Fn = MF.getFunction();
2638   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2639   bool isSoftFloat = Subtarget->useSoftFloat();
2640   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2641          "SSE register cannot be used when SSE is disabled!");
2642   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2643     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2644     // registers.
2645     return None;
2646
2647   static const MCPhysReg XMMArgRegs64Bit[] = {
2648     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2649     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2650   };
2651   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2652 }
2653
2654 SDValue X86TargetLowering::LowerFormalArguments(
2655     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2656     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2657     SmallVectorImpl<SDValue> &InVals) const {
2658   MachineFunction &MF = DAG.getMachineFunction();
2659   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2660   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2661
2662   const Function* Fn = MF.getFunction();
2663   if (Fn->hasExternalLinkage() &&
2664       Subtarget->isTargetCygMing() &&
2665       Fn->getName() == "main")
2666     FuncInfo->setForceFramePointer(true);
2667
2668   MachineFrameInfo *MFI = MF.getFrameInfo();
2669   bool Is64Bit = Subtarget->is64Bit();
2670   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2671
2672   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2673          "Var args not supported with calling convention fastcc, ghc or hipe");
2674
2675   if (CallConv == CallingConv::X86_INTR) {
2676     bool isLegal = Ins.size() == 1 ||
2677                    (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2678                                         (!Is64Bit && Ins[1].VT == MVT::i32)));
2679     if (!isLegal)
2680       report_fatal_error("X86 interrupts may take one or two arguments");
2681   }
2682
2683   // Assign locations to all of the incoming arguments.
2684   SmallVector<CCValAssign, 16> ArgLocs;
2685   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2686
2687   // Allocate shadow area for Win64
2688   if (IsWin64)
2689     CCInfo.AllocateStack(32, 8);
2690
2691   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2692
2693   unsigned LastVal = ~0U;
2694   SDValue ArgValue;
2695   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2696     CCValAssign &VA = ArgLocs[i];
2697     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2698     // places.
2699     assert(VA.getValNo() != LastVal &&
2700            "Don't support value assigned to multiple locs yet");
2701     (void)LastVal;
2702     LastVal = VA.getValNo();
2703
2704     if (VA.isRegLoc()) {
2705       EVT RegVT = VA.getLocVT();
2706       const TargetRegisterClass *RC;
2707       if (RegVT == MVT::i32)
2708         RC = &X86::GR32RegClass;
2709       else if (Is64Bit && RegVT == MVT::i64)
2710         RC = &X86::GR64RegClass;
2711       else if (RegVT == MVT::f32)
2712         RC = &X86::FR32RegClass;
2713       else if (RegVT == MVT::f64)
2714         RC = &X86::FR64RegClass;
2715       else if (RegVT == MVT::f128)
2716         RC = &X86::FR128RegClass;
2717       else if (RegVT.is512BitVector())
2718         RC = &X86::VR512RegClass;
2719       else if (RegVT.is256BitVector())
2720         RC = &X86::VR256RegClass;
2721       else if (RegVT.is128BitVector())
2722         RC = &X86::VR128RegClass;
2723       else if (RegVT == MVT::x86mmx)
2724         RC = &X86::VR64RegClass;
2725       else if (RegVT == MVT::i1)
2726         RC = &X86::VK1RegClass;
2727       else if (RegVT == MVT::v8i1)
2728         RC = &X86::VK8RegClass;
2729       else if (RegVT == MVT::v16i1)
2730         RC = &X86::VK16RegClass;
2731       else if (RegVT == MVT::v32i1)
2732         RC = &X86::VK32RegClass;
2733       else if (RegVT == MVT::v64i1)
2734         RC = &X86::VK64RegClass;
2735       else
2736         llvm_unreachable("Unknown argument type!");
2737
2738       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2739       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2740
2741       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2742       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2743       // right size.
2744       if (VA.getLocInfo() == CCValAssign::SExt)
2745         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2746                                DAG.getValueType(VA.getValVT()));
2747       else if (VA.getLocInfo() == CCValAssign::ZExt)
2748         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2749                                DAG.getValueType(VA.getValVT()));
2750       else if (VA.getLocInfo() == CCValAssign::BCvt)
2751         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2752
2753       if (VA.isExtInLoc()) {
2754         // Handle MMX values passed in XMM regs.
2755         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2756           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2757         else
2758           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2759       }
2760     } else {
2761       assert(VA.isMemLoc());
2762       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2763     }
2764
2765     // If value is passed via pointer - do a load.
2766     if (VA.getLocInfo() == CCValAssign::Indirect)
2767       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2768                              MachinePointerInfo(), false, false, false, 0);
2769
2770     InVals.push_back(ArgValue);
2771   }
2772
2773   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2774     // All x86 ABIs require that for returning structs by value we copy the
2775     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2776     // the argument into a virtual register so that we can access it from the
2777     // return points.
2778     if (Ins[i].Flags.isSRet()) {
2779       unsigned Reg = FuncInfo->getSRetReturnReg();
2780       if (!Reg) {
2781         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2782         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2783         FuncInfo->setSRetReturnReg(Reg);
2784       }
2785       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2786       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2787       break;
2788     }
2789   }
2790
2791   unsigned StackSize = CCInfo.getNextStackOffset();
2792   // Align stack specially for tail calls.
2793   if (shouldGuaranteeTCO(CallConv,
2794                          MF.getTarget().Options.GuaranteedTailCallOpt))
2795     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2796
2797   // If the function takes variable number of arguments, make a frame index for
2798   // the start of the first vararg value... for expansion of llvm.va_start. We
2799   // can skip this if there are no va_start calls.
2800   if (MFI->hasVAStart() &&
2801       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2802                    CallConv != CallingConv::X86_ThisCall))) {
2803     FuncInfo->setVarArgsFrameIndex(
2804         MFI->CreateFixedObject(1, StackSize, true));
2805   }
2806
2807   // Figure out if XMM registers are in use.
2808   assert(!(Subtarget->useSoftFloat() &&
2809            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2810          "SSE register cannot be used when SSE is disabled!");
2811
2812   // 64-bit calling conventions support varargs and register parameters, so we
2813   // have to do extra work to spill them in the prologue.
2814   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2815     // Find the first unallocated argument registers.
2816     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2817     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2818     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2819     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2820     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2821            "SSE register cannot be used when SSE is disabled!");
2822
2823     // Gather all the live in physical registers.
2824     SmallVector<SDValue, 6> LiveGPRs;
2825     SmallVector<SDValue, 8> LiveXMMRegs;
2826     SDValue ALVal;
2827     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2828       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2829       LiveGPRs.push_back(
2830           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2831     }
2832     if (!ArgXMMs.empty()) {
2833       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2834       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2835       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2836         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2837         LiveXMMRegs.push_back(
2838             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2839       }
2840     }
2841
2842     if (IsWin64) {
2843       // Get to the caller-allocated home save location.  Add 8 to account
2844       // for the return address.
2845       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2846       FuncInfo->setRegSaveFrameIndex(
2847           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2848       // Fixup to set vararg frame on shadow area (4 x i64).
2849       if (NumIntRegs < 4)
2850         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2851     } else {
2852       // For X86-64, if there are vararg parameters that are passed via
2853       // registers, then we must store them to their spots on the stack so
2854       // they may be loaded by deferencing the result of va_next.
2855       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2856       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2857       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2858           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2859     }
2860
2861     // Store the integer parameter registers.
2862     SmallVector<SDValue, 8> MemOps;
2863     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2864                                       getPointerTy(DAG.getDataLayout()));
2865     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2866     for (SDValue Val : LiveGPRs) {
2867       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2868                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2869       SDValue Store =
2870           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2871                        MachinePointerInfo::getFixedStack(
2872                            DAG.getMachineFunction(),
2873                            FuncInfo->getRegSaveFrameIndex(), Offset),
2874                        false, false, 0);
2875       MemOps.push_back(Store);
2876       Offset += 8;
2877     }
2878
2879     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2880       // Now store the XMM (fp + vector) parameter registers.
2881       SmallVector<SDValue, 12> SaveXMMOps;
2882       SaveXMMOps.push_back(Chain);
2883       SaveXMMOps.push_back(ALVal);
2884       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2885                              FuncInfo->getRegSaveFrameIndex(), dl));
2886       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2887                              FuncInfo->getVarArgsFPOffset(), dl));
2888       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2889                         LiveXMMRegs.end());
2890       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2891                                    MVT::Other, SaveXMMOps));
2892     }
2893
2894     if (!MemOps.empty())
2895       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2896   }
2897
2898   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2899     // Find the largest legal vector type.
2900     MVT VecVT = MVT::Other;
2901     // FIXME: Only some x86_32 calling conventions support AVX512.
2902     if (Subtarget->hasAVX512() &&
2903         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2904                      CallConv == CallingConv::Intel_OCL_BI)))
2905       VecVT = MVT::v16f32;
2906     else if (Subtarget->hasAVX())
2907       VecVT = MVT::v8f32;
2908     else if (Subtarget->hasSSE2())
2909       VecVT = MVT::v4f32;
2910
2911     // We forward some GPRs and some vector types.
2912     SmallVector<MVT, 2> RegParmTypes;
2913     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2914     RegParmTypes.push_back(IntVT);
2915     if (VecVT != MVT::Other)
2916       RegParmTypes.push_back(VecVT);
2917
2918     // Compute the set of forwarded registers. The rest are scratch.
2919     SmallVectorImpl<ForwardedRegister> &Forwards =
2920         FuncInfo->getForwardedMustTailRegParms();
2921     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2922
2923     // Conservatively forward AL on x86_64, since it might be used for varargs.
2924     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2925       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2926       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2927     }
2928
2929     // Copy all forwards from physical to virtual registers.
2930     for (ForwardedRegister &F : Forwards) {
2931       // FIXME: Can we use a less constrained schedule?
2932       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2933       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2934       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2935     }
2936   }
2937
2938   // Some CCs need callee pop.
2939   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2940                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2941     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2942   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
2943     // X86 interrupts must pop the error code if present
2944     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 8 : 4);
2945   } else {
2946     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2947     // If this is an sret function, the return should pop the hidden pointer.
2948     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2949         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2950         argsAreStructReturn(Ins, Subtarget->isTargetMCU()) == StackStructReturn)
2951       FuncInfo->setBytesToPopOnReturn(4);
2952   }
2953
2954   if (!Is64Bit) {
2955     // RegSaveFrameIndex is X86-64 only.
2956     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2957     if (CallConv == CallingConv::X86_FastCall ||
2958         CallConv == CallingConv::X86_ThisCall)
2959       // fastcc functions can't have varargs.
2960       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2961   }
2962
2963   FuncInfo->setArgumentStackSize(StackSize);
2964
2965   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2966     EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2967     if (Personality == EHPersonality::CoreCLR) {
2968       assert(Is64Bit);
2969       // TODO: Add a mechanism to frame lowering that will allow us to indicate
2970       // that we'd prefer this slot be allocated towards the bottom of the frame
2971       // (i.e. near the stack pointer after allocating the frame).  Every
2972       // funclet needs a copy of this slot in its (mostly empty) frame, and the
2973       // offset from the bottom of this and each funclet's frame must be the
2974       // same, so the size of funclets' (mostly empty) frames is dictated by
2975       // how far this slot is from the bottom (since they allocate just enough
2976       // space to accomodate holding this slot at the correct offset).
2977       int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2978       EHInfo->PSPSymFrameIdx = PSPSymFI;
2979     }
2980   }
2981
2982   return Chain;
2983 }
2984
2985 SDValue
2986 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2987                                     SDValue StackPtr, SDValue Arg,
2988                                     SDLoc dl, SelectionDAG &DAG,
2989                                     const CCValAssign &VA,
2990                                     ISD::ArgFlagsTy Flags) const {
2991   unsigned LocMemOffset = VA.getLocMemOffset();
2992   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2993   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2994                        StackPtr, PtrOff);
2995   if (Flags.isByVal())
2996     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2997
2998   return DAG.getStore(
2999       Chain, dl, Arg, PtrOff,
3000       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
3001       false, false, 0);
3002 }
3003
3004 /// Emit a load of return address if tail call
3005 /// optimization is performed and it is required.
3006 SDValue
3007 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
3008                                            SDValue &OutRetAddr, SDValue Chain,
3009                                            bool IsTailCall, bool Is64Bit,
3010                                            int FPDiff, SDLoc dl) const {
3011   // Adjust the Return address stack slot.
3012   EVT VT = getPointerTy(DAG.getDataLayout());
3013   OutRetAddr = getReturnAddressFrameIndex(DAG);
3014
3015   // Load the "old" Return address.
3016   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
3017                            false, false, false, 0);
3018   return SDValue(OutRetAddr.getNode(), 1);
3019 }
3020
3021 /// Emit a store of the return address if tail call
3022 /// optimization is performed and it is required (FPDiff!=0).
3023 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3024                                         SDValue Chain, SDValue RetAddrFrIdx,
3025                                         EVT PtrVT, unsigned SlotSize,
3026                                         int FPDiff, SDLoc dl) {
3027   // Store the return address to the appropriate stack slot.
3028   if (!FPDiff) return Chain;
3029   // Calculate the new stack slot for the return address.
3030   int NewReturnAddrFI =
3031     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3032                                          false);
3033   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3034   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3035                        MachinePointerInfo::getFixedStack(
3036                            DAG.getMachineFunction(), NewReturnAddrFI),
3037                        false, false, 0);
3038   return Chain;
3039 }
3040
3041 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3042 /// operation of specified width.
3043 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
3044                        SDValue V2) {
3045   unsigned NumElems = VT.getVectorNumElements();
3046   SmallVector<int, 8> Mask;
3047   Mask.push_back(NumElems);
3048   for (unsigned i = 1; i != NumElems; ++i)
3049     Mask.push_back(i);
3050   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3051 }
3052
3053 SDValue
3054 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3055                              SmallVectorImpl<SDValue> &InVals) const {
3056   SelectionDAG &DAG                     = CLI.DAG;
3057   SDLoc &dl                             = CLI.DL;
3058   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3059   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3060   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3061   SDValue Chain                         = CLI.Chain;
3062   SDValue Callee                        = CLI.Callee;
3063   CallingConv::ID CallConv              = CLI.CallConv;
3064   bool &isTailCall                      = CLI.IsTailCall;
3065   bool isVarArg                         = CLI.IsVarArg;
3066
3067   MachineFunction &MF = DAG.getMachineFunction();
3068   bool Is64Bit        = Subtarget->is64Bit();
3069   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
3070   StructReturnType SR = callIsStructReturn(Outs, Subtarget->isTargetMCU());
3071   bool IsSibcall      = false;
3072   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3073   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3074
3075   if (CallConv == CallingConv::X86_INTR)
3076     report_fatal_error("X86 interrupts may not be called directly");
3077
3078   if (Attr.getValueAsString() == "true")
3079     isTailCall = false;
3080
3081   if (Subtarget->isPICStyleGOT() &&
3082       !MF.getTarget().Options.GuaranteedTailCallOpt) {
3083     // If we are using a GOT, disable tail calls to external symbols with
3084     // default visibility. Tail calling such a symbol requires using a GOT
3085     // relocation, which forces early binding of the symbol. This breaks code
3086     // that require lazy function symbol resolution. Using musttail or
3087     // GuaranteedTailCallOpt will override this.
3088     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3089     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3090                G->getGlobal()->hasDefaultVisibility()))
3091       isTailCall = false;
3092   }
3093
3094   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3095   if (IsMustTail) {
3096     // Force this to be a tail call.  The verifier rules are enough to ensure
3097     // that we can lower this successfully without moving the return address
3098     // around.
3099     isTailCall = true;
3100   } else if (isTailCall) {
3101     // Check if it's really possible to do a tail call.
3102     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3103                     isVarArg, SR != NotStructReturn,
3104                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3105                     Outs, OutVals, Ins, DAG);
3106
3107     // Sibcalls are automatically detected tailcalls which do not require
3108     // ABI changes.
3109     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3110       IsSibcall = true;
3111
3112     if (isTailCall)
3113       ++NumTailCalls;
3114   }
3115
3116   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3117          "Var args not supported with calling convention fastcc, ghc or hipe");
3118
3119   // Analyze operands of the call, assigning locations to each operand.
3120   SmallVector<CCValAssign, 16> ArgLocs;
3121   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3122
3123   // Allocate shadow area for Win64
3124   if (IsWin64)
3125     CCInfo.AllocateStack(32, 8);
3126
3127   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3128
3129   // Get a count of how many bytes are to be pushed on the stack.
3130   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3131   if (IsSibcall)
3132     // This is a sibcall. The memory operands are available in caller's
3133     // own caller's stack.
3134     NumBytes = 0;
3135   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3136            canGuaranteeTCO(CallConv))
3137     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3138
3139   int FPDiff = 0;
3140   if (isTailCall && !IsSibcall && !IsMustTail) {
3141     // Lower arguments at fp - stackoffset + fpdiff.
3142     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3143
3144     FPDiff = NumBytesCallerPushed - NumBytes;
3145
3146     // Set the delta of movement of the returnaddr stackslot.
3147     // But only set if delta is greater than previous delta.
3148     if (FPDiff < X86Info->getTCReturnAddrDelta())
3149       X86Info->setTCReturnAddrDelta(FPDiff);
3150   }
3151
3152   unsigned NumBytesToPush = NumBytes;
3153   unsigned NumBytesToPop = NumBytes;
3154
3155   // If we have an inalloca argument, all stack space has already been allocated
3156   // for us and be right at the top of the stack.  We don't support multiple
3157   // arguments passed in memory when using inalloca.
3158   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3159     NumBytesToPush = 0;
3160     if (!ArgLocs.back().isMemLoc())
3161       report_fatal_error("cannot use inalloca attribute on a register "
3162                          "parameter");
3163     if (ArgLocs.back().getLocMemOffset() != 0)
3164       report_fatal_error("any parameter with the inalloca attribute must be "
3165                          "the only memory argument");
3166   }
3167
3168   if (!IsSibcall)
3169     Chain = DAG.getCALLSEQ_START(
3170         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3171
3172   SDValue RetAddrFrIdx;
3173   // Load return address for tail calls.
3174   if (isTailCall && FPDiff)
3175     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3176                                     Is64Bit, FPDiff, dl);
3177
3178   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3179   SmallVector<SDValue, 8> MemOpChains;
3180   SDValue StackPtr;
3181
3182   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3183   // of tail call optimization arguments are handle later.
3184   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3185   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3186     // Skip inalloca arguments, they have already been written.
3187     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3188     if (Flags.isInAlloca())
3189       continue;
3190
3191     CCValAssign &VA = ArgLocs[i];
3192     EVT RegVT = VA.getLocVT();
3193     SDValue Arg = OutVals[i];
3194     bool isByVal = Flags.isByVal();
3195
3196     // Promote the value if needed.
3197     switch (VA.getLocInfo()) {
3198     default: llvm_unreachable("Unknown loc info!");
3199     case CCValAssign::Full: break;
3200     case CCValAssign::SExt:
3201       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3202       break;
3203     case CCValAssign::ZExt:
3204       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3205       break;
3206     case CCValAssign::AExt:
3207       if (Arg.getValueType().isVector() &&
3208           Arg.getValueType().getVectorElementType() == MVT::i1)
3209         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3210       else if (RegVT.is128BitVector()) {
3211         // Special case: passing MMX values in XMM registers.
3212         Arg = DAG.getBitcast(MVT::i64, Arg);
3213         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3214         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3215       } else
3216         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3217       break;
3218     case CCValAssign::BCvt:
3219       Arg = DAG.getBitcast(RegVT, Arg);
3220       break;
3221     case CCValAssign::Indirect: {
3222       // Store the argument.
3223       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3224       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3225       Chain = DAG.getStore(
3226           Chain, dl, Arg, SpillSlot,
3227           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3228           false, false, 0);
3229       Arg = SpillSlot;
3230       break;
3231     }
3232     }
3233
3234     if (VA.isRegLoc()) {
3235       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3236       if (isVarArg && IsWin64) {
3237         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3238         // shadow reg if callee is a varargs function.
3239         unsigned ShadowReg = 0;
3240         switch (VA.getLocReg()) {
3241         case X86::XMM0: ShadowReg = X86::RCX; break;
3242         case X86::XMM1: ShadowReg = X86::RDX; break;
3243         case X86::XMM2: ShadowReg = X86::R8; break;
3244         case X86::XMM3: ShadowReg = X86::R9; break;
3245         }
3246         if (ShadowReg)
3247           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3248       }
3249     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3250       assert(VA.isMemLoc());
3251       if (!StackPtr.getNode())
3252         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3253                                       getPointerTy(DAG.getDataLayout()));
3254       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3255                                              dl, DAG, VA, Flags));
3256     }
3257   }
3258
3259   if (!MemOpChains.empty())
3260     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3261
3262   if (Subtarget->isPICStyleGOT()) {
3263     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3264     // GOT pointer.
3265     if (!isTailCall) {
3266       RegsToPass.push_back(std::make_pair(
3267           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3268                                           getPointerTy(DAG.getDataLayout()))));
3269     } else {
3270       // If we are tail calling and generating PIC/GOT style code load the
3271       // address of the callee into ECX. The value in ecx is used as target of
3272       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3273       // for tail calls on PIC/GOT architectures. Normally we would just put the
3274       // address of GOT into ebx and then call target@PLT. But for tail calls
3275       // ebx would be restored (since ebx is callee saved) before jumping to the
3276       // target@PLT.
3277
3278       // Note: The actual moving to ECX is done further down.
3279       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3280       if (G && !G->getGlobal()->hasLocalLinkage() &&
3281           G->getGlobal()->hasDefaultVisibility())
3282         Callee = LowerGlobalAddress(Callee, DAG);
3283       else if (isa<ExternalSymbolSDNode>(Callee))
3284         Callee = LowerExternalSymbol(Callee, DAG);
3285     }
3286   }
3287
3288   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3289     // From AMD64 ABI document:
3290     // For calls that may call functions that use varargs or stdargs
3291     // (prototype-less calls or calls to functions containing ellipsis (...) in
3292     // the declaration) %al is used as hidden argument to specify the number
3293     // of SSE registers used. The contents of %al do not need to match exactly
3294     // the number of registers, but must be an ubound on the number of SSE
3295     // registers used and is in the range 0 - 8 inclusive.
3296
3297     // Count the number of XMM registers allocated.
3298     static const MCPhysReg XMMArgRegs[] = {
3299       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3300       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3301     };
3302     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3303     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3304            && "SSE registers cannot be used when SSE is disabled");
3305
3306     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3307                                         DAG.getConstant(NumXMMRegs, dl,
3308                                                         MVT::i8)));
3309   }
3310
3311   if (isVarArg && IsMustTail) {
3312     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3313     for (const auto &F : Forwards) {
3314       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3315       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3316     }
3317   }
3318
3319   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3320   // don't need this because the eligibility check rejects calls that require
3321   // shuffling arguments passed in memory.
3322   if (!IsSibcall && isTailCall) {
3323     // Force all the incoming stack arguments to be loaded from the stack
3324     // before any new outgoing arguments are stored to the stack, because the
3325     // outgoing stack slots may alias the incoming argument stack slots, and
3326     // the alias isn't otherwise explicit. This is slightly more conservative
3327     // than necessary, because it means that each store effectively depends
3328     // on every argument instead of just those arguments it would clobber.
3329     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3330
3331     SmallVector<SDValue, 8> MemOpChains2;
3332     SDValue FIN;
3333     int FI = 0;
3334     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3335       CCValAssign &VA = ArgLocs[i];
3336       if (VA.isRegLoc())
3337         continue;
3338       assert(VA.isMemLoc());
3339       SDValue Arg = OutVals[i];
3340       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3341       // Skip inalloca arguments.  They don't require any work.
3342       if (Flags.isInAlloca())
3343         continue;
3344       // Create frame index.
3345       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3346       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3347       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3348       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3349
3350       if (Flags.isByVal()) {
3351         // Copy relative to framepointer.
3352         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3353         if (!StackPtr.getNode())
3354           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3355                                         getPointerTy(DAG.getDataLayout()));
3356         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3357                              StackPtr, Source);
3358
3359         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3360                                                          ArgChain,
3361                                                          Flags, DAG, dl));
3362       } else {
3363         // Store relative to framepointer.
3364         MemOpChains2.push_back(DAG.getStore(
3365             ArgChain, dl, Arg, FIN,
3366             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3367             false, false, 0));
3368       }
3369     }
3370
3371     if (!MemOpChains2.empty())
3372       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3373
3374     // Store the return address to the appropriate stack slot.
3375     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3376                                      getPointerTy(DAG.getDataLayout()),
3377                                      RegInfo->getSlotSize(), FPDiff, dl);
3378   }
3379
3380   // Build a sequence of copy-to-reg nodes chained together with token chain
3381   // and flag operands which copy the outgoing args into registers.
3382   SDValue InFlag;
3383   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3384     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3385                              RegsToPass[i].second, InFlag);
3386     InFlag = Chain.getValue(1);
3387   }
3388
3389   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3390     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3391     // In the 64-bit large code model, we have to make all calls
3392     // through a register, since the call instruction's 32-bit
3393     // pc-relative offset may not be large enough to hold the whole
3394     // address.
3395   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3396     // If the callee is a GlobalAddress node (quite common, every direct call
3397     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3398     // it.
3399     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3400
3401     // We should use extra load for direct calls to dllimported functions in
3402     // non-JIT mode.
3403     const GlobalValue *GV = G->getGlobal();
3404     if (!GV->hasDLLImportStorageClass()) {
3405       unsigned char OpFlags = 0;
3406       bool ExtraLoad = false;
3407       unsigned WrapperKind = ISD::DELETED_NODE;
3408
3409       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3410       // external symbols most go through the PLT in PIC mode.  If the symbol
3411       // has hidden or protected visibility, or if it is static or local, then
3412       // we don't need to use the PLT - we can directly call it.
3413       if (Subtarget->isTargetELF() &&
3414           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3415           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3416         OpFlags = X86II::MO_PLT;
3417       } else if (Subtarget->isPICStyleStubAny() &&
3418                  !GV->isStrongDefinitionForLinker() &&
3419                  (!Subtarget->getTargetTriple().isMacOSX() ||
3420                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3421         // PC-relative references to external symbols should go through $stub,
3422         // unless we're building with the leopard linker or later, which
3423         // automatically synthesizes these stubs.
3424         OpFlags = X86II::MO_DARWIN_STUB;
3425       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3426                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3427         // If the function is marked as non-lazy, generate an indirect call
3428         // which loads from the GOT directly. This avoids runtime overhead
3429         // at the cost of eager binding (and one extra byte of encoding).
3430         OpFlags = X86II::MO_GOTPCREL;
3431         WrapperKind = X86ISD::WrapperRIP;
3432         ExtraLoad = true;
3433       }
3434
3435       Callee = DAG.getTargetGlobalAddress(
3436           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3437
3438       // Add a wrapper if needed.
3439       if (WrapperKind != ISD::DELETED_NODE)
3440         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3441                              getPointerTy(DAG.getDataLayout()), Callee);
3442       // Add extra indirection if needed.
3443       if (ExtraLoad)
3444         Callee = DAG.getLoad(
3445             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3446             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3447             false, 0);
3448     }
3449   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3450     unsigned char OpFlags = 0;
3451
3452     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3453     // external symbols should go through the PLT.
3454     if (Subtarget->isTargetELF() &&
3455         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3456       OpFlags = X86II::MO_PLT;
3457     } else if (Subtarget->isPICStyleStubAny() &&
3458                (!Subtarget->getTargetTriple().isMacOSX() ||
3459                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3460       // PC-relative references to external symbols should go through $stub,
3461       // unless we're building with the leopard linker or later, which
3462       // automatically synthesizes these stubs.
3463       OpFlags = X86II::MO_DARWIN_STUB;
3464     }
3465
3466     Callee = DAG.getTargetExternalSymbol(
3467         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3468   } else if (Subtarget->isTarget64BitILP32() &&
3469              Callee->getValueType(0) == MVT::i32) {
3470     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3471     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3472   }
3473
3474   // Returns a chain & a flag for retval copy to use.
3475   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3476   SmallVector<SDValue, 8> Ops;
3477
3478   if (!IsSibcall && isTailCall) {
3479     Chain = DAG.getCALLSEQ_END(Chain,
3480                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3481                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3482     InFlag = Chain.getValue(1);
3483   }
3484
3485   Ops.push_back(Chain);
3486   Ops.push_back(Callee);
3487
3488   if (isTailCall)
3489     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3490
3491   // Add argument registers to the end of the list so that they are known live
3492   // into the call.
3493   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3494     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3495                                   RegsToPass[i].second.getValueType()));
3496
3497   // Add a register mask operand representing the call-preserved registers.
3498   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3499   assert(Mask && "Missing call preserved mask for calling convention");
3500
3501   // If this is an invoke in a 32-bit function using a funclet-based
3502   // personality, assume the function clobbers all registers. If an exception
3503   // is thrown, the runtime will not restore CSRs.
3504   // FIXME: Model this more precisely so that we can register allocate across
3505   // the normal edge and spill and fill across the exceptional edge.
3506   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3507     const Function *CallerFn = MF.getFunction();
3508     EHPersonality Pers =
3509         CallerFn->hasPersonalityFn()
3510             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3511             : EHPersonality::Unknown;
3512     if (isFuncletEHPersonality(Pers))
3513       Mask = RegInfo->getNoPreservedMask();
3514   }
3515
3516   Ops.push_back(DAG.getRegisterMask(Mask));
3517
3518   if (InFlag.getNode())
3519     Ops.push_back(InFlag);
3520
3521   if (isTailCall) {
3522     // We used to do:
3523     //// If this is the first return lowered for this function, add the regs
3524     //// to the liveout set for the function.
3525     // This isn't right, although it's probably harmless on x86; liveouts
3526     // should be computed from returns not tail calls.  Consider a void
3527     // function making a tail call to a function returning int.
3528     MF.getFrameInfo()->setHasTailCall();
3529     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3530   }
3531
3532   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3533   InFlag = Chain.getValue(1);
3534
3535   // Create the CALLSEQ_END node.
3536   unsigned NumBytesForCalleeToPop;
3537   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3538                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3539     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3540   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3541            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3542            SR == StackStructReturn)
3543     // If this is a call to a struct-return function, the callee
3544     // pops the hidden struct pointer, so we have to push it back.
3545     // This is common for Darwin/X86, Linux & Mingw32 targets.
3546     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3547     NumBytesForCalleeToPop = 4;
3548   else
3549     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3550
3551   // Returns a flag for retval copy to use.
3552   if (!IsSibcall) {
3553     Chain = DAG.getCALLSEQ_END(Chain,
3554                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3555                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3556                                                      true),
3557                                InFlag, dl);
3558     InFlag = Chain.getValue(1);
3559   }
3560
3561   // Handle result values, copying them out of physregs into vregs that we
3562   // return.
3563   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3564                          Ins, dl, DAG, InVals);
3565 }
3566
3567 //===----------------------------------------------------------------------===//
3568 //                Fast Calling Convention (tail call) implementation
3569 //===----------------------------------------------------------------------===//
3570
3571 //  Like std call, callee cleans arguments, convention except that ECX is
3572 //  reserved for storing the tail called function address. Only 2 registers are
3573 //  free for argument passing (inreg). Tail call optimization is performed
3574 //  provided:
3575 //                * tailcallopt is enabled
3576 //                * caller/callee are fastcc
3577 //  On X86_64 architecture with GOT-style position independent code only local
3578 //  (within module) calls are supported at the moment.
3579 //  To keep the stack aligned according to platform abi the function
3580 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3581 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3582 //  If a tail called function callee has more arguments than the caller the
3583 //  caller needs to make sure that there is room to move the RETADDR to. This is
3584 //  achieved by reserving an area the size of the argument delta right after the
3585 //  original RETADDR, but before the saved framepointer or the spilled registers
3586 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3587 //  stack layout:
3588 //    arg1
3589 //    arg2
3590 //    RETADDR
3591 //    [ new RETADDR
3592 //      move area ]
3593 //    (possible EBP)
3594 //    ESI
3595 //    EDI
3596 //    local1 ..
3597
3598 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3599 /// requirement.
3600 unsigned
3601 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3602                                                SelectionDAG& DAG) const {
3603   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3604   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3605   unsigned StackAlignment = TFI.getStackAlignment();
3606   uint64_t AlignMask = StackAlignment - 1;
3607   int64_t Offset = StackSize;
3608   unsigned SlotSize = RegInfo->getSlotSize();
3609   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3610     // Number smaller than 12 so just add the difference.
3611     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3612   } else {
3613     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3614     Offset = ((~AlignMask) & Offset) + StackAlignment +
3615       (StackAlignment-SlotSize);
3616   }
3617   return Offset;
3618 }
3619
3620 /// Return true if the given stack call argument is already available in the
3621 /// same position (relatively) of the caller's incoming argument stack.
3622 static
3623 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3624                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3625                          const X86InstrInfo *TII) {
3626   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3627   int FI = INT_MAX;
3628   if (Arg.getOpcode() == ISD::CopyFromReg) {
3629     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3630     if (!TargetRegisterInfo::isVirtualRegister(VR))
3631       return false;
3632     MachineInstr *Def = MRI->getVRegDef(VR);
3633     if (!Def)
3634       return false;
3635     if (!Flags.isByVal()) {
3636       if (!TII->isLoadFromStackSlot(Def, FI))
3637         return false;
3638     } else {
3639       unsigned Opcode = Def->getOpcode();
3640       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3641            Opcode == X86::LEA64_32r) &&
3642           Def->getOperand(1).isFI()) {
3643         FI = Def->getOperand(1).getIndex();
3644         Bytes = Flags.getByValSize();
3645       } else
3646         return false;
3647     }
3648   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3649     if (Flags.isByVal())
3650       // ByVal argument is passed in as a pointer but it's now being
3651       // dereferenced. e.g.
3652       // define @foo(%struct.X* %A) {
3653       //   tail call @bar(%struct.X* byval %A)
3654       // }
3655       return false;
3656     SDValue Ptr = Ld->getBasePtr();
3657     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3658     if (!FINode)
3659       return false;
3660     FI = FINode->getIndex();
3661   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3662     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3663     FI = FINode->getIndex();
3664     Bytes = Flags.getByValSize();
3665   } else
3666     return false;
3667
3668   assert(FI != INT_MAX);
3669   if (!MFI->isFixedObjectIndex(FI))
3670     return false;
3671   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3672 }
3673
3674 /// Check whether the call is eligible for tail call optimization. Targets
3675 /// that want to do tail call optimization should implement this function.
3676 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3677     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3678     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3679     const SmallVectorImpl<ISD::OutputArg> &Outs,
3680     const SmallVectorImpl<SDValue> &OutVals,
3681     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3682   if (!mayTailCallThisCC(CalleeCC))
3683     return false;
3684
3685   // If -tailcallopt is specified, make fastcc functions tail-callable.
3686   MachineFunction &MF = DAG.getMachineFunction();
3687   const Function *CallerF = MF.getFunction();
3688
3689   // If the function return type is x86_fp80 and the callee return type is not,
3690   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3691   // perform a tailcall optimization here.
3692   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3693     return false;
3694
3695   CallingConv::ID CallerCC = CallerF->getCallingConv();
3696   bool CCMatch = CallerCC == CalleeCC;
3697   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3698   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3699
3700   // Win64 functions have extra shadow space for argument homing. Don't do the
3701   // sibcall if the caller and callee have mismatched expectations for this
3702   // space.
3703   if (IsCalleeWin64 != IsCallerWin64)
3704     return false;
3705
3706   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3707     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3708       return true;
3709     return false;
3710   }
3711
3712   // Look for obvious safe cases to perform tail call optimization that do not
3713   // require ABI changes. This is what gcc calls sibcall.
3714
3715   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3716   // emit a special epilogue.
3717   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3718   if (RegInfo->needsStackRealignment(MF))
3719     return false;
3720
3721   // Also avoid sibcall optimization if either caller or callee uses struct
3722   // return semantics.
3723   if (isCalleeStructRet || isCallerStructRet)
3724     return false;
3725
3726   // Do not sibcall optimize vararg calls unless all arguments are passed via
3727   // registers.
3728   if (isVarArg && !Outs.empty()) {
3729     // Optimizing for varargs on Win64 is unlikely to be safe without
3730     // additional testing.
3731     if (IsCalleeWin64 || IsCallerWin64)
3732       return false;
3733
3734     SmallVector<CCValAssign, 16> ArgLocs;
3735     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3736                    *DAG.getContext());
3737
3738     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3739     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3740       if (!ArgLocs[i].isRegLoc())
3741         return false;
3742   }
3743
3744   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3745   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3746   // this into a sibcall.
3747   bool Unused = false;
3748   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3749     if (!Ins[i].Used) {
3750       Unused = true;
3751       break;
3752     }
3753   }
3754   if (Unused) {
3755     SmallVector<CCValAssign, 16> RVLocs;
3756     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3757                    *DAG.getContext());
3758     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3759     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3760       CCValAssign &VA = RVLocs[i];
3761       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3762         return false;
3763     }
3764   }
3765
3766   // If the calling conventions do not match, then we'd better make sure the
3767   // results are returned in the same way as what the caller expects.
3768   if (!CCMatch) {
3769     SmallVector<CCValAssign, 16> RVLocs1;
3770     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3771                     *DAG.getContext());
3772     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3773
3774     SmallVector<CCValAssign, 16> RVLocs2;
3775     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3776                     *DAG.getContext());
3777     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3778
3779     if (RVLocs1.size() != RVLocs2.size())
3780       return false;
3781     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3782       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3783         return false;
3784       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3785         return false;
3786       if (RVLocs1[i].isRegLoc()) {
3787         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3788           return false;
3789       } else {
3790         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3791           return false;
3792       }
3793     }
3794   }
3795
3796   unsigned StackArgsSize = 0;
3797
3798   // If the callee takes no arguments then go on to check the results of the
3799   // call.
3800   if (!Outs.empty()) {
3801     // Check if stack adjustment is needed. For now, do not do this if any
3802     // argument is passed on the stack.
3803     SmallVector<CCValAssign, 16> ArgLocs;
3804     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3805                    *DAG.getContext());
3806
3807     // Allocate shadow area for Win64
3808     if (IsCalleeWin64)
3809       CCInfo.AllocateStack(32, 8);
3810
3811     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3812     StackArgsSize = CCInfo.getNextStackOffset();
3813
3814     if (CCInfo.getNextStackOffset()) {
3815       // Check if the arguments are already laid out in the right way as
3816       // the caller's fixed stack objects.
3817       MachineFrameInfo *MFI = MF.getFrameInfo();
3818       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3819       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3820       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3821         CCValAssign &VA = ArgLocs[i];
3822         SDValue Arg = OutVals[i];
3823         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3824         if (VA.getLocInfo() == CCValAssign::Indirect)
3825           return false;
3826         if (!VA.isRegLoc()) {
3827           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3828                                    MFI, MRI, TII))
3829             return false;
3830         }
3831       }
3832     }
3833
3834     // If the tailcall address may be in a register, then make sure it's
3835     // possible to register allocate for it. In 32-bit, the call address can
3836     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3837     // callee-saved registers are restored. These happen to be the same
3838     // registers used to pass 'inreg' arguments so watch out for those.
3839     if (!Subtarget->is64Bit() &&
3840         ((!isa<GlobalAddressSDNode>(Callee) &&
3841           !isa<ExternalSymbolSDNode>(Callee)) ||
3842          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3843       unsigned NumInRegs = 0;
3844       // In PIC we need an extra register to formulate the address computation
3845       // for the callee.
3846       unsigned MaxInRegs =
3847         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3848
3849       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3850         CCValAssign &VA = ArgLocs[i];
3851         if (!VA.isRegLoc())
3852           continue;
3853         unsigned Reg = VA.getLocReg();
3854         switch (Reg) {
3855         default: break;
3856         case X86::EAX: case X86::EDX: case X86::ECX:
3857           if (++NumInRegs == MaxInRegs)
3858             return false;
3859           break;
3860         }
3861       }
3862     }
3863   }
3864
3865   bool CalleeWillPop =
3866       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3867                        MF.getTarget().Options.GuaranteedTailCallOpt);
3868
3869   if (unsigned BytesToPop =
3870           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3871     // If we have bytes to pop, the callee must pop them.
3872     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3873     if (!CalleePopMatches)
3874       return false;
3875   } else if (CalleeWillPop && StackArgsSize > 0) {
3876     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3877     return false;
3878   }
3879
3880   return true;
3881 }
3882
3883 FastISel *
3884 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3885                                   const TargetLibraryInfo *libInfo) const {
3886   return X86::createFastISel(funcInfo, libInfo);
3887 }
3888
3889 //===----------------------------------------------------------------------===//
3890 //                           Other Lowering Hooks
3891 //===----------------------------------------------------------------------===//
3892
3893 static bool MayFoldLoad(SDValue Op) {
3894   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3895 }
3896
3897 static bool MayFoldIntoStore(SDValue Op) {
3898   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3899 }
3900
3901 static bool isTargetShuffle(unsigned Opcode) {
3902   switch(Opcode) {
3903   default: return false;
3904   case X86ISD::BLENDI:
3905   case X86ISD::PSHUFB:
3906   case X86ISD::PSHUFD:
3907   case X86ISD::PSHUFHW:
3908   case X86ISD::PSHUFLW:
3909   case X86ISD::SHUFP:
3910   case X86ISD::PALIGNR:
3911   case X86ISD::MOVLHPS:
3912   case X86ISD::MOVLHPD:
3913   case X86ISD::MOVHLPS:
3914   case X86ISD::MOVLPS:
3915   case X86ISD::MOVLPD:
3916   case X86ISD::MOVSHDUP:
3917   case X86ISD::MOVSLDUP:
3918   case X86ISD::MOVDDUP:
3919   case X86ISD::MOVSS:
3920   case X86ISD::MOVSD:
3921   case X86ISD::UNPCKL:
3922   case X86ISD::UNPCKH:
3923   case X86ISD::VPERMILPI:
3924   case X86ISD::VPERM2X128:
3925   case X86ISD::VPERMI:
3926   case X86ISD::VPERMV:
3927   case X86ISD::VPERMV3:
3928     return true;
3929   }
3930 }
3931
3932 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3933                                     SDValue V1, unsigned TargetMask,
3934                                     SelectionDAG &DAG) {
3935   switch(Opc) {
3936   default: llvm_unreachable("Unknown x86 shuffle node");
3937   case X86ISD::PSHUFD:
3938   case X86ISD::PSHUFHW:
3939   case X86ISD::PSHUFLW:
3940   case X86ISD::VPERMILPI:
3941   case X86ISD::VPERMI:
3942     return DAG.getNode(Opc, dl, VT, V1,
3943                        DAG.getConstant(TargetMask, dl, MVT::i8));
3944   }
3945 }
3946
3947 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3948                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3949   switch(Opc) {
3950   default: llvm_unreachable("Unknown x86 shuffle node");
3951   case X86ISD::MOVLHPS:
3952   case X86ISD::MOVLHPD:
3953   case X86ISD::MOVHLPS:
3954   case X86ISD::MOVLPS:
3955   case X86ISD::MOVLPD:
3956   case X86ISD::MOVSS:
3957   case X86ISD::MOVSD:
3958   case X86ISD::UNPCKL:
3959   case X86ISD::UNPCKH:
3960     return DAG.getNode(Opc, dl, VT, V1, V2);
3961   }
3962 }
3963
3964 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3965   MachineFunction &MF = DAG.getMachineFunction();
3966   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3967   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3968   int ReturnAddrIndex = FuncInfo->getRAIndex();
3969
3970   if (ReturnAddrIndex == 0) {
3971     // Set up a frame object for the return address.
3972     unsigned SlotSize = RegInfo->getSlotSize();
3973     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3974                                                            -(int64_t)SlotSize,
3975                                                            false);
3976     FuncInfo->setRAIndex(ReturnAddrIndex);
3977   }
3978
3979   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3980 }
3981
3982 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3983                                        bool hasSymbolicDisplacement) {
3984   // Offset should fit into 32 bit immediate field.
3985   if (!isInt<32>(Offset))
3986     return false;
3987
3988   // If we don't have a symbolic displacement - we don't have any extra
3989   // restrictions.
3990   if (!hasSymbolicDisplacement)
3991     return true;
3992
3993   // FIXME: Some tweaks might be needed for medium code model.
3994   if (M != CodeModel::Small && M != CodeModel::Kernel)
3995     return false;
3996
3997   // For small code model we assume that latest object is 16MB before end of 31
3998   // bits boundary. We may also accept pretty large negative constants knowing
3999   // that all objects are in the positive half of address space.
4000   if (M == CodeModel::Small && Offset < 16*1024*1024)
4001     return true;
4002
4003   // For kernel code model we know that all object resist in the negative half
4004   // of 32bits address space. We may not accept negative offsets, since they may
4005   // be just off and we may accept pretty large positive ones.
4006   if (M == CodeModel::Kernel && Offset >= 0)
4007     return true;
4008
4009   return false;
4010 }
4011
4012 /// Determines whether the callee is required to pop its own arguments.
4013 /// Callee pop is necessary to support tail calls.
4014 bool X86::isCalleePop(CallingConv::ID CallingConv,
4015                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4016   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4017   // can guarantee TCO.
4018   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4019     return true;
4020
4021   switch (CallingConv) {
4022   default:
4023     return false;
4024   case CallingConv::X86_StdCall:
4025   case CallingConv::X86_FastCall:
4026   case CallingConv::X86_ThisCall:
4027   case CallingConv::X86_VectorCall:
4028     return !is64Bit;
4029   }
4030 }
4031
4032 /// \brief Return true if the condition is an unsigned comparison operation.
4033 static bool isX86CCUnsigned(unsigned X86CC) {
4034   switch (X86CC) {
4035   default: llvm_unreachable("Invalid integer condition!");
4036   case X86::COND_E:     return true;
4037   case X86::COND_G:     return false;
4038   case X86::COND_GE:    return false;
4039   case X86::COND_L:     return false;
4040   case X86::COND_LE:    return false;
4041   case X86::COND_NE:    return true;
4042   case X86::COND_B:     return true;
4043   case X86::COND_A:     return true;
4044   case X86::COND_BE:    return true;
4045   case X86::COND_AE:    return true;
4046   }
4047 }
4048
4049 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4050   switch (SetCCOpcode) {
4051   default: llvm_unreachable("Invalid integer condition!");
4052   case ISD::SETEQ:  return X86::COND_E;
4053   case ISD::SETGT:  return X86::COND_G;
4054   case ISD::SETGE:  return X86::COND_GE;
4055   case ISD::SETLT:  return X86::COND_L;
4056   case ISD::SETLE:  return X86::COND_LE;
4057   case ISD::SETNE:  return X86::COND_NE;
4058   case ISD::SETULT: return X86::COND_B;
4059   case ISD::SETUGT: return X86::COND_A;
4060   case ISD::SETULE: return X86::COND_BE;
4061   case ISD::SETUGE: return X86::COND_AE;
4062   }
4063 }
4064
4065 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4066 /// condition code, returning the condition code and the LHS/RHS of the
4067 /// comparison to make.
4068 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4069                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4070   if (!isFP) {
4071     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4072       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4073         // X > -1   -> X == 0, jump !sign.
4074         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4075         return X86::COND_NS;
4076       }
4077       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4078         // X < 0   -> X == 0, jump on sign.
4079         return X86::COND_S;
4080       }
4081       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4082         // X < 1   -> X <= 0
4083         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4084         return X86::COND_LE;
4085       }
4086     }
4087
4088     return TranslateIntegerX86CC(SetCCOpcode);
4089   }
4090
4091   // First determine if it is required or is profitable to flip the operands.
4092
4093   // If LHS is a foldable load, but RHS is not, flip the condition.
4094   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4095       !ISD::isNON_EXTLoad(RHS.getNode())) {
4096     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4097     std::swap(LHS, RHS);
4098   }
4099
4100   switch (SetCCOpcode) {
4101   default: break;
4102   case ISD::SETOLT:
4103   case ISD::SETOLE:
4104   case ISD::SETUGT:
4105   case ISD::SETUGE:
4106     std::swap(LHS, RHS);
4107     break;
4108   }
4109
4110   // On a floating point condition, the flags are set as follows:
4111   // ZF  PF  CF   op
4112   //  0 | 0 | 0 | X > Y
4113   //  0 | 0 | 1 | X < Y
4114   //  1 | 0 | 0 | X == Y
4115   //  1 | 1 | 1 | unordered
4116   switch (SetCCOpcode) {
4117   default: llvm_unreachable("Condcode should be pre-legalized away");
4118   case ISD::SETUEQ:
4119   case ISD::SETEQ:   return X86::COND_E;
4120   case ISD::SETOLT:              // flipped
4121   case ISD::SETOGT:
4122   case ISD::SETGT:   return X86::COND_A;
4123   case ISD::SETOLE:              // flipped
4124   case ISD::SETOGE:
4125   case ISD::SETGE:   return X86::COND_AE;
4126   case ISD::SETUGT:              // flipped
4127   case ISD::SETULT:
4128   case ISD::SETLT:   return X86::COND_B;
4129   case ISD::SETUGE:              // flipped
4130   case ISD::SETULE:
4131   case ISD::SETLE:   return X86::COND_BE;
4132   case ISD::SETONE:
4133   case ISD::SETNE:   return X86::COND_NE;
4134   case ISD::SETUO:   return X86::COND_P;
4135   case ISD::SETO:    return X86::COND_NP;
4136   case ISD::SETOEQ:
4137   case ISD::SETUNE:  return X86::COND_INVALID;
4138   }
4139 }
4140
4141 /// Is there a floating point cmov for the specific X86 condition code?
4142 /// Current x86 isa includes the following FP cmov instructions:
4143 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4144 static bool hasFPCMov(unsigned X86CC) {
4145   switch (X86CC) {
4146   default:
4147     return false;
4148   case X86::COND_B:
4149   case X86::COND_BE:
4150   case X86::COND_E:
4151   case X86::COND_P:
4152   case X86::COND_A:
4153   case X86::COND_AE:
4154   case X86::COND_NE:
4155   case X86::COND_NP:
4156     return true;
4157   }
4158 }
4159
4160 /// Returns true if the target can instruction select the
4161 /// specified FP immediate natively. If false, the legalizer will
4162 /// materialize the FP immediate as a load from a constant pool.
4163 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4164   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4165     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4166       return true;
4167   }
4168   return false;
4169 }
4170
4171 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4172                                               ISD::LoadExtType ExtTy,
4173                                               EVT NewVT) const {
4174   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4175   // relocation target a movq or addq instruction: don't let the load shrink.
4176   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4177   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4178     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4179       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4180   return true;
4181 }
4182
4183 /// \brief Returns true if it is beneficial to convert a load of a constant
4184 /// to just the constant itself.
4185 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4186                                                           Type *Ty) const {
4187   assert(Ty->isIntegerTy());
4188
4189   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4190   if (BitSize == 0 || BitSize > 64)
4191     return false;
4192   return true;
4193 }
4194
4195 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4196                                                 unsigned Index) const {
4197   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4198     return false;
4199
4200   return (Index == 0 || Index == ResVT.getVectorNumElements());
4201 }
4202
4203 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4204   // Speculate cttz only if we can directly use TZCNT.
4205   return Subtarget->hasBMI();
4206 }
4207
4208 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4209   // Speculate ctlz only if we can directly use LZCNT.
4210   return Subtarget->hasLZCNT();
4211 }
4212
4213 /// Return true if every element in Mask, beginning
4214 /// from position Pos and ending in Pos+Size is undef.
4215 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4216   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4217     if (0 <= Mask[i])
4218       return false;
4219   return true;
4220 }
4221
4222 /// Return true if Val is undef or if its value falls within the
4223 /// specified range (L, H].
4224 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4225   return (Val < 0) || (Val >= Low && Val < Hi);
4226 }
4227
4228 /// Val is either less than zero (undef) or equal to the specified value.
4229 static bool isUndefOrEqual(int Val, int CmpVal) {
4230   return (Val < 0 || Val == CmpVal);
4231 }
4232
4233 /// Return true if every element in Mask, beginning
4234 /// from position Pos and ending in Pos+Size, falls within the specified
4235 /// sequential range (Low, Low+Size]. or is undef.
4236 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4237                                        unsigned Pos, unsigned Size, int Low) {
4238   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4239     if (!isUndefOrEqual(Mask[i], Low))
4240       return false;
4241   return true;
4242 }
4243
4244 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4245 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4246 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4247   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4248   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4249     return false;
4250
4251   // The index should be aligned on a vecWidth-bit boundary.
4252   uint64_t Index =
4253     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4254
4255   MVT VT = N->getSimpleValueType(0);
4256   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4257   bool Result = (Index * ElSize) % vecWidth == 0;
4258
4259   return Result;
4260 }
4261
4262 /// Return true if the specified INSERT_SUBVECTOR
4263 /// operand specifies a subvector insert that is suitable for input to
4264 /// insertion of 128 or 256-bit subvectors
4265 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4266   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4267   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4268     return false;
4269   // The index should be aligned on a vecWidth-bit boundary.
4270   uint64_t Index =
4271     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4272
4273   MVT VT = N->getSimpleValueType(0);
4274   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4275   bool Result = (Index * ElSize) % vecWidth == 0;
4276
4277   return Result;
4278 }
4279
4280 bool X86::isVINSERT128Index(SDNode *N) {
4281   return isVINSERTIndex(N, 128);
4282 }
4283
4284 bool X86::isVINSERT256Index(SDNode *N) {
4285   return isVINSERTIndex(N, 256);
4286 }
4287
4288 bool X86::isVEXTRACT128Index(SDNode *N) {
4289   return isVEXTRACTIndex(N, 128);
4290 }
4291
4292 bool X86::isVEXTRACT256Index(SDNode *N) {
4293   return isVEXTRACTIndex(N, 256);
4294 }
4295
4296 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4297   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4298   assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4299          "Illegal extract subvector for VEXTRACT");
4300
4301   uint64_t Index =
4302     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4303
4304   MVT VecVT = N->getOperand(0).getSimpleValueType();
4305   MVT ElVT = VecVT.getVectorElementType();
4306
4307   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4308   return Index / NumElemsPerChunk;
4309 }
4310
4311 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4312   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4313   assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4314          "Illegal insert subvector for VINSERT");
4315
4316   uint64_t Index =
4317     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4318
4319   MVT VecVT = N->getSimpleValueType(0);
4320   MVT ElVT = VecVT.getVectorElementType();
4321
4322   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4323   return Index / NumElemsPerChunk;
4324 }
4325
4326 /// Return the appropriate immediate to extract the specified
4327 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4328 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4329   return getExtractVEXTRACTImmediate(N, 128);
4330 }
4331
4332 /// Return the appropriate immediate to extract the specified
4333 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4334 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4335   return getExtractVEXTRACTImmediate(N, 256);
4336 }
4337
4338 /// Return the appropriate immediate to insert at the specified
4339 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4340 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4341   return getInsertVINSERTImmediate(N, 128);
4342 }
4343
4344 /// Return the appropriate immediate to insert at the specified
4345 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4346 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4347   return getInsertVINSERTImmediate(N, 256);
4348 }
4349
4350 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4351 bool X86::isZeroNode(SDValue Elt) {
4352   return isNullConstant(Elt) || isNullFPConstant(Elt);
4353 }
4354
4355 // Build a vector of constants
4356 // Use an UNDEF node if MaskElt == -1.
4357 // Spilt 64-bit constants in the 32-bit mode.
4358 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4359                               SelectionDAG &DAG,
4360                               SDLoc dl, bool IsMask = false) {
4361
4362   SmallVector<SDValue, 32>  Ops;
4363   bool Split = false;
4364
4365   MVT ConstVecVT = VT;
4366   unsigned NumElts = VT.getVectorNumElements();
4367   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4368   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4369     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4370     Split = true;
4371   }
4372
4373   MVT EltVT = ConstVecVT.getVectorElementType();
4374   for (unsigned i = 0; i < NumElts; ++i) {
4375     bool IsUndef = Values[i] < 0 && IsMask;
4376     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4377       DAG.getConstant(Values[i], dl, EltVT);
4378     Ops.push_back(OpNode);
4379     if (Split)
4380       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4381                     DAG.getConstant(0, dl, EltVT));
4382   }
4383   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4384   if (Split)
4385     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4386   return ConstsNode;
4387 }
4388
4389 /// Returns a vector of specified type with all zero elements.
4390 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4391                              SelectionDAG &DAG, SDLoc dl) {
4392   assert(VT.isVector() && "Expected a vector type");
4393
4394   // Always build SSE zero vectors as <4 x i32> bitcasted
4395   // to their dest type. This ensures they get CSE'd.
4396   SDValue Vec;
4397   if (VT.is128BitVector()) {  // SSE
4398     if (Subtarget->hasSSE2()) {  // SSE2
4399       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4400       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4401     } else { // SSE1
4402       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4403       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4404     }
4405   } else if (VT.is256BitVector()) { // AVX
4406     if (Subtarget->hasInt256()) { // AVX2
4407       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4408       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4409       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4410     } else {
4411       // 256-bit logic and arithmetic instructions in AVX are all
4412       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4413       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4414       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4415       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4416     }
4417   } else if (VT.is512BitVector()) { // AVX-512
4418       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4419       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4420                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4421       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4422   } else if (VT.getVectorElementType() == MVT::i1) {
4423
4424     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4425             && "Unexpected vector type");
4426     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4427             && "Unexpected vector type");
4428     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4429     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4430     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4431   } else
4432     llvm_unreachable("Unexpected vector type");
4433
4434   return DAG.getBitcast(VT, Vec);
4435 }
4436
4437 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4438                                 SelectionDAG &DAG, SDLoc dl,
4439                                 unsigned vectorWidth) {
4440   assert((vectorWidth == 128 || vectorWidth == 256) &&
4441          "Unsupported vector width");
4442   EVT VT = Vec.getValueType();
4443   EVT ElVT = VT.getVectorElementType();
4444   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4445   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4446                                   VT.getVectorNumElements()/Factor);
4447
4448   // Extract from UNDEF is UNDEF.
4449   if (Vec.getOpcode() == ISD::UNDEF)
4450     return DAG.getUNDEF(ResultVT);
4451
4452   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4453   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4454   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4455
4456   // This is the index of the first element of the vectorWidth-bit chunk
4457   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4458   IdxVal &= ~(ElemsPerChunk - 1);
4459
4460   // If the input is a buildvector just emit a smaller one.
4461   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4462     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4463                        makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4464
4465   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4466   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4467 }
4468
4469 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4470 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4471 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4472 /// instructions or a simple subregister reference. Idx is an index in the
4473 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4474 /// lowering EXTRACT_VECTOR_ELT operations easier.
4475 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4476                                    SelectionDAG &DAG, SDLoc dl) {
4477   assert((Vec.getValueType().is256BitVector() ||
4478           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4479   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4480 }
4481
4482 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4483 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4484                                    SelectionDAG &DAG, SDLoc dl) {
4485   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4486   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4487 }
4488
4489 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4490                                unsigned IdxVal, SelectionDAG &DAG,
4491                                SDLoc dl, unsigned vectorWidth) {
4492   assert((vectorWidth == 128 || vectorWidth == 256) &&
4493          "Unsupported vector width");
4494   // Inserting UNDEF is Result
4495   if (Vec.getOpcode() == ISD::UNDEF)
4496     return Result;
4497   EVT VT = Vec.getValueType();
4498   EVT ElVT = VT.getVectorElementType();
4499   EVT ResultVT = Result.getValueType();
4500
4501   // Insert the relevant vectorWidth bits.
4502   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4503   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4504
4505   // This is the index of the first element of the vectorWidth-bit chunk
4506   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4507   IdxVal &= ~(ElemsPerChunk - 1);
4508
4509   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4510   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4511 }
4512
4513 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4514 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4515 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4516 /// simple superregister reference.  Idx is an index in the 128 bits
4517 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4518 /// lowering INSERT_VECTOR_ELT operations easier.
4519 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4520                                   SelectionDAG &DAG, SDLoc dl) {
4521   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4522
4523   // For insertion into the zero index (low half) of a 256-bit vector, it is
4524   // more efficient to generate a blend with immediate instead of an insert*128.
4525   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4526   // extend the subvector to the size of the result vector. Make sure that
4527   // we are not recursing on that node by checking for undef here.
4528   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4529       Result.getOpcode() != ISD::UNDEF) {
4530     EVT ResultVT = Result.getValueType();
4531     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4532     SDValue Undef = DAG.getUNDEF(ResultVT);
4533     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4534                                  Vec, ZeroIndex);
4535
4536     // The blend instruction, and therefore its mask, depend on the data type.
4537     MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4538     if (ScalarType.isFloatingPoint()) {
4539       // Choose either vblendps (float) or vblendpd (double).
4540       unsigned ScalarSize = ScalarType.getSizeInBits();
4541       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4542       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4543       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4544       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4545     }
4546
4547     const X86Subtarget &Subtarget =
4548     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4549
4550     // AVX2 is needed for 256-bit integer blend support.
4551     // Integers must be cast to 32-bit because there is only vpblendd;
4552     // vpblendw can't be used for this because it has a handicapped mask.
4553
4554     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4555     // is still more efficient than using the wrong domain vinsertf128 that
4556     // will be created by InsertSubVector().
4557     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4558
4559     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4560     Result = DAG.getBitcast(CastVT, Result);
4561     Vec256 = DAG.getBitcast(CastVT, Vec256);
4562     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4563     return DAG.getBitcast(ResultVT, Vec256);
4564   }
4565
4566   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4567 }
4568
4569 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4570                                   SelectionDAG &DAG, SDLoc dl) {
4571   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4572   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4573 }
4574
4575 /// Insert i1-subvector to i1-vector.
4576 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4577
4578   SDLoc dl(Op);
4579   SDValue Vec = Op.getOperand(0);
4580   SDValue SubVec = Op.getOperand(1);
4581   SDValue Idx = Op.getOperand(2);
4582
4583   if (!isa<ConstantSDNode>(Idx))
4584     return SDValue();
4585
4586   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4587   if (IdxVal == 0  && Vec.isUndef()) // the operation is legal
4588     return Op;
4589
4590   MVT OpVT = Op.getSimpleValueType();
4591   MVT SubVecVT = SubVec.getSimpleValueType();
4592   unsigned NumElems = OpVT.getVectorNumElements();
4593   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4594
4595   assert(IdxVal + SubVecNumElems <= NumElems &&
4596          IdxVal % SubVecVT.getSizeInBits() == 0 &&
4597          "Unexpected index value in INSERT_SUBVECTOR");
4598
4599   // There are 3 possible cases:
4600   // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4601   // 2. Subvector should be inserted in the upper part
4602   //    (IdxVal + SubVecNumElems == NumElems)
4603   // 3. Subvector should be inserted in the middle (for example v2i1
4604   //    to v16i1, index 2)
4605
4606   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4607   SDValue Undef = DAG.getUNDEF(OpVT);
4608   SDValue WideSubVec =
4609     DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4610   if (Vec.isUndef())
4611     return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4612       DAG.getConstant(IdxVal, dl, MVT::i8));
4613
4614   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4615     unsigned ShiftLeft = NumElems - SubVecNumElems;
4616     unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4617     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4618       DAG.getConstant(ShiftLeft, dl, MVT::i8));
4619     return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4620       DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4621   }
4622
4623   if (IdxVal == 0) {
4624     // Zero lower bits of the Vec
4625     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4626     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4627     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4628     // Merge them together
4629     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4630   }
4631
4632   // Simple case when we put subvector in the upper part
4633   if (IdxVal + SubVecNumElems == NumElems) {
4634     // Zero upper bits of the Vec
4635     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4636                         DAG.getConstant(IdxVal, dl, MVT::i8));
4637     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4638     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4639     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4640     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4641   }
4642   // Subvector should be inserted in the middle - use shuffle
4643   SmallVector<int, 64> Mask;
4644   for (unsigned i = 0; i < NumElems; ++i)
4645     Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4646                     i : i + NumElems);
4647   return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4648 }
4649
4650 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4651 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4652 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4653 /// large BUILD_VECTORS.
4654 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4655                                    unsigned NumElems, SelectionDAG &DAG,
4656                                    SDLoc dl) {
4657   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4658   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4659 }
4660
4661 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4662                                    unsigned NumElems, SelectionDAG &DAG,
4663                                    SDLoc dl) {
4664   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4665   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4666 }
4667
4668 /// Returns a vector of specified type with all bits set.
4669 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4670 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4671 /// Then bitcast to their original type, ensuring they get CSE'd.
4672 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4673                              SelectionDAG &DAG, SDLoc dl) {
4674   assert(VT.isVector() && "Expected a vector type");
4675
4676   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4677   SDValue Vec;
4678   if (VT.is512BitVector()) {
4679     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4680                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4681     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4682   } else if (VT.is256BitVector()) {
4683     if (Subtarget->hasInt256()) { // AVX2
4684       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4685       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4686     } else { // AVX
4687       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4688       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4689     }
4690   } else if (VT.is128BitVector()) {
4691     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4692   } else
4693     llvm_unreachable("Unexpected vector type");
4694
4695   return DAG.getBitcast(VT, Vec);
4696 }
4697
4698 /// Returns a vector_shuffle node for an unpackl operation.
4699 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4700                           SDValue V2) {
4701   unsigned NumElems = VT.getVectorNumElements();
4702   SmallVector<int, 8> Mask;
4703   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4704     Mask.push_back(i);
4705     Mask.push_back(i + NumElems);
4706   }
4707   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4708 }
4709
4710 /// Returns a vector_shuffle node for an unpackh operation.
4711 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4712                           SDValue V2) {
4713   unsigned NumElems = VT.getVectorNumElements();
4714   SmallVector<int, 8> Mask;
4715   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4716     Mask.push_back(i + Half);
4717     Mask.push_back(i + NumElems + Half);
4718   }
4719   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4720 }
4721
4722 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4723 /// This produces a shuffle where the low element of V2 is swizzled into the
4724 /// zero/undef vector, landing at element Idx.
4725 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4726 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4727                                            bool IsZero,
4728                                            const X86Subtarget *Subtarget,
4729                                            SelectionDAG &DAG) {
4730   MVT VT = V2.getSimpleValueType();
4731   SDValue V1 = IsZero
4732     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4733   unsigned NumElems = VT.getVectorNumElements();
4734   SmallVector<int, 16> MaskVec;
4735   for (unsigned i = 0; i != NumElems; ++i)
4736     // If this is the insertion idx, put the low elt of V2 here.
4737     MaskVec.push_back(i == Idx ? NumElems : i);
4738   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4739 }
4740
4741 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4742 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4743 /// uses one source. Note that this will set IsUnary for shuffles which use a
4744 /// single input multiple times, and in those cases it will
4745 /// adjust the mask to only have indices within that single input.
4746 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4747 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4748                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4749   unsigned NumElems = VT.getVectorNumElements();
4750   SDValue ImmN;
4751
4752   IsUnary = false;
4753   bool IsFakeUnary = false;
4754   switch(N->getOpcode()) {
4755   case X86ISD::BLENDI:
4756     ImmN = N->getOperand(N->getNumOperands()-1);
4757     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4758     break;
4759   case X86ISD::SHUFP:
4760     ImmN = N->getOperand(N->getNumOperands()-1);
4761     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4762     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4763     break;
4764   case X86ISD::UNPCKH:
4765     DecodeUNPCKHMask(VT, Mask);
4766     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4767     break;
4768   case X86ISD::UNPCKL:
4769     DecodeUNPCKLMask(VT, Mask);
4770     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4771     break;
4772   case X86ISD::MOVHLPS:
4773     DecodeMOVHLPSMask(NumElems, Mask);
4774     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4775     break;
4776   case X86ISD::MOVLHPS:
4777     DecodeMOVLHPSMask(NumElems, Mask);
4778     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4779     break;
4780   case X86ISD::PALIGNR:
4781     ImmN = N->getOperand(N->getNumOperands()-1);
4782     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4783     break;
4784   case X86ISD::PSHUFD:
4785   case X86ISD::VPERMILPI:
4786     ImmN = N->getOperand(N->getNumOperands()-1);
4787     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4788     IsUnary = true;
4789     break;
4790   case X86ISD::PSHUFHW:
4791     ImmN = N->getOperand(N->getNumOperands()-1);
4792     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4793     IsUnary = true;
4794     break;
4795   case X86ISD::PSHUFLW:
4796     ImmN = N->getOperand(N->getNumOperands()-1);
4797     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4798     IsUnary = true;
4799     break;
4800   case X86ISD::PSHUFB: {
4801     IsUnary = true;
4802     SDValue MaskNode = N->getOperand(1);
4803     while (MaskNode->getOpcode() == ISD::BITCAST)
4804       MaskNode = MaskNode->getOperand(0);
4805
4806     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4807       // If we have a build-vector, then things are easy.
4808       MVT VT = MaskNode.getSimpleValueType();
4809       assert(VT.isVector() &&
4810              "Can't produce a non-vector with a build_vector!");
4811       if (!VT.isInteger())
4812         return false;
4813
4814       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4815
4816       SmallVector<uint64_t, 32> RawMask;
4817       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4818         SDValue Op = MaskNode->getOperand(i);
4819         if (Op->getOpcode() == ISD::UNDEF) {
4820           RawMask.push_back((uint64_t)SM_SentinelUndef);
4821           continue;
4822         }
4823         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4824         if (!CN)
4825           return false;
4826         APInt MaskElement = CN->getAPIntValue();
4827
4828         // We now have to decode the element which could be any integer size and
4829         // extract each byte of it.
4830         for (int j = 0; j < NumBytesPerElement; ++j) {
4831           // Note that this is x86 and so always little endian: the low byte is
4832           // the first byte of the mask.
4833           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4834           MaskElement = MaskElement.lshr(8);
4835         }
4836       }
4837       DecodePSHUFBMask(RawMask, Mask);
4838       break;
4839     }
4840
4841     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4842     if (!MaskLoad)
4843       return false;
4844
4845     SDValue Ptr = MaskLoad->getBasePtr();
4846     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4847         Ptr->getOpcode() == X86ISD::WrapperRIP)
4848       Ptr = Ptr->getOperand(0);
4849
4850     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4851     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4852       return false;
4853
4854     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4855       DecodePSHUFBMask(C, Mask);
4856       if (Mask.empty())
4857         return false;
4858       break;
4859     }
4860
4861     return false;
4862   }
4863   case X86ISD::VPERMI:
4864     ImmN = N->getOperand(N->getNumOperands()-1);
4865     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4866     IsUnary = true;
4867     break;
4868   case X86ISD::MOVSS:
4869   case X86ISD::MOVSD:
4870     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4871     break;
4872   case X86ISD::VPERM2X128:
4873     ImmN = N->getOperand(N->getNumOperands()-1);
4874     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4875     if (Mask.empty()) return false;
4876     // Mask only contains negative index if an element is zero.
4877     if (std::any_of(Mask.begin(), Mask.end(),
4878                     [](int M){ return M == SM_SentinelZero; }))
4879       return false;
4880     break;
4881   case X86ISD::MOVSLDUP:
4882     DecodeMOVSLDUPMask(VT, Mask);
4883     IsUnary = true;
4884     break;
4885   case X86ISD::MOVSHDUP:
4886     DecodeMOVSHDUPMask(VT, Mask);
4887     IsUnary = true;
4888     break;
4889   case X86ISD::MOVDDUP:
4890     DecodeMOVDDUPMask(VT, Mask);
4891     IsUnary = true;
4892     break;
4893   case X86ISD::MOVLHPD:
4894   case X86ISD::MOVLPD:
4895   case X86ISD::MOVLPS:
4896     // Not yet implemented
4897     return false;
4898   case X86ISD::VPERMV: {
4899     IsUnary = true;
4900     SDValue MaskNode = N->getOperand(0);
4901     while (MaskNode->getOpcode() == ISD::BITCAST)
4902       MaskNode = MaskNode->getOperand(0);
4903
4904     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4905     SmallVector<uint64_t, 32> RawMask;
4906     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4907       // If we have a build-vector, then things are easy.
4908       assert(MaskNode.getSimpleValueType().isInteger() &&
4909              MaskNode.getSimpleValueType().getVectorNumElements() ==
4910              VT.getVectorNumElements());
4911
4912       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4913         SDValue Op = MaskNode->getOperand(i);
4914         if (Op->getOpcode() == ISD::UNDEF)
4915           RawMask.push_back((uint64_t)SM_SentinelUndef);
4916         else if (isa<ConstantSDNode>(Op)) {
4917           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4918           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4919         } else
4920           return false;
4921       }
4922       DecodeVPERMVMask(RawMask, Mask);
4923       break;
4924     }
4925     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4926       unsigned NumEltsInMask = MaskNode->getNumOperands();
4927       MaskNode = MaskNode->getOperand(0);
4928       if (auto *CN = dyn_cast<ConstantSDNode>(MaskNode)) {
4929         APInt MaskEltValue = CN->getAPIntValue();
4930         for (unsigned i = 0; i < NumEltsInMask; ++i)
4931           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4932         DecodeVPERMVMask(RawMask, Mask);
4933         break;
4934       }
4935       // It may be a scalar load
4936     }
4937
4938     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4939     if (!MaskLoad)
4940       return false;
4941
4942     SDValue Ptr = MaskLoad->getBasePtr();
4943     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4944         Ptr->getOpcode() == X86ISD::WrapperRIP)
4945       Ptr = Ptr->getOperand(0);
4946
4947     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4948     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4949       return false;
4950
4951     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4952       DecodeVPERMVMask(C, VT, Mask);
4953       if (Mask.empty())
4954         return false;
4955       break;
4956     }
4957     return false;
4958   }
4959   case X86ISD::VPERMV3: {
4960     IsUnary = false;
4961     SDValue MaskNode = N->getOperand(1);
4962     while (MaskNode->getOpcode() == ISD::BITCAST)
4963       MaskNode = MaskNode->getOperand(1);
4964
4965     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4966       // If we have a build-vector, then things are easy.
4967       assert(MaskNode.getSimpleValueType().isInteger() &&
4968              MaskNode.getSimpleValueType().getVectorNumElements() ==
4969              VT.getVectorNumElements());
4970
4971       SmallVector<uint64_t, 32> RawMask;
4972       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4973
4974       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4975         SDValue Op = MaskNode->getOperand(i);
4976         if (Op->getOpcode() == ISD::UNDEF)
4977           RawMask.push_back((uint64_t)SM_SentinelUndef);
4978         else {
4979           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4980           if (!CN)
4981             return false;
4982           APInt MaskElement = CN->getAPIntValue();
4983           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4984         }
4985       }
4986       DecodeVPERMV3Mask(RawMask, Mask);
4987       break;
4988     }
4989
4990     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4991     if (!MaskLoad)
4992       return false;
4993
4994     SDValue Ptr = MaskLoad->getBasePtr();
4995     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4996         Ptr->getOpcode() == X86ISD::WrapperRIP)
4997       Ptr = Ptr->getOperand(0);
4998
4999     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5000     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5001       return false;
5002
5003     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5004       DecodeVPERMV3Mask(C, VT, Mask);
5005       if (Mask.empty())
5006         return false;
5007       break;
5008     }
5009     return false;
5010   }
5011   default: llvm_unreachable("unknown target shuffle node");
5012   }
5013
5014   // If we have a fake unary shuffle, the shuffle mask is spread across two
5015   // inputs that are actually the same node. Re-map the mask to always point
5016   // into the first input.
5017   if (IsFakeUnary)
5018     for (int &M : Mask)
5019       if (M >= (int)Mask.size())
5020         M -= Mask.size();
5021
5022   return true;
5023 }
5024
5025 /// Returns the scalar element that will make up the ith
5026 /// element of the result of the vector shuffle.
5027 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5028                                    unsigned Depth) {
5029   if (Depth == 6)
5030     return SDValue();  // Limit search depth.
5031
5032   SDValue V = SDValue(N, 0);
5033   EVT VT = V.getValueType();
5034   unsigned Opcode = V.getOpcode();
5035
5036   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5037   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5038     int Elt = SV->getMaskElt(Index);
5039
5040     if (Elt < 0)
5041       return DAG.getUNDEF(VT.getVectorElementType());
5042
5043     unsigned NumElems = VT.getVectorNumElements();
5044     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5045                                          : SV->getOperand(1);
5046     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5047   }
5048
5049   // Recurse into target specific vector shuffles to find scalars.
5050   if (isTargetShuffle(Opcode)) {
5051     MVT ShufVT = V.getSimpleValueType();
5052     unsigned NumElems = ShufVT.getVectorNumElements();
5053     SmallVector<int, 16> ShuffleMask;
5054     bool IsUnary;
5055
5056     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5057       return SDValue();
5058
5059     int Elt = ShuffleMask[Index];
5060     if (Elt < 0)
5061       return DAG.getUNDEF(ShufVT.getVectorElementType());
5062
5063     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5064                                          : N->getOperand(1);
5065     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5066                                Depth+1);
5067   }
5068
5069   // Actual nodes that may contain scalar elements
5070   if (Opcode == ISD::BITCAST) {
5071     V = V.getOperand(0);
5072     EVT SrcVT = V.getValueType();
5073     unsigned NumElems = VT.getVectorNumElements();
5074
5075     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5076       return SDValue();
5077   }
5078
5079   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5080     return (Index == 0) ? V.getOperand(0)
5081                         : DAG.getUNDEF(VT.getVectorElementType());
5082
5083   if (V.getOpcode() == ISD::BUILD_VECTOR)
5084     return V.getOperand(Index);
5085
5086   return SDValue();
5087 }
5088
5089 /// Custom lower build_vector of v16i8.
5090 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5091                                        unsigned NumNonZero, unsigned NumZero,
5092                                        SelectionDAG &DAG,
5093                                        const X86Subtarget* Subtarget,
5094                                        const TargetLowering &TLI) {
5095   if (NumNonZero > 8)
5096     return SDValue();
5097
5098   SDLoc dl(Op);
5099   SDValue V;
5100   bool First = true;
5101
5102   // SSE4.1 - use PINSRB to insert each byte directly.
5103   if (Subtarget->hasSSE41()) {
5104     for (unsigned i = 0; i < 16; ++i) {
5105       bool isNonZero = (NonZeros & (1 << i)) != 0;
5106       if (isNonZero) {
5107         if (First) {
5108           if (NumZero)
5109             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5110           else
5111             V = DAG.getUNDEF(MVT::v16i8);
5112           First = false;
5113         }
5114         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5115                         MVT::v16i8, V, Op.getOperand(i),
5116                         DAG.getIntPtrConstant(i, dl));
5117       }
5118     }
5119
5120     return V;
5121   }
5122
5123   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5124   for (unsigned i = 0; i < 16; ++i) {
5125     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5126     if (ThisIsNonZero && First) {
5127       if (NumZero)
5128         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5129       else
5130         V = DAG.getUNDEF(MVT::v8i16);
5131       First = false;
5132     }
5133
5134     if ((i & 1) != 0) {
5135       SDValue ThisElt, LastElt;
5136       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5137       if (LastIsNonZero) {
5138         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5139                               MVT::i16, Op.getOperand(i-1));
5140       }
5141       if (ThisIsNonZero) {
5142         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5143         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5144                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
5145         if (LastIsNonZero)
5146           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5147       } else
5148         ThisElt = LastElt;
5149
5150       if (ThisElt.getNode())
5151         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5152                         DAG.getIntPtrConstant(i/2, dl));
5153     }
5154   }
5155
5156   return DAG.getBitcast(MVT::v16i8, V);
5157 }
5158
5159 /// Custom lower build_vector of v8i16.
5160 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5161                                      unsigned NumNonZero, unsigned NumZero,
5162                                      SelectionDAG &DAG,
5163                                      const X86Subtarget* Subtarget,
5164                                      const TargetLowering &TLI) {
5165   if (NumNonZero > 4)
5166     return SDValue();
5167
5168   SDLoc dl(Op);
5169   SDValue V;
5170   bool First = true;
5171   for (unsigned i = 0; i < 8; ++i) {
5172     bool isNonZero = (NonZeros & (1 << i)) != 0;
5173     if (isNonZero) {
5174       if (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       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5182                       MVT::v8i16, V, Op.getOperand(i),
5183                       DAG.getIntPtrConstant(i, dl));
5184     }
5185   }
5186
5187   return V;
5188 }
5189
5190 /// Custom lower build_vector of v4i32 or v4f32.
5191 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5192                                      const X86Subtarget *Subtarget,
5193                                      const TargetLowering &TLI) {
5194   // Find all zeroable elements.
5195   std::bitset<4> Zeroable;
5196   for (int i=0; i < 4; ++i) {
5197     SDValue Elt = Op->getOperand(i);
5198     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5199   }
5200   assert(Zeroable.size() - Zeroable.count() > 1 &&
5201          "We expect at least two non-zero elements!");
5202
5203   // We only know how to deal with build_vector nodes where elements are either
5204   // zeroable or extract_vector_elt with constant index.
5205   SDValue FirstNonZero;
5206   unsigned FirstNonZeroIdx;
5207   for (unsigned i=0; i < 4; ++i) {
5208     if (Zeroable[i])
5209       continue;
5210     SDValue Elt = Op->getOperand(i);
5211     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5212         !isa<ConstantSDNode>(Elt.getOperand(1)))
5213       return SDValue();
5214     // Make sure that this node is extracting from a 128-bit vector.
5215     MVT VT = Elt.getOperand(0).getSimpleValueType();
5216     if (!VT.is128BitVector())
5217       return SDValue();
5218     if (!FirstNonZero.getNode()) {
5219       FirstNonZero = Elt;
5220       FirstNonZeroIdx = i;
5221     }
5222   }
5223
5224   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5225   SDValue V1 = FirstNonZero.getOperand(0);
5226   MVT VT = V1.getSimpleValueType();
5227
5228   // See if this build_vector can be lowered as a blend with zero.
5229   SDValue Elt;
5230   unsigned EltMaskIdx, EltIdx;
5231   int Mask[4];
5232   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5233     if (Zeroable[EltIdx]) {
5234       // The zero vector will be on the right hand side.
5235       Mask[EltIdx] = EltIdx+4;
5236       continue;
5237     }
5238
5239     Elt = Op->getOperand(EltIdx);
5240     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5241     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5242     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5243       break;
5244     Mask[EltIdx] = EltIdx;
5245   }
5246
5247   if (EltIdx == 4) {
5248     // Let the shuffle legalizer deal with blend operations.
5249     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5250     if (V1.getSimpleValueType() != VT)
5251       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5252     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5253   }
5254
5255   // See if we can lower this build_vector to a INSERTPS.
5256   if (!Subtarget->hasSSE41())
5257     return SDValue();
5258
5259   SDValue V2 = Elt.getOperand(0);
5260   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5261     V1 = SDValue();
5262
5263   bool CanFold = true;
5264   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5265     if (Zeroable[i])
5266       continue;
5267
5268     SDValue Current = Op->getOperand(i);
5269     SDValue SrcVector = Current->getOperand(0);
5270     if (!V1.getNode())
5271       V1 = SrcVector;
5272     CanFold = SrcVector == V1 &&
5273       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5274   }
5275
5276   if (!CanFold)
5277     return SDValue();
5278
5279   assert(V1.getNode() && "Expected at least two non-zero elements!");
5280   if (V1.getSimpleValueType() != MVT::v4f32)
5281     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5282   if (V2.getSimpleValueType() != MVT::v4f32)
5283     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5284
5285   // Ok, we can emit an INSERTPS instruction.
5286   unsigned ZMask = Zeroable.to_ulong();
5287
5288   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5289   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5290   SDLoc DL(Op);
5291   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5292                                DAG.getIntPtrConstant(InsertPSMask, DL));
5293   return DAG.getBitcast(VT, Result);
5294 }
5295
5296 /// Return a vector logical shift node.
5297 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5298                          unsigned NumBits, SelectionDAG &DAG,
5299                          const TargetLowering &TLI, SDLoc dl) {
5300   assert(VT.is128BitVector() && "Unknown type for VShift");
5301   MVT ShVT = MVT::v2i64;
5302   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5303   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5304   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5305   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5306   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5307   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5308 }
5309
5310 static SDValue
5311 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5312
5313   // Check if the scalar load can be widened into a vector load. And if
5314   // the address is "base + cst" see if the cst can be "absorbed" into
5315   // the shuffle mask.
5316   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5317     SDValue Ptr = LD->getBasePtr();
5318     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5319       return SDValue();
5320     EVT PVT = LD->getValueType(0);
5321     if (PVT != MVT::i32 && PVT != MVT::f32)
5322       return SDValue();
5323
5324     int FI = -1;
5325     int64_t Offset = 0;
5326     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5327       FI = FINode->getIndex();
5328       Offset = 0;
5329     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5330                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5331       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5332       Offset = Ptr.getConstantOperandVal(1);
5333       Ptr = Ptr.getOperand(0);
5334     } else {
5335       return SDValue();
5336     }
5337
5338     // FIXME: 256-bit vector instructions don't require a strict alignment,
5339     // improve this code to support it better.
5340     unsigned RequiredAlign = VT.getSizeInBits()/8;
5341     SDValue Chain = LD->getChain();
5342     // Make sure the stack object alignment is at least 16 or 32.
5343     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5344     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5345       if (MFI->isFixedObjectIndex(FI)) {
5346         // Can't change the alignment. FIXME: It's possible to compute
5347         // the exact stack offset and reference FI + adjust offset instead.
5348         // If someone *really* cares about this. That's the way to implement it.
5349         return SDValue();
5350       } else {
5351         MFI->setObjectAlignment(FI, RequiredAlign);
5352       }
5353     }
5354
5355     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5356     // Ptr + (Offset & ~15).
5357     if (Offset < 0)
5358       return SDValue();
5359     if ((Offset % RequiredAlign) & 3)
5360       return SDValue();
5361     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5362     if (StartOffset) {
5363       SDLoc DL(Ptr);
5364       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5365                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5366     }
5367
5368     int EltNo = (Offset - StartOffset) >> 2;
5369     unsigned NumElems = VT.getVectorNumElements();
5370
5371     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5372     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5373                              LD->getPointerInfo().getWithOffset(StartOffset),
5374                              false, false, false, 0);
5375
5376     SmallVector<int, 8> Mask(NumElems, EltNo);
5377
5378     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5379   }
5380
5381   return SDValue();
5382 }
5383
5384 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5385 /// elements can be replaced by a single large load which has the same value as
5386 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5387 ///
5388 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5389 ///
5390 /// FIXME: we'd also like to handle the case where the last elements are zero
5391 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5392 /// There's even a handy isZeroNode for that purpose.
5393 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5394                                         SDLoc &DL, SelectionDAG &DAG,
5395                                         bool isAfterLegalize) {
5396   unsigned NumElems = Elts.size();
5397
5398   LoadSDNode *LDBase = nullptr;
5399   unsigned LastLoadedElt = -1U;
5400
5401   // For each element in the initializer, see if we've found a load or an undef.
5402   // If we don't find an initial load element, or later load elements are
5403   // non-consecutive, bail out.
5404   for (unsigned i = 0; i < NumElems; ++i) {
5405     SDValue Elt = Elts[i];
5406     // Look through a bitcast.
5407     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5408       Elt = Elt.getOperand(0);
5409     if (!Elt.getNode() ||
5410         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5411       return SDValue();
5412     if (!LDBase) {
5413       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5414         return SDValue();
5415       LDBase = cast<LoadSDNode>(Elt.getNode());
5416       LastLoadedElt = i;
5417       continue;
5418     }
5419     if (Elt.getOpcode() == ISD::UNDEF)
5420       continue;
5421
5422     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5423     EVT LdVT = Elt.getValueType();
5424     // Each loaded element must be the correct fractional portion of the
5425     // requested vector load.
5426     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5427       return SDValue();
5428     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5429       return SDValue();
5430     LastLoadedElt = i;
5431   }
5432
5433   // If we have found an entire vector of loads and undefs, then return a large
5434   // load of the entire vector width starting at the base pointer.  If we found
5435   // consecutive loads for the low half, generate a vzext_load node.
5436   if (LastLoadedElt == NumElems - 1) {
5437     assert(LDBase && "Did not find base load for merging consecutive loads");
5438     EVT EltVT = LDBase->getValueType(0);
5439     // Ensure that the input vector size for the merged loads matches the
5440     // cumulative size of the input elements.
5441     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5442       return SDValue();
5443
5444     if (isAfterLegalize &&
5445         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5446       return SDValue();
5447
5448     SDValue NewLd = SDValue();
5449
5450     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5451                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5452                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5453                         LDBase->getAlignment());
5454
5455     if (LDBase->hasAnyUseOfValue(1)) {
5456       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5457                                      SDValue(LDBase, 1),
5458                                      SDValue(NewLd.getNode(), 1));
5459       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5460       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5461                              SDValue(NewLd.getNode(), 1));
5462     }
5463
5464     return NewLd;
5465   }
5466
5467   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5468   //of a v4i32 / v4f32. It's probably worth generalizing.
5469   EVT EltVT = VT.getVectorElementType();
5470   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5471       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5472     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5473     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5474     SDValue ResNode =
5475         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5476                                 LDBase->getPointerInfo(),
5477                                 LDBase->getAlignment(),
5478                                 false/*isVolatile*/, true/*ReadMem*/,
5479                                 false/*WriteMem*/);
5480
5481     // Make sure the newly-created LOAD is in the same position as LDBase in
5482     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5483     // update uses of LDBase's output chain to use the TokenFactor.
5484     if (LDBase->hasAnyUseOfValue(1)) {
5485       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5486                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5487       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5488       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5489                              SDValue(ResNode.getNode(), 1));
5490     }
5491
5492     return DAG.getBitcast(VT, ResNode);
5493   }
5494   return SDValue();
5495 }
5496
5497 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5498 /// to generate a splat value for the following cases:
5499 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5500 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5501 /// a scalar load, or a constant.
5502 /// The VBROADCAST node is returned when a pattern is found,
5503 /// or SDValue() otherwise.
5504 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5505                                     SelectionDAG &DAG) {
5506   // VBROADCAST requires AVX.
5507   // TODO: Splats could be generated for non-AVX CPUs using SSE
5508   // instructions, but there's less potential gain for only 128-bit vectors.
5509   if (!Subtarget->hasAVX())
5510     return SDValue();
5511
5512   MVT VT = Op.getSimpleValueType();
5513   SDLoc dl(Op);
5514
5515   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5516          "Unsupported vector type for broadcast.");
5517
5518   SDValue Ld;
5519   bool ConstSplatVal;
5520
5521   switch (Op.getOpcode()) {
5522     default:
5523       // Unknown pattern found.
5524       return SDValue();
5525
5526     case ISD::BUILD_VECTOR: {
5527       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5528       BitVector UndefElements;
5529       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5530
5531       // We need a splat of a single value to use broadcast, and it doesn't
5532       // make any sense if the value is only in one element of the vector.
5533       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5534         return SDValue();
5535
5536       Ld = Splat;
5537       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5538                        Ld.getOpcode() == ISD::ConstantFP);
5539
5540       // Make sure that all of the users of a non-constant load are from the
5541       // BUILD_VECTOR node.
5542       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5543         return SDValue();
5544       break;
5545     }
5546
5547     case ISD::VECTOR_SHUFFLE: {
5548       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5549
5550       // Shuffles must have a splat mask where the first element is
5551       // broadcasted.
5552       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5553         return SDValue();
5554
5555       SDValue Sc = Op.getOperand(0);
5556       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5557           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5558
5559         if (!Subtarget->hasInt256())
5560           return SDValue();
5561
5562         // Use the register form of the broadcast instruction available on AVX2.
5563         if (VT.getSizeInBits() >= 256)
5564           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5565         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5566       }
5567
5568       Ld = Sc.getOperand(0);
5569       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5570                        Ld.getOpcode() == ISD::ConstantFP);
5571
5572       // The scalar_to_vector node and the suspected
5573       // load node must have exactly one user.
5574       // Constants may have multiple users.
5575
5576       // AVX-512 has register version of the broadcast
5577       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5578         Ld.getValueType().getSizeInBits() >= 32;
5579       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5580           !hasRegVer))
5581         return SDValue();
5582       break;
5583     }
5584   }
5585
5586   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5587   bool IsGE256 = (VT.getSizeInBits() >= 256);
5588
5589   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5590   // instruction to save 8 or more bytes of constant pool data.
5591   // TODO: If multiple splats are generated to load the same constant,
5592   // it may be detrimental to overall size. There needs to be a way to detect
5593   // that condition to know if this is truly a size win.
5594   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5595
5596   // Handle broadcasting a single constant scalar from the constant pool
5597   // into a vector.
5598   // On Sandybridge (no AVX2), it is still better to load a constant vector
5599   // from the constant pool and not to broadcast it from a scalar.
5600   // But override that restriction when optimizing for size.
5601   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5602   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5603     EVT CVT = Ld.getValueType();
5604     assert(!CVT.isVector() && "Must not broadcast a vector type");
5605
5606     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5607     // For size optimization, also splat v2f64 and v2i64, and for size opt
5608     // with AVX2, also splat i8 and i16.
5609     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5610     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5611         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5612       const Constant *C = nullptr;
5613       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5614         C = CI->getConstantIntValue();
5615       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5616         C = CF->getConstantFPValue();
5617
5618       assert(C && "Invalid constant type");
5619
5620       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5621       SDValue CP =
5622           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5623       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5624       Ld = DAG.getLoad(
5625           CVT, dl, DAG.getEntryNode(), CP,
5626           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5627           false, false, Alignment);
5628
5629       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5630     }
5631   }
5632
5633   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5634
5635   // Handle AVX2 in-register broadcasts.
5636   if (!IsLoad && Subtarget->hasInt256() &&
5637       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5638     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5639
5640   // The scalar source must be a normal load.
5641   if (!IsLoad)
5642     return SDValue();
5643
5644   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5645       (Subtarget->hasVLX() && ScalarSize == 64))
5646     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5647
5648   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5649   // double since there is no vbroadcastsd xmm
5650   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5651     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5652       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5653   }
5654
5655   // Unsupported broadcast.
5656   return SDValue();
5657 }
5658
5659 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5660 /// underlying vector and index.
5661 ///
5662 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5663 /// index.
5664 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5665                                          SDValue ExtIdx) {
5666   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5667   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5668     return Idx;
5669
5670   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5671   // lowered this:
5672   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5673   // to:
5674   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5675   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5676   //                           undef)
5677   //                       Constant<0>)
5678   // In this case the vector is the extract_subvector expression and the index
5679   // is 2, as specified by the shuffle.
5680   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5681   SDValue ShuffleVec = SVOp->getOperand(0);
5682   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5683   assert(ShuffleVecVT.getVectorElementType() ==
5684          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5685
5686   int ShuffleIdx = SVOp->getMaskElt(Idx);
5687   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5688     ExtractedFromVec = ShuffleVec;
5689     return ShuffleIdx;
5690   }
5691   return Idx;
5692 }
5693
5694 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5695   MVT VT = Op.getSimpleValueType();
5696
5697   // Skip if insert_vec_elt is not supported.
5698   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5699   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5700     return SDValue();
5701
5702   SDLoc DL(Op);
5703   unsigned NumElems = Op.getNumOperands();
5704
5705   SDValue VecIn1;
5706   SDValue VecIn2;
5707   SmallVector<unsigned, 4> InsertIndices;
5708   SmallVector<int, 8> Mask(NumElems, -1);
5709
5710   for (unsigned i = 0; i != NumElems; ++i) {
5711     unsigned Opc = Op.getOperand(i).getOpcode();
5712
5713     if (Opc == ISD::UNDEF)
5714       continue;
5715
5716     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5717       // Quit if more than 1 elements need inserting.
5718       if (InsertIndices.size() > 1)
5719         return SDValue();
5720
5721       InsertIndices.push_back(i);
5722       continue;
5723     }
5724
5725     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5726     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5727     // Quit if non-constant index.
5728     if (!isa<ConstantSDNode>(ExtIdx))
5729       return SDValue();
5730     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5731
5732     // Quit if extracted from vector of different type.
5733     if (ExtractedFromVec.getValueType() != VT)
5734       return SDValue();
5735
5736     if (!VecIn1.getNode())
5737       VecIn1 = ExtractedFromVec;
5738     else if (VecIn1 != ExtractedFromVec) {
5739       if (!VecIn2.getNode())
5740         VecIn2 = ExtractedFromVec;
5741       else if (VecIn2 != ExtractedFromVec)
5742         // Quit if more than 2 vectors to shuffle
5743         return SDValue();
5744     }
5745
5746     if (ExtractedFromVec == VecIn1)
5747       Mask[i] = Idx;
5748     else if (ExtractedFromVec == VecIn2)
5749       Mask[i] = Idx + NumElems;
5750   }
5751
5752   if (!VecIn1.getNode())
5753     return SDValue();
5754
5755   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5756   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5757   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5758     unsigned Idx = InsertIndices[i];
5759     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5760                      DAG.getIntPtrConstant(Idx, DL));
5761   }
5762
5763   return NV;
5764 }
5765
5766 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5767   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5768          Op.getScalarValueSizeInBits() == 1 &&
5769          "Can not convert non-constant vector");
5770   uint64_t Immediate = 0;
5771   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5772     SDValue In = Op.getOperand(idx);
5773     if (In.getOpcode() != ISD::UNDEF)
5774       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5775   }
5776   SDLoc dl(Op);
5777   MVT VT =
5778    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5779   return DAG.getConstant(Immediate, dl, VT);
5780 }
5781 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5782 SDValue
5783 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5784
5785   MVT VT = Op.getSimpleValueType();
5786   assert((VT.getVectorElementType() == MVT::i1) &&
5787          "Unexpected type in LowerBUILD_VECTORvXi1!");
5788
5789   SDLoc dl(Op);
5790   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5791     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5792     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5793     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5794   }
5795
5796   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5797     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5798     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5799     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5800   }
5801
5802   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5803     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5804     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5805       return DAG.getBitcast(VT, Imm);
5806     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5807     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5808                         DAG.getIntPtrConstant(0, dl));
5809   }
5810
5811   // Vector has one or more non-const elements
5812   uint64_t Immediate = 0;
5813   SmallVector<unsigned, 16> NonConstIdx;
5814   bool IsSplat = true;
5815   bool HasConstElts = false;
5816   int SplatIdx = -1;
5817   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5818     SDValue In = Op.getOperand(idx);
5819     if (In.getOpcode() == ISD::UNDEF)
5820       continue;
5821     if (!isa<ConstantSDNode>(In))
5822       NonConstIdx.push_back(idx);
5823     else {
5824       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5825       HasConstElts = true;
5826     }
5827     if (SplatIdx == -1)
5828       SplatIdx = idx;
5829     else if (In != Op.getOperand(SplatIdx))
5830       IsSplat = false;
5831   }
5832
5833   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5834   if (IsSplat)
5835     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5836                        DAG.getConstant(1, dl, VT),
5837                        DAG.getConstant(0, dl, VT));
5838
5839   // insert elements one by one
5840   SDValue DstVec;
5841   SDValue Imm;
5842   if (Immediate) {
5843     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5844     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5845   }
5846   else if (HasConstElts)
5847     Imm = DAG.getConstant(0, dl, VT);
5848   else
5849     Imm = DAG.getUNDEF(VT);
5850   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5851     DstVec = DAG.getBitcast(VT, Imm);
5852   else {
5853     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5854     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5855                          DAG.getIntPtrConstant(0, dl));
5856   }
5857
5858   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5859     unsigned InsertIdx = NonConstIdx[i];
5860     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5861                          Op.getOperand(InsertIdx),
5862                          DAG.getIntPtrConstant(InsertIdx, dl));
5863   }
5864   return DstVec;
5865 }
5866
5867 /// \brief Return true if \p N implements a horizontal binop and return the
5868 /// operands for the horizontal binop into V0 and V1.
5869 ///
5870 /// This is a helper function of LowerToHorizontalOp().
5871 /// This function checks that the build_vector \p N in input implements a
5872 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5873 /// operation to match.
5874 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5875 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5876 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5877 /// arithmetic sub.
5878 ///
5879 /// This function only analyzes elements of \p N whose indices are
5880 /// in range [BaseIdx, LastIdx).
5881 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5882                               SelectionDAG &DAG,
5883                               unsigned BaseIdx, unsigned LastIdx,
5884                               SDValue &V0, SDValue &V1) {
5885   EVT VT = N->getValueType(0);
5886
5887   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5888   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5889          "Invalid Vector in input!");
5890
5891   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5892   bool CanFold = true;
5893   unsigned ExpectedVExtractIdx = BaseIdx;
5894   unsigned NumElts = LastIdx - BaseIdx;
5895   V0 = DAG.getUNDEF(VT);
5896   V1 = DAG.getUNDEF(VT);
5897
5898   // Check if N implements a horizontal binop.
5899   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5900     SDValue Op = N->getOperand(i + BaseIdx);
5901
5902     // Skip UNDEFs.
5903     if (Op->getOpcode() == ISD::UNDEF) {
5904       // Update the expected vector extract index.
5905       if (i * 2 == NumElts)
5906         ExpectedVExtractIdx = BaseIdx;
5907       ExpectedVExtractIdx += 2;
5908       continue;
5909     }
5910
5911     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5912
5913     if (!CanFold)
5914       break;
5915
5916     SDValue Op0 = Op.getOperand(0);
5917     SDValue Op1 = Op.getOperand(1);
5918
5919     // Try to match the following pattern:
5920     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5921     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5922         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5923         Op0.getOperand(0) == Op1.getOperand(0) &&
5924         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5925         isa<ConstantSDNode>(Op1.getOperand(1)));
5926     if (!CanFold)
5927       break;
5928
5929     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5930     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5931
5932     if (i * 2 < NumElts) {
5933       if (V0.getOpcode() == ISD::UNDEF) {
5934         V0 = Op0.getOperand(0);
5935         if (V0.getValueType() != VT)
5936           return false;
5937       }
5938     } else {
5939       if (V1.getOpcode() == ISD::UNDEF) {
5940         V1 = Op0.getOperand(0);
5941         if (V1.getValueType() != VT)
5942           return false;
5943       }
5944       if (i * 2 == NumElts)
5945         ExpectedVExtractIdx = BaseIdx;
5946     }
5947
5948     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5949     if (I0 == ExpectedVExtractIdx)
5950       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5951     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5952       // Try to match the following dag sequence:
5953       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5954       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5955     } else
5956       CanFold = false;
5957
5958     ExpectedVExtractIdx += 2;
5959   }
5960
5961   return CanFold;
5962 }
5963
5964 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5965 /// a concat_vector.
5966 ///
5967 /// This is a helper function of LowerToHorizontalOp().
5968 /// This function expects two 256-bit vectors called V0 and V1.
5969 /// At first, each vector is split into two separate 128-bit vectors.
5970 /// Then, the resulting 128-bit vectors are used to implement two
5971 /// horizontal binary operations.
5972 ///
5973 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5974 ///
5975 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5976 /// the two new horizontal binop.
5977 /// When Mode is set, the first horizontal binop dag node would take as input
5978 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5979 /// horizontal binop dag node would take as input the lower 128-bit of V1
5980 /// and the upper 128-bit of V1.
5981 ///   Example:
5982 ///     HADD V0_LO, V0_HI
5983 ///     HADD V1_LO, V1_HI
5984 ///
5985 /// Otherwise, the first horizontal binop dag node takes as input the lower
5986 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5987 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5988 ///   Example:
5989 ///     HADD V0_LO, V1_LO
5990 ///     HADD V0_HI, V1_HI
5991 ///
5992 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5993 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5994 /// the upper 128-bits of the result.
5995 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5996                                      SDLoc DL, SelectionDAG &DAG,
5997                                      unsigned X86Opcode, bool Mode,
5998                                      bool isUndefLO, bool isUndefHI) {
5999   EVT VT = V0.getValueType();
6000   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6001          "Invalid nodes in input!");
6002
6003   unsigned NumElts = VT.getVectorNumElements();
6004   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6005   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6006   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6007   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6008   EVT NewVT = V0_LO.getValueType();
6009
6010   SDValue LO = DAG.getUNDEF(NewVT);
6011   SDValue HI = DAG.getUNDEF(NewVT);
6012
6013   if (Mode) {
6014     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6015     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6016       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6017     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6018       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6019   } else {
6020     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6021     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6022                        V1_LO->getOpcode() != ISD::UNDEF))
6023       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6024
6025     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6026                        V1_HI->getOpcode() != ISD::UNDEF))
6027       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6028   }
6029
6030   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6031 }
6032
6033 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6034 /// node.
6035 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6036                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6037   MVT VT = BV->getSimpleValueType(0);
6038   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6039       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6040     return SDValue();
6041
6042   SDLoc DL(BV);
6043   unsigned NumElts = VT.getVectorNumElements();
6044   SDValue InVec0 = DAG.getUNDEF(VT);
6045   SDValue InVec1 = DAG.getUNDEF(VT);
6046
6047   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6048           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6049
6050   // Odd-numbered elements in the input build vector are obtained from
6051   // adding two integer/float elements.
6052   // Even-numbered elements in the input build vector are obtained from
6053   // subtracting two integer/float elements.
6054   unsigned ExpectedOpcode = ISD::FSUB;
6055   unsigned NextExpectedOpcode = ISD::FADD;
6056   bool AddFound = false;
6057   bool SubFound = false;
6058
6059   for (unsigned i = 0, e = NumElts; i != e; ++i) {
6060     SDValue Op = BV->getOperand(i);
6061
6062     // Skip 'undef' values.
6063     unsigned Opcode = Op.getOpcode();
6064     if (Opcode == ISD::UNDEF) {
6065       std::swap(ExpectedOpcode, NextExpectedOpcode);
6066       continue;
6067     }
6068
6069     // Early exit if we found an unexpected opcode.
6070     if (Opcode != ExpectedOpcode)
6071       return SDValue();
6072
6073     SDValue Op0 = Op.getOperand(0);
6074     SDValue Op1 = Op.getOperand(1);
6075
6076     // Try to match the following pattern:
6077     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6078     // Early exit if we cannot match that sequence.
6079     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6080         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6081         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6082         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6083         Op0.getOperand(1) != Op1.getOperand(1))
6084       return SDValue();
6085
6086     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6087     if (I0 != i)
6088       return SDValue();
6089
6090     // We found a valid add/sub node. Update the information accordingly.
6091     if (i & 1)
6092       AddFound = true;
6093     else
6094       SubFound = true;
6095
6096     // Update InVec0 and InVec1.
6097     if (InVec0.getOpcode() == ISD::UNDEF) {
6098       InVec0 = Op0.getOperand(0);
6099       if (InVec0.getSimpleValueType() != VT)
6100         return SDValue();
6101     }
6102     if (InVec1.getOpcode() == ISD::UNDEF) {
6103       InVec1 = Op1.getOperand(0);
6104       if (InVec1.getSimpleValueType() != VT)
6105         return SDValue();
6106     }
6107
6108     // Make sure that operands in input to each add/sub node always
6109     // come from a same pair of vectors.
6110     if (InVec0 != Op0.getOperand(0)) {
6111       if (ExpectedOpcode == ISD::FSUB)
6112         return SDValue();
6113
6114       // FADD is commutable. Try to commute the operands
6115       // and then test again.
6116       std::swap(Op0, Op1);
6117       if (InVec0 != Op0.getOperand(0))
6118         return SDValue();
6119     }
6120
6121     if (InVec1 != Op1.getOperand(0))
6122       return SDValue();
6123
6124     // Update the pair of expected opcodes.
6125     std::swap(ExpectedOpcode, NextExpectedOpcode);
6126   }
6127
6128   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6129   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6130       InVec1.getOpcode() != ISD::UNDEF)
6131     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6132
6133   return SDValue();
6134 }
6135
6136 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6137 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6138                                    const X86Subtarget *Subtarget,
6139                                    SelectionDAG &DAG) {
6140   MVT VT = BV->getSimpleValueType(0);
6141   unsigned NumElts = VT.getVectorNumElements();
6142   unsigned NumUndefsLO = 0;
6143   unsigned NumUndefsHI = 0;
6144   unsigned Half = NumElts/2;
6145
6146   // Count the number of UNDEF operands in the build_vector in input.
6147   for (unsigned i = 0, e = Half; i != e; ++i)
6148     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6149       NumUndefsLO++;
6150
6151   for (unsigned i = Half, e = NumElts; i != e; ++i)
6152     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6153       NumUndefsHI++;
6154
6155   // Early exit if this is either a build_vector of all UNDEFs or all the
6156   // operands but one are UNDEF.
6157   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6158     return SDValue();
6159
6160   SDLoc DL(BV);
6161   SDValue InVec0, InVec1;
6162   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6163     // Try to match an SSE3 float HADD/HSUB.
6164     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6165       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6166
6167     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6168       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6169   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6170     // Try to match an SSSE3 integer HADD/HSUB.
6171     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6172       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6173
6174     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6175       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6176   }
6177
6178   if (!Subtarget->hasAVX())
6179     return SDValue();
6180
6181   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6182     // Try to match an AVX horizontal add/sub of packed single/double
6183     // precision floating point values from 256-bit vectors.
6184     SDValue InVec2, InVec3;
6185     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6186         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6187         ((InVec0.getOpcode() == ISD::UNDEF ||
6188           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6189         ((InVec1.getOpcode() == ISD::UNDEF ||
6190           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6191       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6192
6193     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6194         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6195         ((InVec0.getOpcode() == ISD::UNDEF ||
6196           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6197         ((InVec1.getOpcode() == ISD::UNDEF ||
6198           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6199       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6200   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6201     // Try to match an AVX2 horizontal add/sub of signed integers.
6202     SDValue InVec2, InVec3;
6203     unsigned X86Opcode;
6204     bool CanFold = true;
6205
6206     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6207         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6208         ((InVec0.getOpcode() == ISD::UNDEF ||
6209           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6210         ((InVec1.getOpcode() == ISD::UNDEF ||
6211           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6212       X86Opcode = X86ISD::HADD;
6213     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6214         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6215         ((InVec0.getOpcode() == ISD::UNDEF ||
6216           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6217         ((InVec1.getOpcode() == ISD::UNDEF ||
6218           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6219       X86Opcode = X86ISD::HSUB;
6220     else
6221       CanFold = false;
6222
6223     if (CanFold) {
6224       // Fold this build_vector into a single horizontal add/sub.
6225       // Do this only if the target has AVX2.
6226       if (Subtarget->hasAVX2())
6227         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6228
6229       // Do not try to expand this build_vector into a pair of horizontal
6230       // add/sub if we can emit a pair of scalar add/sub.
6231       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6232         return SDValue();
6233
6234       // Convert this build_vector into a pair of horizontal binop followed by
6235       // a concat vector.
6236       bool isUndefLO = NumUndefsLO == Half;
6237       bool isUndefHI = NumUndefsHI == Half;
6238       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6239                                    isUndefLO, isUndefHI);
6240     }
6241   }
6242
6243   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6244        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6245     unsigned X86Opcode;
6246     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6247       X86Opcode = X86ISD::HADD;
6248     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6249       X86Opcode = X86ISD::HSUB;
6250     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6251       X86Opcode = X86ISD::FHADD;
6252     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6253       X86Opcode = X86ISD::FHSUB;
6254     else
6255       return SDValue();
6256
6257     // Don't try to expand this build_vector into a pair of horizontal add/sub
6258     // if we can simply emit a pair of scalar add/sub.
6259     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6260       return SDValue();
6261
6262     // Convert this build_vector into two horizontal add/sub followed by
6263     // a concat vector.
6264     bool isUndefLO = NumUndefsLO == Half;
6265     bool isUndefHI = NumUndefsHI == Half;
6266     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6267                                  isUndefLO, isUndefHI);
6268   }
6269
6270   return SDValue();
6271 }
6272
6273 SDValue
6274 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6275   SDLoc dl(Op);
6276
6277   MVT VT = Op.getSimpleValueType();
6278   MVT ExtVT = VT.getVectorElementType();
6279   unsigned NumElems = Op.getNumOperands();
6280
6281   // Generate vectors for predicate vectors.
6282   if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6283     return LowerBUILD_VECTORvXi1(Op, DAG);
6284
6285   // Vectors containing all zeros can be matched by pxor and xorps later
6286   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6287     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6288     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6289     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6290       return Op;
6291
6292     return getZeroVector(VT, Subtarget, DAG, dl);
6293   }
6294
6295   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6296   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6297   // vpcmpeqd on 256-bit vectors.
6298   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6299     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6300       return Op;
6301
6302     if (!VT.is512BitVector())
6303       return getOnesVector(VT, Subtarget, DAG, dl);
6304   }
6305
6306   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6307   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6308     return AddSub;
6309   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6310     return HorizontalOp;
6311   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6312     return Broadcast;
6313
6314   unsigned EVTBits = ExtVT.getSizeInBits();
6315
6316   unsigned NumZero  = 0;
6317   unsigned NumNonZero = 0;
6318   uint64_t NonZeros = 0;
6319   bool IsAllConstants = true;
6320   SmallSet<SDValue, 8> Values;
6321   for (unsigned i = 0; i < NumElems; ++i) {
6322     SDValue Elt = Op.getOperand(i);
6323     if (Elt.getOpcode() == ISD::UNDEF)
6324       continue;
6325     Values.insert(Elt);
6326     if (Elt.getOpcode() != ISD::Constant &&
6327         Elt.getOpcode() != ISD::ConstantFP)
6328       IsAllConstants = false;
6329     if (X86::isZeroNode(Elt))
6330       NumZero++;
6331     else {
6332       assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6333       NonZeros |= ((uint64_t)1 << i);
6334       NumNonZero++;
6335     }
6336   }
6337
6338   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6339   if (NumNonZero == 0)
6340     return DAG.getUNDEF(VT);
6341
6342   // Special case for single non-zero, non-undef, element.
6343   if (NumNonZero == 1) {
6344     unsigned Idx = countTrailingZeros(NonZeros);
6345     SDValue Item = Op.getOperand(Idx);
6346
6347     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6348     // the value are obviously zero, truncate the value to i32 and do the
6349     // insertion that way.  Only do this if the value is non-constant or if the
6350     // value is a constant being inserted into element 0.  It is cheaper to do
6351     // a constant pool load than it is to do a movd + shuffle.
6352     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6353         (!IsAllConstants || Idx == 0)) {
6354       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6355         // Handle SSE only.
6356         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6357         MVT VecVT = MVT::v4i32;
6358
6359         // Truncate the value (which may itself be a constant) to i32, and
6360         // convert it to a vector with movd (S2V+shuffle to zero extend).
6361         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6362         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6363         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6364                                       Item, Idx * 2, true, Subtarget, DAG));
6365       }
6366     }
6367
6368     // If we have a constant or non-constant insertion into the low element of
6369     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6370     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6371     // depending on what the source datatype is.
6372     if (Idx == 0) {
6373       if (NumZero == 0)
6374         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6375
6376       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6377           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6378         if (VT.is512BitVector()) {
6379           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6380           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6381                              Item, DAG.getIntPtrConstant(0, dl));
6382         }
6383         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6384                "Expected an SSE value type!");
6385         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6386         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6387         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6388       }
6389
6390       // We can't directly insert an i8 or i16 into a vector, so zero extend
6391       // it to i32 first.
6392       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6393         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6394         if (VT.is256BitVector()) {
6395           if (Subtarget->hasAVX()) {
6396             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6397             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6398           } else {
6399             // Without AVX, we need to extend to a 128-bit vector and then
6400             // insert into the 256-bit vector.
6401             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6402             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6403             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6404           }
6405         } else {
6406           assert(VT.is128BitVector() && "Expected an SSE value type!");
6407           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6408           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6409         }
6410         return DAG.getBitcast(VT, Item);
6411       }
6412     }
6413
6414     // Is it a vector logical left shift?
6415     if (NumElems == 2 && Idx == 1 &&
6416         X86::isZeroNode(Op.getOperand(0)) &&
6417         !X86::isZeroNode(Op.getOperand(1))) {
6418       unsigned NumBits = VT.getSizeInBits();
6419       return getVShift(true, VT,
6420                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6421                                    VT, Op.getOperand(1)),
6422                        NumBits/2, DAG, *this, dl);
6423     }
6424
6425     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6426       return SDValue();
6427
6428     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6429     // is a non-constant being inserted into an element other than the low one,
6430     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6431     // movd/movss) to move this into the low element, then shuffle it into
6432     // place.
6433     if (EVTBits == 32) {
6434       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6435       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6436     }
6437   }
6438
6439   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6440   if (Values.size() == 1) {
6441     if (EVTBits == 32) {
6442       // Instead of a shuffle like this:
6443       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6444       // Check if it's possible to issue this instead.
6445       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6446       unsigned Idx = countTrailingZeros(NonZeros);
6447       SDValue Item = Op.getOperand(Idx);
6448       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6449         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6450     }
6451     return SDValue();
6452   }
6453
6454   // A vector full of immediates; various special cases are already
6455   // handled, so this is best done with a single constant-pool load.
6456   if (IsAllConstants)
6457     return SDValue();
6458
6459   // For AVX-length vectors, see if we can use a vector load to get all of the
6460   // elements, otherwise build the individual 128-bit pieces and use
6461   // shuffles to put them in place.
6462   if (VT.is256BitVector() || VT.is512BitVector()) {
6463     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6464
6465     // Check for a build vector of consecutive loads.
6466     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6467       return LD;
6468
6469     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6470
6471     // Build both the lower and upper subvector.
6472     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6473                                 makeArrayRef(&V[0], NumElems/2));
6474     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6475                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6476
6477     // Recreate the wider vector with the lower and upper part.
6478     if (VT.is256BitVector())
6479       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6480     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6481   }
6482
6483   // Let legalizer expand 2-wide build_vectors.
6484   if (EVTBits == 64) {
6485     if (NumNonZero == 1) {
6486       // One half is zero or undef.
6487       unsigned Idx = countTrailingZeros(NonZeros);
6488       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6489                                Op.getOperand(Idx));
6490       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6491     }
6492     return SDValue();
6493   }
6494
6495   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6496   if (EVTBits == 8 && NumElems == 16)
6497     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6498                                           DAG, Subtarget, *this))
6499       return V;
6500
6501   if (EVTBits == 16 && NumElems == 8)
6502     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6503                                           DAG, Subtarget, *this))
6504       return V;
6505
6506   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6507   if (EVTBits == 32 && NumElems == 4)
6508     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6509       return V;
6510
6511   // If element VT is == 32 bits, turn it into a number of shuffles.
6512   SmallVector<SDValue, 8> V(NumElems);
6513   if (NumElems == 4 && NumZero > 0) {
6514     for (unsigned i = 0; i < 4; ++i) {
6515       bool isZero = !(NonZeros & (1ULL << i));
6516       if (isZero)
6517         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6518       else
6519         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6520     }
6521
6522     for (unsigned i = 0; i < 2; ++i) {
6523       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6524         default: break;
6525         case 0:
6526           V[i] = V[i*2];  // Must be a zero vector.
6527           break;
6528         case 1:
6529           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6530           break;
6531         case 2:
6532           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6533           break;
6534         case 3:
6535           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6536           break;
6537       }
6538     }
6539
6540     bool Reverse1 = (NonZeros & 0x3) == 2;
6541     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6542     int MaskVec[] = {
6543       Reverse1 ? 1 : 0,
6544       Reverse1 ? 0 : 1,
6545       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6546       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6547     };
6548     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6549   }
6550
6551   if (Values.size() > 1 && VT.is128BitVector()) {
6552     // Check for a build vector of consecutive loads.
6553     for (unsigned i = 0; i < NumElems; ++i)
6554       V[i] = Op.getOperand(i);
6555
6556     // Check for elements which are consecutive loads.
6557     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6558       return LD;
6559
6560     // Check for a build vector from mostly shuffle plus few inserting.
6561     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6562       return Sh;
6563
6564     // For SSE 4.1, use insertps to put the high elements into the low element.
6565     if (Subtarget->hasSSE41()) {
6566       SDValue Result;
6567       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6568         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6569       else
6570         Result = DAG.getUNDEF(VT);
6571
6572       for (unsigned i = 1; i < NumElems; ++i) {
6573         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6574         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6575                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6576       }
6577       return Result;
6578     }
6579
6580     // Otherwise, expand into a number of unpckl*, start by extending each of
6581     // our (non-undef) elements to the full vector width with the element in the
6582     // bottom slot of the vector (which generates no code for SSE).
6583     for (unsigned i = 0; i < NumElems; ++i) {
6584       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6585         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6586       else
6587         V[i] = DAG.getUNDEF(VT);
6588     }
6589
6590     // Next, we iteratively mix elements, e.g. for v4f32:
6591     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6592     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6593     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6594     unsigned EltStride = NumElems >> 1;
6595     while (EltStride != 0) {
6596       for (unsigned i = 0; i < EltStride; ++i) {
6597         // If V[i+EltStride] is undef and this is the first round of mixing,
6598         // then it is safe to just drop this shuffle: V[i] is already in the
6599         // right place, the one element (since it's the first round) being
6600         // inserted as undef can be dropped.  This isn't safe for successive
6601         // rounds because they will permute elements within both vectors.
6602         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6603             EltStride == NumElems/2)
6604           continue;
6605
6606         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6607       }
6608       EltStride >>= 1;
6609     }
6610     return V[0];
6611   }
6612   return SDValue();
6613 }
6614
6615 // 256-bit AVX can use the vinsertf128 instruction
6616 // to create 256-bit vectors from two other 128-bit ones.
6617 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6618   SDLoc dl(Op);
6619   MVT ResVT = Op.getSimpleValueType();
6620
6621   assert((ResVT.is256BitVector() ||
6622           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6623
6624   SDValue V1 = Op.getOperand(0);
6625   SDValue V2 = Op.getOperand(1);
6626   unsigned NumElems = ResVT.getVectorNumElements();
6627   if (ResVT.is256BitVector())
6628     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6629
6630   if (Op.getNumOperands() == 4) {
6631     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6632                                   ResVT.getVectorNumElements()/2);
6633     SDValue V3 = Op.getOperand(2);
6634     SDValue V4 = Op.getOperand(3);
6635     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6636       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6637   }
6638   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6639 }
6640
6641 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6642                                        const X86Subtarget *Subtarget,
6643                                        SelectionDAG & DAG) {
6644   SDLoc dl(Op);
6645   MVT ResVT = Op.getSimpleValueType();
6646   unsigned NumOfOperands = Op.getNumOperands();
6647
6648   assert(isPowerOf2_32(NumOfOperands) &&
6649          "Unexpected number of operands in CONCAT_VECTORS");
6650
6651   SDValue Undef = DAG.getUNDEF(ResVT);
6652   if (NumOfOperands > 2) {
6653     // Specialize the cases when all, or all but one, of the operands are undef.
6654     unsigned NumOfDefinedOps = 0;
6655     unsigned OpIdx = 0;
6656     for (unsigned i = 0; i < NumOfOperands; i++)
6657       if (!Op.getOperand(i).isUndef()) {
6658         NumOfDefinedOps++;
6659         OpIdx = i;
6660       }
6661     if (NumOfDefinedOps == 0)
6662       return Undef;
6663     if (NumOfDefinedOps == 1) {
6664       unsigned SubVecNumElts =
6665         Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6666       SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6667       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6668                          Op.getOperand(OpIdx), IdxVal);
6669     }
6670
6671     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6672                                   ResVT.getVectorNumElements()/2);
6673     SmallVector<SDValue, 2> Ops;
6674     for (unsigned i = 0; i < NumOfOperands/2; i++)
6675       Ops.push_back(Op.getOperand(i));
6676     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6677     Ops.clear();
6678     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6679       Ops.push_back(Op.getOperand(i));
6680     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6681     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6682   }
6683
6684   // 2 operands
6685   SDValue V1 = Op.getOperand(0);
6686   SDValue V2 = Op.getOperand(1);
6687   unsigned NumElems = ResVT.getVectorNumElements();
6688   assert(V1.getValueType() == V2.getValueType() &&
6689          V1.getValueType().getVectorNumElements() == NumElems/2 &&
6690          "Unexpected operands in CONCAT_VECTORS");
6691
6692   if (ResVT.getSizeInBits() >= 16)
6693     return Op; // The operation is legal with KUNPCK
6694
6695   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6696   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6697   SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6698   if (IsZeroV1 && IsZeroV2)
6699     return ZeroVec;
6700
6701   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6702   if (V2.isUndef())
6703     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6704   if (IsZeroV2)
6705     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6706
6707   SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6708   if (V1.isUndef())
6709     V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6710
6711   if (IsZeroV1)
6712     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6713
6714   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6715   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6716 }
6717
6718 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6719                                    const X86Subtarget *Subtarget,
6720                                    SelectionDAG &DAG) {
6721   MVT VT = Op.getSimpleValueType();
6722   if (VT.getVectorElementType() == MVT::i1)
6723     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6724
6725   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6726          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6727           Op.getNumOperands() == 4)));
6728
6729   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6730   // from two other 128-bit ones.
6731
6732   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6733   return LowerAVXCONCAT_VECTORS(Op, DAG);
6734 }
6735
6736 //===----------------------------------------------------------------------===//
6737 // Vector shuffle lowering
6738 //
6739 // This is an experimental code path for lowering vector shuffles on x86. It is
6740 // designed to handle arbitrary vector shuffles and blends, gracefully
6741 // degrading performance as necessary. It works hard to recognize idiomatic
6742 // shuffles and lower them to optimal instruction patterns without leaving
6743 // a framework that allows reasonably efficient handling of all vector shuffle
6744 // patterns.
6745 //===----------------------------------------------------------------------===//
6746
6747 /// \brief Tiny helper function to identify a no-op mask.
6748 ///
6749 /// This is a somewhat boring predicate function. It checks whether the mask
6750 /// array input, which is assumed to be a single-input shuffle mask of the kind
6751 /// used by the X86 shuffle instructions (not a fully general
6752 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6753 /// in-place shuffle are 'no-op's.
6754 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6755   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6756     if (Mask[i] != -1 && Mask[i] != i)
6757       return false;
6758   return true;
6759 }
6760
6761 /// \brief Helper function to classify a mask as a single-input mask.
6762 ///
6763 /// This isn't a generic single-input test because in the vector shuffle
6764 /// lowering we canonicalize single inputs to be the first input operand. This
6765 /// means we can more quickly test for a single input by only checking whether
6766 /// an input from the second operand exists. We also assume that the size of
6767 /// mask corresponds to the size of the input vectors which isn't true in the
6768 /// fully general case.
6769 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6770   for (int M : Mask)
6771     if (M >= (int)Mask.size())
6772       return false;
6773   return true;
6774 }
6775
6776 /// \brief Test whether there are elements crossing 128-bit lanes in this
6777 /// shuffle mask.
6778 ///
6779 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6780 /// and we routinely test for these.
6781 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6782   int LaneSize = 128 / VT.getScalarSizeInBits();
6783   int Size = Mask.size();
6784   for (int i = 0; i < Size; ++i)
6785     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6786       return true;
6787   return false;
6788 }
6789
6790 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6791 ///
6792 /// This checks a shuffle mask to see if it is performing the same
6793 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6794 /// that it is also not lane-crossing. It may however involve a blend from the
6795 /// same lane of a second vector.
6796 ///
6797 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6798 /// non-trivial to compute in the face of undef lanes. The representation is
6799 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6800 /// entries from both V1 and V2 inputs to the wider mask.
6801 static bool
6802 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6803                                 SmallVectorImpl<int> &RepeatedMask) {
6804   int LaneSize = 128 / VT.getScalarSizeInBits();
6805   RepeatedMask.resize(LaneSize, -1);
6806   int Size = Mask.size();
6807   for (int i = 0; i < Size; ++i) {
6808     if (Mask[i] < 0)
6809       continue;
6810     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6811       // This entry crosses lanes, so there is no way to model this shuffle.
6812       return false;
6813
6814     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6815     if (RepeatedMask[i % LaneSize] == -1)
6816       // This is the first non-undef entry in this slot of a 128-bit lane.
6817       RepeatedMask[i % LaneSize] =
6818           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6819     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6820       // Found a mismatch with the repeated mask.
6821       return false;
6822   }
6823   return true;
6824 }
6825
6826 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6827 /// arguments.
6828 ///
6829 /// This is a fast way to test a shuffle mask against a fixed pattern:
6830 ///
6831 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6832 ///
6833 /// It returns true if the mask is exactly as wide as the argument list, and
6834 /// each element of the mask is either -1 (signifying undef) or the value given
6835 /// in the argument.
6836 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6837                                 ArrayRef<int> ExpectedMask) {
6838   if (Mask.size() != ExpectedMask.size())
6839     return false;
6840
6841   int Size = Mask.size();
6842
6843   // If the values are build vectors, we can look through them to find
6844   // equivalent inputs that make the shuffles equivalent.
6845   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6846   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6847
6848   for (int i = 0; i < Size; ++i)
6849     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6850       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6851       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6852       if (!MaskBV || !ExpectedBV ||
6853           MaskBV->getOperand(Mask[i] % Size) !=
6854               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6855         return false;
6856     }
6857
6858   return true;
6859 }
6860
6861 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6862 ///
6863 /// This helper function produces an 8-bit shuffle immediate corresponding to
6864 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6865 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6866 /// example.
6867 ///
6868 /// NB: We rely heavily on "undef" masks preserving the input lane.
6869 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6870                                           SelectionDAG &DAG) {
6871   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6872   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6873   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6874   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6875   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6876
6877   unsigned Imm = 0;
6878   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6879   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6880   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6881   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6882   return DAG.getConstant(Imm, DL, MVT::i8);
6883 }
6884
6885 /// \brief Compute whether each element of a shuffle is zeroable.
6886 ///
6887 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6888 /// Either it is an undef element in the shuffle mask, the element of the input
6889 /// referenced is undef, or the element of the input referenced is known to be
6890 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6891 /// as many lanes with this technique as possible to simplify the remaining
6892 /// shuffle.
6893 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6894                                                      SDValue V1, SDValue V2) {
6895   SmallBitVector Zeroable(Mask.size(), false);
6896
6897   while (V1.getOpcode() == ISD::BITCAST)
6898     V1 = V1->getOperand(0);
6899   while (V2.getOpcode() == ISD::BITCAST)
6900     V2 = V2->getOperand(0);
6901
6902   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6903   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6904
6905   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6906     int M = Mask[i];
6907     // Handle the easy cases.
6908     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6909       Zeroable[i] = true;
6910       continue;
6911     }
6912
6913     // If this is an index into a build_vector node (which has the same number
6914     // of elements), dig out the input value and use it.
6915     SDValue V = M < Size ? V1 : V2;
6916     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6917       continue;
6918
6919     SDValue Input = V.getOperand(M % Size);
6920     // The UNDEF opcode check really should be dead code here, but not quite
6921     // worth asserting on (it isn't invalid, just unexpected).
6922     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6923       Zeroable[i] = true;
6924   }
6925
6926   return Zeroable;
6927 }
6928
6929 // X86 has dedicated unpack instructions that can handle specific blend
6930 // operations: UNPCKH and UNPCKL.
6931 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6932                                            SDValue V1, SDValue V2,
6933                                            SelectionDAG &DAG) {
6934   int NumElts = VT.getVectorNumElements();
6935   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6936   SmallVector<int, 8> Unpckl;
6937   SmallVector<int, 8> Unpckh;
6938
6939   for (int i = 0; i < NumElts; ++i) {
6940     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6941     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6942     int HiPos = LoPos + NumEltsInLane / 2;
6943     Unpckl.push_back(LoPos);
6944     Unpckh.push_back(HiPos);
6945   }
6946
6947   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6948     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6949   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6950     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6951
6952   // Commute and try again.
6953   ShuffleVectorSDNode::commuteMask(Unpckl);
6954   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6955     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6956
6957   ShuffleVectorSDNode::commuteMask(Unpckh);
6958   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6959     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6960
6961   return SDValue();
6962 }
6963
6964 /// \brief Try to emit a bitmask instruction for a shuffle.
6965 ///
6966 /// This handles cases where we can model a blend exactly as a bitmask due to
6967 /// one of the inputs being zeroable.
6968 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6969                                            SDValue V2, ArrayRef<int> Mask,
6970                                            SelectionDAG &DAG) {
6971   MVT EltVT = VT.getVectorElementType();
6972   int NumEltBits = EltVT.getSizeInBits();
6973   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6974   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6975   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6976                                     IntEltVT);
6977   if (EltVT.isFloatingPoint()) {
6978     Zero = DAG.getBitcast(EltVT, Zero);
6979     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6980   }
6981   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6982   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6983   SDValue V;
6984   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6985     if (Zeroable[i])
6986       continue;
6987     if (Mask[i] % Size != i)
6988       return SDValue(); // Not a blend.
6989     if (!V)
6990       V = Mask[i] < Size ? V1 : V2;
6991     else if (V != (Mask[i] < Size ? V1 : V2))
6992       return SDValue(); // Can only let one input through the mask.
6993
6994     VMaskOps[i] = AllOnes;
6995   }
6996   if (!V)
6997     return SDValue(); // No non-zeroable elements!
6998
6999   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
7000   V = DAG.getNode(VT.isFloatingPoint()
7001                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7002                   DL, VT, V, VMask);
7003   return V;
7004 }
7005
7006 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7007 ///
7008 /// This is used as a fallback approach when first class blend instructions are
7009 /// unavailable. Currently it is only suitable for integer vectors, but could
7010 /// be generalized for floating point vectors if desirable.
7011 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
7012                                             SDValue V2, ArrayRef<int> Mask,
7013                                             SelectionDAG &DAG) {
7014   assert(VT.isInteger() && "Only supports integer vector types!");
7015   MVT EltVT = VT.getVectorElementType();
7016   int NumEltBits = EltVT.getSizeInBits();
7017   SDValue Zero = DAG.getConstant(0, DL, EltVT);
7018   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7019                                     EltVT);
7020   SmallVector<SDValue, 16> MaskOps;
7021   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7022     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
7023       return SDValue(); // Shuffled input!
7024     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7025   }
7026
7027   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
7028   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7029   // We have to cast V2 around.
7030   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7031   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7032                                       DAG.getBitcast(MaskVT, V1Mask),
7033                                       DAG.getBitcast(MaskVT, V2)));
7034   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7035 }
7036
7037 /// \brief Try to emit a blend instruction for a shuffle.
7038 ///
7039 /// This doesn't do any checks for the availability of instructions for blending
7040 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7041 /// be matched in the backend with the type given. What it does check for is
7042 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7043 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7044                                          SDValue V2, ArrayRef<int> Original,
7045                                          const X86Subtarget *Subtarget,
7046                                          SelectionDAG &DAG) {
7047   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7048   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7049   SmallVector<int, 8> Mask(Original.begin(), Original.end());
7050   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7051   bool ForceV1Zero = false, ForceV2Zero = false;
7052
7053   // Attempt to generate the binary blend mask. If an input is zero then
7054   // we can use any lane.
7055   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7056   unsigned BlendMask = 0;
7057   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7058     int M = Mask[i];
7059     if (M < 0)
7060       continue;
7061     if (M == i)
7062       continue;
7063     if (M == i + Size) {
7064       BlendMask |= 1u << i;
7065       continue;
7066     }
7067     if (Zeroable[i]) {
7068       if (V1IsZero) {
7069         ForceV1Zero = true;
7070         Mask[i] = i;
7071         continue;
7072       }
7073       if (V2IsZero) {
7074         ForceV2Zero = true;
7075         BlendMask |= 1u << i;
7076         Mask[i] = i + Size;
7077         continue;
7078       }
7079     }
7080     return SDValue(); // Shuffled input!
7081   }
7082
7083   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7084   if (ForceV1Zero)
7085     V1 = getZeroVector(VT, Subtarget, DAG, DL);
7086   if (ForceV2Zero)
7087     V2 = getZeroVector(VT, Subtarget, DAG, DL);
7088
7089   auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7090     unsigned ScaledMask = 0;
7091     for (int i = 0; i != Size; ++i)
7092       if (BlendMask & (1u << i))
7093         for (int j = 0; j != Scale; ++j)
7094           ScaledMask |= 1u << (i * Scale + j);
7095     return ScaledMask;
7096   };
7097
7098   switch (VT.SimpleTy) {
7099   case MVT::v2f64:
7100   case MVT::v4f32:
7101   case MVT::v4f64:
7102   case MVT::v8f32:
7103     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7104                        DAG.getConstant(BlendMask, DL, MVT::i8));
7105
7106   case MVT::v4i64:
7107   case MVT::v8i32:
7108     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7109     // FALLTHROUGH
7110   case MVT::v2i64:
7111   case MVT::v4i32:
7112     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7113     // that instruction.
7114     if (Subtarget->hasAVX2()) {
7115       // Scale the blend by the number of 32-bit dwords per element.
7116       int Scale =  VT.getScalarSizeInBits() / 32;
7117       BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7118       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7119       V1 = DAG.getBitcast(BlendVT, V1);
7120       V2 = DAG.getBitcast(BlendVT, V2);
7121       return DAG.getBitcast(
7122           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7123                           DAG.getConstant(BlendMask, DL, MVT::i8)));
7124     }
7125     // FALLTHROUGH
7126   case MVT::v8i16: {
7127     // For integer shuffles we need to expand the mask and cast the inputs to
7128     // v8i16s prior to blending.
7129     int Scale = 8 / VT.getVectorNumElements();
7130     BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7131     V1 = DAG.getBitcast(MVT::v8i16, V1);
7132     V2 = DAG.getBitcast(MVT::v8i16, V2);
7133     return DAG.getBitcast(VT,
7134                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7135                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
7136   }
7137
7138   case MVT::v16i16: {
7139     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7140     SmallVector<int, 8> RepeatedMask;
7141     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7142       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7143       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7144       BlendMask = 0;
7145       for (int i = 0; i < 8; ++i)
7146         if (RepeatedMask[i] >= 16)
7147           BlendMask |= 1u << i;
7148       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7149                          DAG.getConstant(BlendMask, DL, MVT::i8));
7150     }
7151   }
7152     // FALLTHROUGH
7153   case MVT::v16i8:
7154   case MVT::v32i8: {
7155     assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7156            "256-bit byte-blends require AVX2 support!");
7157
7158     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7159     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7160       return Masked;
7161
7162     // Scale the blend by the number of bytes per element.
7163     int Scale = VT.getScalarSizeInBits() / 8;
7164
7165     // This form of blend is always done on bytes. Compute the byte vector
7166     // type.
7167     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7168
7169     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7170     // mix of LLVM's code generator and the x86 backend. We tell the code
7171     // generator that boolean values in the elements of an x86 vector register
7172     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7173     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7174     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7175     // of the element (the remaining are ignored) and 0 in that high bit would
7176     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7177     // the LLVM model for boolean values in vector elements gets the relevant
7178     // bit set, it is set backwards and over constrained relative to x86's
7179     // actual model.
7180     SmallVector<SDValue, 32> VSELECTMask;
7181     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7182       for (int j = 0; j < Scale; ++j)
7183         VSELECTMask.push_back(
7184             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7185                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7186                                           MVT::i8));
7187
7188     V1 = DAG.getBitcast(BlendVT, V1);
7189     V2 = DAG.getBitcast(BlendVT, V2);
7190     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7191                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7192                                                       BlendVT, VSELECTMask),
7193                                           V1, V2));
7194   }
7195
7196   default:
7197     llvm_unreachable("Not a supported integer vector type!");
7198   }
7199 }
7200
7201 /// \brief Try to lower as a blend of elements from two inputs followed by
7202 /// a single-input permutation.
7203 ///
7204 /// This matches the pattern where we can blend elements from two inputs and
7205 /// then reduce the shuffle to a single-input permutation.
7206 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7207                                                    SDValue V2,
7208                                                    ArrayRef<int> Mask,
7209                                                    SelectionDAG &DAG) {
7210   // We build up the blend mask while checking whether a blend is a viable way
7211   // to reduce the shuffle.
7212   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7213   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7214
7215   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7216     if (Mask[i] < 0)
7217       continue;
7218
7219     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7220
7221     if (BlendMask[Mask[i] % Size] == -1)
7222       BlendMask[Mask[i] % Size] = Mask[i];
7223     else if (BlendMask[Mask[i] % Size] != Mask[i])
7224       return SDValue(); // Can't blend in the needed input!
7225
7226     PermuteMask[i] = Mask[i] % Size;
7227   }
7228
7229   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7230   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7231 }
7232
7233 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7234 /// blends and permutes.
7235 ///
7236 /// This matches the extremely common pattern for handling combined
7237 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7238 /// operations. It will try to pick the best arrangement of shuffles and
7239 /// blends.
7240 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7241                                                           SDValue V1,
7242                                                           SDValue V2,
7243                                                           ArrayRef<int> Mask,
7244                                                           SelectionDAG &DAG) {
7245   // Shuffle the input elements into the desired positions in V1 and V2 and
7246   // blend them together.
7247   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7248   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7249   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7250   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7251     if (Mask[i] >= 0 && Mask[i] < Size) {
7252       V1Mask[i] = Mask[i];
7253       BlendMask[i] = i;
7254     } else if (Mask[i] >= Size) {
7255       V2Mask[i] = Mask[i] - Size;
7256       BlendMask[i] = i + Size;
7257     }
7258
7259   // Try to lower with the simpler initial blend strategy unless one of the
7260   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7261   // shuffle may be able to fold with a load or other benefit. However, when
7262   // we'll have to do 2x as many shuffles in order to achieve this, blending
7263   // first is a better strategy.
7264   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7265     if (SDValue BlendPerm =
7266             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7267       return BlendPerm;
7268
7269   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7270   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7271   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7272 }
7273
7274 /// \brief Try to lower a vector shuffle as a byte rotation.
7275 ///
7276 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7277 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7278 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7279 /// try to generically lower a vector shuffle through such an pattern. It
7280 /// does not check for the profitability of lowering either as PALIGNR or
7281 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7282 /// This matches shuffle vectors that look like:
7283 ///
7284 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7285 ///
7286 /// Essentially it concatenates V1 and V2, shifts right by some number of
7287 /// elements, and takes the low elements as the result. Note that while this is
7288 /// specified as a *right shift* because x86 is little-endian, it is a *left
7289 /// rotate* of the vector lanes.
7290 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7291                                               SDValue V2,
7292                                               ArrayRef<int> Mask,
7293                                               const X86Subtarget *Subtarget,
7294                                               SelectionDAG &DAG) {
7295   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7296
7297   int NumElts = Mask.size();
7298   int NumLanes = VT.getSizeInBits() / 128;
7299   int NumLaneElts = NumElts / NumLanes;
7300
7301   // We need to detect various ways of spelling a rotation:
7302   //   [11, 12, 13, 14, 15,  0,  1,  2]
7303   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7304   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7305   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7306   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7307   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7308   int Rotation = 0;
7309   SDValue Lo, Hi;
7310   for (int l = 0; l < NumElts; l += NumLaneElts) {
7311     for (int i = 0; i < NumLaneElts; ++i) {
7312       if (Mask[l + i] == -1)
7313         continue;
7314       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7315
7316       // Get the mod-Size index and lane correct it.
7317       int LaneIdx = (Mask[l + i] % NumElts) - l;
7318       // Make sure it was in this lane.
7319       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7320         return SDValue();
7321
7322       // Determine where a rotated vector would have started.
7323       int StartIdx = i - LaneIdx;
7324       if (StartIdx == 0)
7325         // The identity rotation isn't interesting, stop.
7326         return SDValue();
7327
7328       // If we found the tail of a vector the rotation must be the missing
7329       // front. If we found the head of a vector, it must be how much of the
7330       // head.
7331       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7332
7333       if (Rotation == 0)
7334         Rotation = CandidateRotation;
7335       else if (Rotation != CandidateRotation)
7336         // The rotations don't match, so we can't match this mask.
7337         return SDValue();
7338
7339       // Compute which value this mask is pointing at.
7340       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7341
7342       // Compute which of the two target values this index should be assigned
7343       // to. This reflects whether the high elements are remaining or the low
7344       // elements are remaining.
7345       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7346
7347       // Either set up this value if we've not encountered it before, or check
7348       // that it remains consistent.
7349       if (!TargetV)
7350         TargetV = MaskV;
7351       else if (TargetV != MaskV)
7352         // This may be a rotation, but it pulls from the inputs in some
7353         // unsupported interleaving.
7354         return SDValue();
7355     }
7356   }
7357
7358   // Check that we successfully analyzed the mask, and normalize the results.
7359   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7360   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7361   if (!Lo)
7362     Lo = Hi;
7363   else if (!Hi)
7364     Hi = Lo;
7365
7366   // The actual rotate instruction rotates bytes, so we need to scale the
7367   // rotation based on how many bytes are in the vector lane.
7368   int Scale = 16 / NumLaneElts;
7369
7370   // SSSE3 targets can use the palignr instruction.
7371   if (Subtarget->hasSSSE3()) {
7372     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7373     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7374     Lo = DAG.getBitcast(AlignVT, Lo);
7375     Hi = DAG.getBitcast(AlignVT, Hi);
7376
7377     return DAG.getBitcast(
7378         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7379                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7380   }
7381
7382   assert(VT.is128BitVector() &&
7383          "Rotate-based lowering only supports 128-bit lowering!");
7384   assert(Mask.size() <= 16 &&
7385          "Can shuffle at most 16 bytes in a 128-bit vector!");
7386
7387   // Default SSE2 implementation
7388   int LoByteShift = 16 - Rotation * Scale;
7389   int HiByteShift = Rotation * Scale;
7390
7391   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7392   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7393   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7394
7395   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7396                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7397   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7398                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7399   return DAG.getBitcast(VT,
7400                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7401 }
7402
7403 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7404 ///
7405 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7406 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7407 /// matches elements from one of the input vectors shuffled to the left or
7408 /// right with zeroable elements 'shifted in'. It handles both the strictly
7409 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7410 /// quad word lane.
7411 ///
7412 /// PSHL : (little-endian) left bit shift.
7413 /// [ zz, 0, zz,  2 ]
7414 /// [ -1, 4, zz, -1 ]
7415 /// PSRL : (little-endian) right bit shift.
7416 /// [  1, zz,  3, zz]
7417 /// [ -1, -1,  7, zz]
7418 /// PSLLDQ : (little-endian) left byte shift
7419 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7420 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7421 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7422 /// PSRLDQ : (little-endian) right byte shift
7423 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7424 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7425 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7426 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7427                                          SDValue V2, ArrayRef<int> Mask,
7428                                          SelectionDAG &DAG) {
7429   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7430
7431   int Size = Mask.size();
7432   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7433
7434   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7435     for (int i = 0; i < Size; i += Scale)
7436       for (int j = 0; j < Shift; ++j)
7437         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7438           return false;
7439
7440     return true;
7441   };
7442
7443   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7444     for (int i = 0; i != Size; i += Scale) {
7445       unsigned Pos = Left ? i + Shift : i;
7446       unsigned Low = Left ? i : i + Shift;
7447       unsigned Len = Scale - Shift;
7448       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7449                                       Low + (V == V1 ? 0 : Size)))
7450         return SDValue();
7451     }
7452
7453     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7454     bool ByteShift = ShiftEltBits > 64;
7455     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7456                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7457     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7458
7459     // Normalize the scale for byte shifts to still produce an i64 element
7460     // type.
7461     Scale = ByteShift ? Scale / 2 : Scale;
7462
7463     // We need to round trip through the appropriate type for the shift.
7464     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7465     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7466     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7467            "Illegal integer vector type");
7468     V = DAG.getBitcast(ShiftVT, V);
7469
7470     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7471                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7472     return DAG.getBitcast(VT, V);
7473   };
7474
7475   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7476   // keep doubling the size of the integer elements up to that. We can
7477   // then shift the elements of the integer vector by whole multiples of
7478   // their width within the elements of the larger integer vector. Test each
7479   // multiple to see if we can find a match with the moved element indices
7480   // and that the shifted in elements are all zeroable.
7481   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7482     for (int Shift = 1; Shift != Scale; ++Shift)
7483       for (bool Left : {true, false})
7484         if (CheckZeros(Shift, Scale, Left))
7485           for (SDValue V : {V1, V2})
7486             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7487               return Match;
7488
7489   // no match
7490   return SDValue();
7491 }
7492
7493 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7494 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7495                                            SDValue V2, ArrayRef<int> Mask,
7496                                            SelectionDAG &DAG) {
7497   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7498   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7499
7500   int Size = Mask.size();
7501   int HalfSize = Size / 2;
7502   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7503
7504   // Upper half must be undefined.
7505   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7506     return SDValue();
7507
7508   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7509   // Remainder of lower half result is zero and upper half is all undef.
7510   auto LowerAsEXTRQ = [&]() {
7511     // Determine the extraction length from the part of the
7512     // lower half that isn't zeroable.
7513     int Len = HalfSize;
7514     for (; Len > 0; --Len)
7515       if (!Zeroable[Len - 1])
7516         break;
7517     assert(Len > 0 && "Zeroable shuffle mask");
7518
7519     // Attempt to match first Len sequential elements from the lower half.
7520     SDValue Src;
7521     int Idx = -1;
7522     for (int i = 0; i != Len; ++i) {
7523       int M = Mask[i];
7524       if (M < 0)
7525         continue;
7526       SDValue &V = (M < Size ? V1 : V2);
7527       M = M % Size;
7528
7529       // The extracted elements must start at a valid index and all mask
7530       // elements must be in the lower half.
7531       if (i > M || M >= HalfSize)
7532         return SDValue();
7533
7534       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7535         Src = V;
7536         Idx = M - i;
7537         continue;
7538       }
7539       return SDValue();
7540     }
7541
7542     if (Idx < 0)
7543       return SDValue();
7544
7545     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7546     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7547     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7548     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7549                        DAG.getConstant(BitLen, DL, MVT::i8),
7550                        DAG.getConstant(BitIdx, DL, MVT::i8));
7551   };
7552
7553   if (SDValue ExtrQ = LowerAsEXTRQ())
7554     return ExtrQ;
7555
7556   // INSERTQ: Extract lowest Len elements from lower half of second source and
7557   // insert over first source, starting at Idx.
7558   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7559   auto LowerAsInsertQ = [&]() {
7560     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7561       SDValue Base;
7562
7563       // Attempt to match first source from mask before insertion point.
7564       if (isUndefInRange(Mask, 0, Idx)) {
7565         /* EMPTY */
7566       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7567         Base = V1;
7568       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7569         Base = V2;
7570       } else {
7571         continue;
7572       }
7573
7574       // Extend the extraction length looking to match both the insertion of
7575       // the second source and the remaining elements of the first.
7576       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7577         SDValue Insert;
7578         int Len = Hi - Idx;
7579
7580         // Match insertion.
7581         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7582           Insert = V1;
7583         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7584           Insert = V2;
7585         } else {
7586           continue;
7587         }
7588
7589         // Match the remaining elements of the lower half.
7590         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7591           /* EMPTY */
7592         } else if ((!Base || (Base == V1)) &&
7593                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7594           Base = V1;
7595         } else if ((!Base || (Base == V2)) &&
7596                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7597                                               Size + Hi)) {
7598           Base = V2;
7599         } else {
7600           continue;
7601         }
7602
7603         // We may not have a base (first source) - this can safely be undefined.
7604         if (!Base)
7605           Base = DAG.getUNDEF(VT);
7606
7607         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7608         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7609         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7610                            DAG.getConstant(BitLen, DL, MVT::i8),
7611                            DAG.getConstant(BitIdx, DL, MVT::i8));
7612       }
7613     }
7614
7615     return SDValue();
7616   };
7617
7618   if (SDValue InsertQ = LowerAsInsertQ())
7619     return InsertQ;
7620
7621   return SDValue();
7622 }
7623
7624 /// \brief Lower a vector shuffle as a zero or any extension.
7625 ///
7626 /// Given a specific number of elements, element bit width, and extension
7627 /// stride, produce either a zero or any extension based on the available
7628 /// features of the subtarget. The extended elements are consecutive and
7629 /// begin and can start from an offseted element index in the input; to
7630 /// avoid excess shuffling the offset must either being in the bottom lane
7631 /// or at the start of a higher lane. All extended elements must be from
7632 /// the same lane.
7633 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7634     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7635     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7636   assert(Scale > 1 && "Need a scale to extend.");
7637   int EltBits = VT.getScalarSizeInBits();
7638   int NumElements = VT.getVectorNumElements();
7639   int NumEltsPerLane = 128 / EltBits;
7640   int OffsetLane = Offset / NumEltsPerLane;
7641   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7642          "Only 8, 16, and 32 bit elements can be extended.");
7643   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7644   assert(0 <= Offset && "Extension offset must be positive.");
7645   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7646          "Extension offset must be in the first lane or start an upper lane.");
7647
7648   // Check that an index is in same lane as the base offset.
7649   auto SafeOffset = [&](int Idx) {
7650     return OffsetLane == (Idx / NumEltsPerLane);
7651   };
7652
7653   // Shift along an input so that the offset base moves to the first element.
7654   auto ShuffleOffset = [&](SDValue V) {
7655     if (!Offset)
7656       return V;
7657
7658     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7659     for (int i = 0; i * Scale < NumElements; ++i) {
7660       int SrcIdx = i + Offset;
7661       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7662     }
7663     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7664   };
7665
7666   // Found a valid zext mask! Try various lowering strategies based on the
7667   // input type and available ISA extensions.
7668   if (Subtarget->hasSSE41()) {
7669     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7670     // PUNPCK will catch this in a later shuffle match.
7671     if (Offset && Scale == 2 && VT.is128BitVector())
7672       return SDValue();
7673     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7674                                  NumElements / Scale);
7675     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7676     return DAG.getBitcast(VT, InputV);
7677   }
7678
7679   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7680
7681   // For any extends we can cheat for larger element sizes and use shuffle
7682   // instructions that can fold with a load and/or copy.
7683   if (AnyExt && EltBits == 32) {
7684     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7685                          -1};
7686     return DAG.getBitcast(
7687         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7688                         DAG.getBitcast(MVT::v4i32, InputV),
7689                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7690   }
7691   if (AnyExt && EltBits == 16 && Scale > 2) {
7692     int PSHUFDMask[4] = {Offset / 2, -1,
7693                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7694     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7695                          DAG.getBitcast(MVT::v4i32, InputV),
7696                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7697     int PSHUFWMask[4] = {1, -1, -1, -1};
7698     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7699     return DAG.getBitcast(
7700         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7701                         DAG.getBitcast(MVT::v8i16, InputV),
7702                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7703   }
7704
7705   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7706   // to 64-bits.
7707   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7708     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7709     assert(VT.is128BitVector() && "Unexpected vector width!");
7710
7711     int LoIdx = Offset * EltBits;
7712     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7713                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7714                                          DAG.getConstant(EltBits, DL, MVT::i8),
7715                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7716
7717     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7718         !SafeOffset(Offset + 1))
7719       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7720
7721     int HiIdx = (Offset + 1) * EltBits;
7722     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7723                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7724                                          DAG.getConstant(EltBits, DL, MVT::i8),
7725                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7726     return DAG.getNode(ISD::BITCAST, DL, VT,
7727                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7728   }
7729
7730   // If this would require more than 2 unpack instructions to expand, use
7731   // pshufb when available. We can only use more than 2 unpack instructions
7732   // when zero extending i8 elements which also makes it easier to use pshufb.
7733   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7734     assert(NumElements == 16 && "Unexpected byte vector width!");
7735     SDValue PSHUFBMask[16];
7736     for (int i = 0; i < 16; ++i) {
7737       int Idx = Offset + (i / Scale);
7738       PSHUFBMask[i] = DAG.getConstant(
7739           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7740     }
7741     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7742     return DAG.getBitcast(VT,
7743                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7744                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7745                                                   MVT::v16i8, PSHUFBMask)));
7746   }
7747
7748   // If we are extending from an offset, ensure we start on a boundary that
7749   // we can unpack from.
7750   int AlignToUnpack = Offset % (NumElements / Scale);
7751   if (AlignToUnpack) {
7752     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7753     for (int i = AlignToUnpack; i < NumElements; ++i)
7754       ShMask[i - AlignToUnpack] = i;
7755     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7756     Offset -= AlignToUnpack;
7757   }
7758
7759   // Otherwise emit a sequence of unpacks.
7760   do {
7761     unsigned UnpackLoHi = X86ISD::UNPCKL;
7762     if (Offset >= (NumElements / 2)) {
7763       UnpackLoHi = X86ISD::UNPCKH;
7764       Offset -= (NumElements / 2);
7765     }
7766
7767     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7768     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7769                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7770     InputV = DAG.getBitcast(InputVT, InputV);
7771     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7772     Scale /= 2;
7773     EltBits *= 2;
7774     NumElements /= 2;
7775   } while (Scale > 1);
7776   return DAG.getBitcast(VT, InputV);
7777 }
7778
7779 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7780 ///
7781 /// This routine will try to do everything in its power to cleverly lower
7782 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7783 /// check for the profitability of this lowering,  it tries to aggressively
7784 /// match this pattern. It will use all of the micro-architectural details it
7785 /// can to emit an efficient lowering. It handles both blends with all-zero
7786 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7787 /// masking out later).
7788 ///
7789 /// The reason we have dedicated lowering for zext-style shuffles is that they
7790 /// are both incredibly common and often quite performance sensitive.
7791 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7792     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7793     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7794   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7795
7796   int Bits = VT.getSizeInBits();
7797   int NumLanes = Bits / 128;
7798   int NumElements = VT.getVectorNumElements();
7799   int NumEltsPerLane = NumElements / NumLanes;
7800   assert(VT.getScalarSizeInBits() <= 32 &&
7801          "Exceeds 32-bit integer zero extension limit");
7802   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7803
7804   // Define a helper function to check a particular ext-scale and lower to it if
7805   // valid.
7806   auto Lower = [&](int Scale) -> SDValue {
7807     SDValue InputV;
7808     bool AnyExt = true;
7809     int Offset = 0;
7810     int Matches = 0;
7811     for (int i = 0; i < NumElements; ++i) {
7812       int M = Mask[i];
7813       if (M == -1)
7814         continue; // Valid anywhere but doesn't tell us anything.
7815       if (i % Scale != 0) {
7816         // Each of the extended elements need to be zeroable.
7817         if (!Zeroable[i])
7818           return SDValue();
7819
7820         // We no longer are in the anyext case.
7821         AnyExt = false;
7822         continue;
7823       }
7824
7825       // Each of the base elements needs to be consecutive indices into the
7826       // same input vector.
7827       SDValue V = M < NumElements ? V1 : V2;
7828       M = M % NumElements;
7829       if (!InputV) {
7830         InputV = V;
7831         Offset = M - (i / Scale);
7832       } else if (InputV != V)
7833         return SDValue(); // Flip-flopping inputs.
7834
7835       // Offset must start in the lowest 128-bit lane or at the start of an
7836       // upper lane.
7837       // FIXME: Is it ever worth allowing a negative base offset?
7838       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7839             (Offset % NumEltsPerLane) == 0))
7840         return SDValue();
7841
7842       // If we are offsetting, all referenced entries must come from the same
7843       // lane.
7844       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7845         return SDValue();
7846
7847       if ((M % NumElements) != (Offset + (i / Scale)))
7848         return SDValue(); // Non-consecutive strided elements.
7849       Matches++;
7850     }
7851
7852     // If we fail to find an input, we have a zero-shuffle which should always
7853     // have already been handled.
7854     // FIXME: Maybe handle this here in case during blending we end up with one?
7855     if (!InputV)
7856       return SDValue();
7857
7858     // If we are offsetting, don't extend if we only match a single input, we
7859     // can always do better by using a basic PSHUF or PUNPCK.
7860     if (Offset != 0 && Matches < 2)
7861       return SDValue();
7862
7863     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7864         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7865   };
7866
7867   // The widest scale possible for extending is to a 64-bit integer.
7868   assert(Bits % 64 == 0 &&
7869          "The number of bits in a vector must be divisible by 64 on x86!");
7870   int NumExtElements = Bits / 64;
7871
7872   // Each iteration, try extending the elements half as much, but into twice as
7873   // many elements.
7874   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7875     assert(NumElements % NumExtElements == 0 &&
7876            "The input vector size must be divisible by the extended size.");
7877     if (SDValue V = Lower(NumElements / NumExtElements))
7878       return V;
7879   }
7880
7881   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7882   if (Bits != 128)
7883     return SDValue();
7884
7885   // Returns one of the source operands if the shuffle can be reduced to a
7886   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7887   auto CanZExtLowHalf = [&]() {
7888     for (int i = NumElements / 2; i != NumElements; ++i)
7889       if (!Zeroable[i])
7890         return SDValue();
7891     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7892       return V1;
7893     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7894       return V2;
7895     return SDValue();
7896   };
7897
7898   if (SDValue V = CanZExtLowHalf()) {
7899     V = DAG.getBitcast(MVT::v2i64, V);
7900     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7901     return DAG.getBitcast(VT, V);
7902   }
7903
7904   // No viable ext lowering found.
7905   return SDValue();
7906 }
7907
7908 /// \brief Try to get a scalar value for a specific element of a vector.
7909 ///
7910 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7911 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7912                                               SelectionDAG &DAG) {
7913   MVT VT = V.getSimpleValueType();
7914   MVT EltVT = VT.getVectorElementType();
7915   while (V.getOpcode() == ISD::BITCAST)
7916     V = V.getOperand(0);
7917   // If the bitcasts shift the element size, we can't extract an equivalent
7918   // element from it.
7919   MVT NewVT = V.getSimpleValueType();
7920   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7921     return SDValue();
7922
7923   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7924       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7925     // Ensure the scalar operand is the same size as the destination.
7926     // FIXME: Add support for scalar truncation where possible.
7927     SDValue S = V.getOperand(Idx);
7928     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7929       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7930   }
7931
7932   return SDValue();
7933 }
7934
7935 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7936 ///
7937 /// This is particularly important because the set of instructions varies
7938 /// significantly based on whether the operand is a load or not.
7939 static bool isShuffleFoldableLoad(SDValue V) {
7940   while (V.getOpcode() == ISD::BITCAST)
7941     V = V.getOperand(0);
7942
7943   return ISD::isNON_EXTLoad(V.getNode());
7944 }
7945
7946 /// \brief Try to lower insertion of a single element into a zero vector.
7947 ///
7948 /// This is a common pattern that we have especially efficient patterns to lower
7949 /// across all subtarget feature sets.
7950 static SDValue lowerVectorShuffleAsElementInsertion(
7951     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7952     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7953   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7954   MVT ExtVT = VT;
7955   MVT EltVT = VT.getVectorElementType();
7956
7957   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7958                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7959                 Mask.begin();
7960   bool IsV1Zeroable = true;
7961   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7962     if (i != V2Index && !Zeroable[i]) {
7963       IsV1Zeroable = false;
7964       break;
7965     }
7966
7967   // Check for a single input from a SCALAR_TO_VECTOR node.
7968   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7969   // all the smarts here sunk into that routine. However, the current
7970   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7971   // vector shuffle lowering is dead.
7972   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7973                                                DAG);
7974   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7975     // We need to zext the scalar if it is smaller than an i32.
7976     V2S = DAG.getBitcast(EltVT, V2S);
7977     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7978       // Using zext to expand a narrow element won't work for non-zero
7979       // insertions.
7980       if (!IsV1Zeroable)
7981         return SDValue();
7982
7983       // Zero-extend directly to i32.
7984       ExtVT = MVT::v4i32;
7985       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7986     }
7987     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7988   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7989              EltVT == MVT::i16) {
7990     // Either not inserting from the low element of the input or the input
7991     // element size is too small to use VZEXT_MOVL to clear the high bits.
7992     return SDValue();
7993   }
7994
7995   if (!IsV1Zeroable) {
7996     // If V1 can't be treated as a zero vector we have fewer options to lower
7997     // this. We can't support integer vectors or non-zero targets cheaply, and
7998     // the V1 elements can't be permuted in any way.
7999     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8000     if (!VT.isFloatingPoint() || V2Index != 0)
8001       return SDValue();
8002     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8003     V1Mask[V2Index] = -1;
8004     if (!isNoopShuffleMask(V1Mask))
8005       return SDValue();
8006     // This is essentially a special case blend operation, but if we have
8007     // general purpose blend operations, they are always faster. Bail and let
8008     // the rest of the lowering handle these as blends.
8009     if (Subtarget->hasSSE41())
8010       return SDValue();
8011
8012     // Otherwise, use MOVSD or MOVSS.
8013     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8014            "Only two types of floating point element types to handle!");
8015     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8016                        ExtVT, V1, V2);
8017   }
8018
8019   // This lowering only works for the low element with floating point vectors.
8020   if (VT.isFloatingPoint() && V2Index != 0)
8021     return SDValue();
8022
8023   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8024   if (ExtVT != VT)
8025     V2 = DAG.getBitcast(VT, V2);
8026
8027   if (V2Index != 0) {
8028     // If we have 4 or fewer lanes we can cheaply shuffle the element into
8029     // the desired position. Otherwise it is more efficient to do a vector
8030     // shift left. We know that we can do a vector shift left because all
8031     // the inputs are zero.
8032     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8033       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8034       V2Shuffle[V2Index] = 0;
8035       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8036     } else {
8037       V2 = DAG.getBitcast(MVT::v2i64, V2);
8038       V2 = DAG.getNode(
8039           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8040           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8041                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8042                               DAG.getDataLayout(), VT)));
8043       V2 = DAG.getBitcast(VT, V2);
8044     }
8045   }
8046   return V2;
8047 }
8048
8049 /// \brief Try to lower broadcast of a single - truncated - integer element,
8050 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8051 ///
8052 /// This assumes we have AVX2.
8053 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
8054                                                   int BroadcastIdx,
8055                                                   const X86Subtarget *Subtarget,
8056                                                   SelectionDAG &DAG) {
8057   assert(Subtarget->hasAVX2() &&
8058          "We can only lower integer broadcasts with AVX2!");
8059
8060   EVT EltVT = VT.getVectorElementType();
8061   EVT V0VT = V0.getValueType();
8062
8063   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8064   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8065
8066   EVT V0EltVT = V0VT.getVectorElementType();
8067   if (!V0EltVT.isInteger())
8068     return SDValue();
8069
8070   const unsigned EltSize = EltVT.getSizeInBits();
8071   const unsigned V0EltSize = V0EltVT.getSizeInBits();
8072
8073   // This is only a truncation if the original element type is larger.
8074   if (V0EltSize <= EltSize)
8075     return SDValue();
8076
8077   assert(((V0EltSize % EltSize) == 0) &&
8078          "Scalar type sizes must all be powers of 2 on x86!");
8079
8080   const unsigned V0Opc = V0.getOpcode();
8081   const unsigned Scale = V0EltSize / EltSize;
8082   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8083
8084   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8085       V0Opc != ISD::BUILD_VECTOR)
8086     return SDValue();
8087
8088   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8089
8090   // If we're extracting non-least-significant bits, shift so we can truncate.
8091   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8092   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8093   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8094   if (const int OffsetIdx = BroadcastIdx % Scale)
8095     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8096             DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8097
8098   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8099                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8100 }
8101
8102 /// \brief Try to lower broadcast of a single element.
8103 ///
8104 /// For convenience, this code also bundles all of the subtarget feature set
8105 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8106 /// a convenient way to factor it out.
8107 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8108 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8109                                              ArrayRef<int> Mask,
8110                                              const X86Subtarget *Subtarget,
8111                                              SelectionDAG &DAG) {
8112   if (!Subtarget->hasAVX())
8113     return SDValue();
8114   if (VT.isInteger() && !Subtarget->hasAVX2())
8115     return SDValue();
8116
8117   // Check that the mask is a broadcast.
8118   int BroadcastIdx = -1;
8119   for (int M : Mask)
8120     if (M >= 0 && BroadcastIdx == -1)
8121       BroadcastIdx = M;
8122     else if (M >= 0 && M != BroadcastIdx)
8123       return SDValue();
8124
8125   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8126                                             "a sorted mask where the broadcast "
8127                                             "comes from V1.");
8128
8129   // Go up the chain of (vector) values to find a scalar load that we can
8130   // combine with the broadcast.
8131   for (;;) {
8132     switch (V.getOpcode()) {
8133     case ISD::CONCAT_VECTORS: {
8134       int OperandSize = Mask.size() / V.getNumOperands();
8135       V = V.getOperand(BroadcastIdx / OperandSize);
8136       BroadcastIdx %= OperandSize;
8137       continue;
8138     }
8139
8140     case ISD::INSERT_SUBVECTOR: {
8141       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8142       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8143       if (!ConstantIdx)
8144         break;
8145
8146       int BeginIdx = (int)ConstantIdx->getZExtValue();
8147       int EndIdx =
8148           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8149       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8150         BroadcastIdx -= BeginIdx;
8151         V = VInner;
8152       } else {
8153         V = VOuter;
8154       }
8155       continue;
8156     }
8157     }
8158     break;
8159   }
8160
8161   // Check if this is a broadcast of a scalar. We special case lowering
8162   // for scalars so that we can more effectively fold with loads.
8163   // First, look through bitcast: if the original value has a larger element
8164   // type than the shuffle, the broadcast element is in essence truncated.
8165   // Make that explicit to ease folding.
8166   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8167     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8168             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8169       return TruncBroadcast;
8170
8171   // Also check the simpler case, where we can directly reuse the scalar.
8172   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8173       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8174     V = V.getOperand(BroadcastIdx);
8175
8176     // If the scalar isn't a load, we can't broadcast from it in AVX1.
8177     // Only AVX2 has register broadcasts.
8178     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8179       return SDValue();
8180   } else if (MayFoldLoad(V) && !cast<LoadSDNode>(V)->isVolatile()) {
8181     // If we are broadcasting a load that is only used by the shuffle
8182     // then we can reduce the vector load to the broadcasted scalar load.
8183     LoadSDNode *Ld = cast<LoadSDNode>(V);
8184     SDValue BaseAddr = Ld->getOperand(1);
8185     EVT AddrVT = BaseAddr.getValueType();
8186     EVT SVT = VT.getScalarType();
8187     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8188     SDValue NewAddr = DAG.getNode(
8189         ISD::ADD, DL, AddrVT, BaseAddr,
8190         DAG.getConstant(Offset, DL, AddrVT));
8191     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8192                     DAG.getMachineFunction().getMachineMemOperand(
8193                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8194   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8195     // We can't broadcast from a vector register without AVX2, and we can only
8196     // broadcast from the zero-element of a vector register.
8197     return SDValue();
8198   }
8199
8200   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8201 }
8202
8203 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8204 // INSERTPS when the V1 elements are already in the correct locations
8205 // because otherwise we can just always use two SHUFPS instructions which
8206 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8207 // perform INSERTPS if a single V1 element is out of place and all V2
8208 // elements are zeroable.
8209 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8210                                             ArrayRef<int> Mask,
8211                                             SelectionDAG &DAG) {
8212   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8213   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8214   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8215   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8216
8217   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8218
8219   unsigned ZMask = 0;
8220   int V1DstIndex = -1;
8221   int V2DstIndex = -1;
8222   bool V1UsedInPlace = false;
8223
8224   for (int i = 0; i < 4; ++i) {
8225     // Synthesize a zero mask from the zeroable elements (includes undefs).
8226     if (Zeroable[i]) {
8227       ZMask |= 1 << i;
8228       continue;
8229     }
8230
8231     // Flag if we use any V1 inputs in place.
8232     if (i == Mask[i]) {
8233       V1UsedInPlace = true;
8234       continue;
8235     }
8236
8237     // We can only insert a single non-zeroable element.
8238     if (V1DstIndex != -1 || V2DstIndex != -1)
8239       return SDValue();
8240
8241     if (Mask[i] < 4) {
8242       // V1 input out of place for insertion.
8243       V1DstIndex = i;
8244     } else {
8245       // V2 input for insertion.
8246       V2DstIndex = i;
8247     }
8248   }
8249
8250   // Don't bother if we have no (non-zeroable) element for insertion.
8251   if (V1DstIndex == -1 && V2DstIndex == -1)
8252     return SDValue();
8253
8254   // Determine element insertion src/dst indices. The src index is from the
8255   // start of the inserted vector, not the start of the concatenated vector.
8256   unsigned V2SrcIndex = 0;
8257   if (V1DstIndex != -1) {
8258     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8259     // and don't use the original V2 at all.
8260     V2SrcIndex = Mask[V1DstIndex];
8261     V2DstIndex = V1DstIndex;
8262     V2 = V1;
8263   } else {
8264     V2SrcIndex = Mask[V2DstIndex] - 4;
8265   }
8266
8267   // If no V1 inputs are used in place, then the result is created only from
8268   // the zero mask and the V2 insertion - so remove V1 dependency.
8269   if (!V1UsedInPlace)
8270     V1 = DAG.getUNDEF(MVT::v4f32);
8271
8272   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8273   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8274
8275   // Insert the V2 element into the desired position.
8276   SDLoc DL(Op);
8277   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8278                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8279 }
8280
8281 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8282 /// UNPCK instruction.
8283 ///
8284 /// This specifically targets cases where we end up with alternating between
8285 /// the two inputs, and so can permute them into something that feeds a single
8286 /// UNPCK instruction. Note that this routine only targets integer vectors
8287 /// because for floating point vectors we have a generalized SHUFPS lowering
8288 /// strategy that handles everything that doesn't *exactly* match an unpack,
8289 /// making this clever lowering unnecessary.
8290 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8291                                                     SDValue V1, SDValue V2,
8292                                                     ArrayRef<int> Mask,
8293                                                     SelectionDAG &DAG) {
8294   assert(!VT.isFloatingPoint() &&
8295          "This routine only supports integer vectors.");
8296   assert(!isSingleInputShuffleMask(Mask) &&
8297          "This routine should only be used when blending two inputs.");
8298   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8299
8300   int Size = Mask.size();
8301
8302   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8303     return M >= 0 && M % Size < Size / 2;
8304   });
8305   int NumHiInputs = std::count_if(
8306       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8307
8308   bool UnpackLo = NumLoInputs >= NumHiInputs;
8309
8310   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8311     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8312     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8313
8314     for (int i = 0; i < Size; ++i) {
8315       if (Mask[i] < 0)
8316         continue;
8317
8318       // Each element of the unpack contains Scale elements from this mask.
8319       int UnpackIdx = i / Scale;
8320
8321       // We only handle the case where V1 feeds the first slots of the unpack.
8322       // We rely on canonicalization to ensure this is the case.
8323       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8324         return SDValue();
8325
8326       // Setup the mask for this input. The indexing is tricky as we have to
8327       // handle the unpack stride.
8328       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8329       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8330           Mask[i] % Size;
8331     }
8332
8333     // If we will have to shuffle both inputs to use the unpack, check whether
8334     // we can just unpack first and shuffle the result. If so, skip this unpack.
8335     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8336         !isNoopShuffleMask(V2Mask))
8337       return SDValue();
8338
8339     // Shuffle the inputs into place.
8340     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8341     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8342
8343     // Cast the inputs to the type we will use to unpack them.
8344     V1 = DAG.getBitcast(UnpackVT, V1);
8345     V2 = DAG.getBitcast(UnpackVT, V2);
8346
8347     // Unpack the inputs and cast the result back to the desired type.
8348     return DAG.getBitcast(
8349         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8350                         UnpackVT, V1, V2));
8351   };
8352
8353   // We try each unpack from the largest to the smallest to try and find one
8354   // that fits this mask.
8355   int OrigNumElements = VT.getVectorNumElements();
8356   int OrigScalarSize = VT.getScalarSizeInBits();
8357   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8358     int Scale = ScalarSize / OrigScalarSize;
8359     int NumElements = OrigNumElements / Scale;
8360     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8361     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8362       return Unpack;
8363   }
8364
8365   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8366   // initial unpack.
8367   if (NumLoInputs == 0 || NumHiInputs == 0) {
8368     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8369            "We have to have *some* inputs!");
8370     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8371
8372     // FIXME: We could consider the total complexity of the permute of each
8373     // possible unpacking. Or at the least we should consider how many
8374     // half-crossings are created.
8375     // FIXME: We could consider commuting the unpacks.
8376
8377     SmallVector<int, 32> PermMask;
8378     PermMask.assign(Size, -1);
8379     for (int i = 0; i < Size; ++i) {
8380       if (Mask[i] < 0)
8381         continue;
8382
8383       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8384
8385       PermMask[i] =
8386           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8387     }
8388     return DAG.getVectorShuffle(
8389         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8390                             DL, VT, V1, V2),
8391         DAG.getUNDEF(VT), PermMask);
8392   }
8393
8394   return SDValue();
8395 }
8396
8397 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8398 ///
8399 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8400 /// support for floating point shuffles but not integer shuffles. These
8401 /// instructions will incur a domain crossing penalty on some chips though so
8402 /// it is better to avoid lowering through this for integer vectors where
8403 /// possible.
8404 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8405                                        const X86Subtarget *Subtarget,
8406                                        SelectionDAG &DAG) {
8407   SDLoc DL(Op);
8408   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8409   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8410   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8411   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8412   ArrayRef<int> Mask = SVOp->getMask();
8413   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8414
8415   if (isSingleInputShuffleMask(Mask)) {
8416     // Use low duplicate instructions for masks that match their pattern.
8417     if (Subtarget->hasSSE3())
8418       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8419         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8420
8421     // Straight shuffle of a single input vector. Simulate this by using the
8422     // single input as both of the "inputs" to this instruction..
8423     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8424
8425     if (Subtarget->hasAVX()) {
8426       // If we have AVX, we can use VPERMILPS which will allow folding a load
8427       // into the shuffle.
8428       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8429                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8430     }
8431
8432     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8433                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8434   }
8435   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8436   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8437
8438   // If we have a single input, insert that into V1 if we can do so cheaply.
8439   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8440     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8441             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8442       return Insertion;
8443     // Try inverting the insertion since for v2 masks it is easy to do and we
8444     // can't reliably sort the mask one way or the other.
8445     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8446                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8447     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8448             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8449       return Insertion;
8450   }
8451
8452   // Try to use one of the special instruction patterns to handle two common
8453   // blend patterns if a zero-blend above didn't work.
8454   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8455       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8456     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8457       // We can either use a special instruction to load over the low double or
8458       // to move just the low double.
8459       return DAG.getNode(
8460           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8461           DL, MVT::v2f64, V2,
8462           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8463
8464   if (Subtarget->hasSSE41())
8465     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8466                                                   Subtarget, DAG))
8467       return Blend;
8468
8469   // Use dedicated unpack instructions for masks that match their pattern.
8470   if (SDValue V =
8471           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8472     return V;
8473
8474   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8475   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8476                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8477 }
8478
8479 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8480 ///
8481 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8482 /// the integer unit to minimize domain crossing penalties. However, for blends
8483 /// it falls back to the floating point shuffle operation with appropriate bit
8484 /// casting.
8485 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8486                                        const X86Subtarget *Subtarget,
8487                                        SelectionDAG &DAG) {
8488   SDLoc DL(Op);
8489   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8490   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8491   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8492   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8493   ArrayRef<int> Mask = SVOp->getMask();
8494   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8495
8496   if (isSingleInputShuffleMask(Mask)) {
8497     // Check for being able to broadcast a single element.
8498     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8499                                                           Mask, Subtarget, DAG))
8500       return Broadcast;
8501
8502     // Straight shuffle of a single input vector. For everything from SSE2
8503     // onward this has a single fast instruction with no scary immediates.
8504     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8505     V1 = DAG.getBitcast(MVT::v4i32, V1);
8506     int WidenedMask[4] = {
8507         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8508         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8509     return DAG.getBitcast(
8510         MVT::v2i64,
8511         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8512                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8513   }
8514   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8515   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8516   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8517   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8518
8519   // If we have a blend of two PACKUS operations an the blend aligns with the
8520   // low and half halves, we can just merge the PACKUS operations. This is
8521   // particularly important as it lets us merge shuffles that this routine itself
8522   // creates.
8523   auto GetPackNode = [](SDValue V) {
8524     while (V.getOpcode() == ISD::BITCAST)
8525       V = V.getOperand(0);
8526
8527     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8528   };
8529   if (SDValue V1Pack = GetPackNode(V1))
8530     if (SDValue V2Pack = GetPackNode(V2))
8531       return DAG.getBitcast(MVT::v2i64,
8532                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8533                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8534                                                      : V1Pack.getOperand(1),
8535                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8536                                                      : V2Pack.getOperand(1)));
8537
8538   // Try to use shift instructions.
8539   if (SDValue Shift =
8540           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8541     return Shift;
8542
8543   // When loading a scalar and then shuffling it into a vector we can often do
8544   // the insertion cheaply.
8545   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8546           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8547     return Insertion;
8548   // Try inverting the insertion since for v2 masks it is easy to do and we
8549   // can't reliably sort the mask one way or the other.
8550   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8551   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8552           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8553     return Insertion;
8554
8555   // We have different paths for blend lowering, but they all must use the
8556   // *exact* same predicate.
8557   bool IsBlendSupported = Subtarget->hasSSE41();
8558   if (IsBlendSupported)
8559     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8560                                                   Subtarget, DAG))
8561       return Blend;
8562
8563   // Use dedicated unpack instructions for masks that match their pattern.
8564   if (SDValue V =
8565           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8566     return V;
8567
8568   // Try to use byte rotation instructions.
8569   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8570   if (Subtarget->hasSSSE3())
8571     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8572             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8573       return Rotate;
8574
8575   // If we have direct support for blends, we should lower by decomposing into
8576   // a permute. That will be faster than the domain cross.
8577   if (IsBlendSupported)
8578     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8579                                                       Mask, DAG);
8580
8581   // We implement this with SHUFPD which is pretty lame because it will likely
8582   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8583   // However, all the alternatives are still more cycles and newer chips don't
8584   // have this problem. It would be really nice if x86 had better shuffles here.
8585   V1 = DAG.getBitcast(MVT::v2f64, V1);
8586   V2 = DAG.getBitcast(MVT::v2f64, V2);
8587   return DAG.getBitcast(MVT::v2i64,
8588                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8589 }
8590
8591 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8592 ///
8593 /// This is used to disable more specialized lowerings when the shufps lowering
8594 /// will happen to be efficient.
8595 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8596   // This routine only handles 128-bit shufps.
8597   assert(Mask.size() == 4 && "Unsupported mask size!");
8598
8599   // To lower with a single SHUFPS we need to have the low half and high half
8600   // each requiring a single input.
8601   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8602     return false;
8603   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8604     return false;
8605
8606   return true;
8607 }
8608
8609 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8610 ///
8611 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8612 /// It makes no assumptions about whether this is the *best* lowering, it simply
8613 /// uses it.
8614 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8615                                             ArrayRef<int> Mask, SDValue V1,
8616                                             SDValue V2, SelectionDAG &DAG) {
8617   SDValue LowV = V1, HighV = V2;
8618   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8619
8620   int NumV2Elements =
8621       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8622
8623   if (NumV2Elements == 1) {
8624     int V2Index =
8625         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8626         Mask.begin();
8627
8628     // Compute the index adjacent to V2Index and in the same half by toggling
8629     // the low bit.
8630     int V2AdjIndex = V2Index ^ 1;
8631
8632     if (Mask[V2AdjIndex] == -1) {
8633       // Handles all the cases where we have a single V2 element and an undef.
8634       // This will only ever happen in the high lanes because we commute the
8635       // vector otherwise.
8636       if (V2Index < 2)
8637         std::swap(LowV, HighV);
8638       NewMask[V2Index] -= 4;
8639     } else {
8640       // Handle the case where the V2 element ends up adjacent to a V1 element.
8641       // To make this work, blend them together as the first step.
8642       int V1Index = V2AdjIndex;
8643       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8644       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8645                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8646
8647       // Now proceed to reconstruct the final blend as we have the necessary
8648       // high or low half formed.
8649       if (V2Index < 2) {
8650         LowV = V2;
8651         HighV = V1;
8652       } else {
8653         HighV = V2;
8654       }
8655       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8656       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8657     }
8658   } else if (NumV2Elements == 2) {
8659     if (Mask[0] < 4 && Mask[1] < 4) {
8660       // Handle the easy case where we have V1 in the low lanes and V2 in the
8661       // high lanes.
8662       NewMask[2] -= 4;
8663       NewMask[3] -= 4;
8664     } else if (Mask[2] < 4 && Mask[3] < 4) {
8665       // We also handle the reversed case because this utility may get called
8666       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8667       // arrange things in the right direction.
8668       NewMask[0] -= 4;
8669       NewMask[1] -= 4;
8670       HighV = V1;
8671       LowV = V2;
8672     } else {
8673       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8674       // trying to place elements directly, just blend them and set up the final
8675       // shuffle to place them.
8676
8677       // The first two blend mask elements are for V1, the second two are for
8678       // V2.
8679       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8680                           Mask[2] < 4 ? Mask[2] : Mask[3],
8681                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8682                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8683       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8684                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8685
8686       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8687       // a blend.
8688       LowV = HighV = V1;
8689       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8690       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8691       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8692       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8693     }
8694   }
8695   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8696                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8697 }
8698
8699 /// \brief Lower 4-lane 32-bit floating point shuffles.
8700 ///
8701 /// Uses instructions exclusively from the floating point unit to minimize
8702 /// domain crossing penalties, as these are sufficient to implement all v4f32
8703 /// shuffles.
8704 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8705                                        const X86Subtarget *Subtarget,
8706                                        SelectionDAG &DAG) {
8707   SDLoc DL(Op);
8708   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8709   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8710   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8711   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8712   ArrayRef<int> Mask = SVOp->getMask();
8713   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8714
8715   int NumV2Elements =
8716       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8717
8718   if (NumV2Elements == 0) {
8719     // Check for being able to broadcast a single element.
8720     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8721                                                           Mask, Subtarget, DAG))
8722       return Broadcast;
8723
8724     // Use even/odd duplicate instructions for masks that match their pattern.
8725     if (Subtarget->hasSSE3()) {
8726       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8727         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8728       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8729         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8730     }
8731
8732     if (Subtarget->hasAVX()) {
8733       // If we have AVX, we can use VPERMILPS which will allow folding a load
8734       // into the shuffle.
8735       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8736                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8737     }
8738
8739     // Otherwise, use a straight shuffle of a single input vector. We pass the
8740     // input vector to both operands to simulate this with a SHUFPS.
8741     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8742                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8743   }
8744
8745   // There are special ways we can lower some single-element blends. However, we
8746   // have custom ways we can lower more complex single-element blends below that
8747   // we defer to if both this and BLENDPS fail to match, so restrict this to
8748   // when the V2 input is targeting element 0 of the mask -- that is the fast
8749   // case here.
8750   if (NumV2Elements == 1 && Mask[0] >= 4)
8751     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8752                                                          Mask, Subtarget, DAG))
8753       return V;
8754
8755   if (Subtarget->hasSSE41()) {
8756     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8757                                                   Subtarget, DAG))
8758       return Blend;
8759
8760     // Use INSERTPS if we can complete the shuffle efficiently.
8761     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8762       return V;
8763
8764     if (!isSingleSHUFPSMask(Mask))
8765       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8766               DL, MVT::v4f32, V1, V2, Mask, DAG))
8767         return BlendPerm;
8768   }
8769
8770   // Use dedicated unpack instructions for masks that match their pattern.
8771   if (SDValue V =
8772           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8773     return V;
8774
8775   // Otherwise fall back to a SHUFPS lowering strategy.
8776   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8777 }
8778
8779 /// \brief Lower 4-lane i32 vector shuffles.
8780 ///
8781 /// We try to handle these with integer-domain shuffles where we can, but for
8782 /// blends we use the floating point domain blend instructions.
8783 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8784                                        const X86Subtarget *Subtarget,
8785                                        SelectionDAG &DAG) {
8786   SDLoc DL(Op);
8787   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8788   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8789   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8790   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8791   ArrayRef<int> Mask = SVOp->getMask();
8792   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8793
8794   // Whenever we can lower this as a zext, that instruction is strictly faster
8795   // than any alternative. It also allows us to fold memory operands into the
8796   // shuffle in many cases.
8797   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8798                                                          Mask, Subtarget, DAG))
8799     return ZExt;
8800
8801   int NumV2Elements =
8802       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8803
8804   if (NumV2Elements == 0) {
8805     // Check for being able to broadcast a single element.
8806     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8807                                                           Mask, Subtarget, DAG))
8808       return Broadcast;
8809
8810     // Straight shuffle of a single input vector. For everything from SSE2
8811     // onward this has a single fast instruction with no scary immediates.
8812     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8813     // but we aren't actually going to use the UNPCK instruction because doing
8814     // so prevents folding a load into this instruction or making a copy.
8815     const int UnpackLoMask[] = {0, 0, 1, 1};
8816     const int UnpackHiMask[] = {2, 2, 3, 3};
8817     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8818       Mask = UnpackLoMask;
8819     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8820       Mask = UnpackHiMask;
8821
8822     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8823                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8824   }
8825
8826   // Try to use shift instructions.
8827   if (SDValue Shift =
8828           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8829     return Shift;
8830
8831   // There are special ways we can lower some single-element blends.
8832   if (NumV2Elements == 1)
8833     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8834                                                          Mask, Subtarget, DAG))
8835       return V;
8836
8837   // We have different paths for blend lowering, but they all must use the
8838   // *exact* same predicate.
8839   bool IsBlendSupported = Subtarget->hasSSE41();
8840   if (IsBlendSupported)
8841     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8842                                                   Subtarget, DAG))
8843       return Blend;
8844
8845   if (SDValue Masked =
8846           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8847     return Masked;
8848
8849   // Use dedicated unpack instructions for masks that match their pattern.
8850   if (SDValue V =
8851           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8852     return V;
8853
8854   // Try to use byte rotation instructions.
8855   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8856   if (Subtarget->hasSSSE3())
8857     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8858             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8859       return Rotate;
8860
8861   // If we have direct support for blends, we should lower by decomposing into
8862   // a permute. That will be faster than the domain cross.
8863   if (IsBlendSupported)
8864     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8865                                                       Mask, DAG);
8866
8867   // Try to lower by permuting the inputs into an unpack instruction.
8868   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8869                                                             V2, Mask, DAG))
8870     return Unpack;
8871
8872   // We implement this with SHUFPS because it can blend from two vectors.
8873   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8874   // up the inputs, bypassing domain shift penalties that we would encur if we
8875   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8876   // relevant.
8877   return DAG.getBitcast(
8878       MVT::v4i32,
8879       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8880                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8881 }
8882
8883 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8884 /// shuffle lowering, and the most complex part.
8885 ///
8886 /// The lowering strategy is to try to form pairs of input lanes which are
8887 /// targeted at the same half of the final vector, and then use a dword shuffle
8888 /// to place them onto the right half, and finally unpack the paired lanes into
8889 /// their final position.
8890 ///
8891 /// The exact breakdown of how to form these dword pairs and align them on the
8892 /// correct sides is really tricky. See the comments within the function for
8893 /// more of the details.
8894 ///
8895 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8896 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8897 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8898 /// vector, form the analogous 128-bit 8-element Mask.
8899 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8900     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8901     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8902   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8903   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8904
8905   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8906   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8907   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8908
8909   SmallVector<int, 4> LoInputs;
8910   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8911                [](int M) { return M >= 0; });
8912   std::sort(LoInputs.begin(), LoInputs.end());
8913   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8914   SmallVector<int, 4> HiInputs;
8915   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8916                [](int M) { return M >= 0; });
8917   std::sort(HiInputs.begin(), HiInputs.end());
8918   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8919   int NumLToL =
8920       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8921   int NumHToL = LoInputs.size() - NumLToL;
8922   int NumLToH =
8923       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8924   int NumHToH = HiInputs.size() - NumLToH;
8925   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8926   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8927   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8928   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8929
8930   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8931   // such inputs we can swap two of the dwords across the half mark and end up
8932   // with <=2 inputs to each half in each half. Once there, we can fall through
8933   // to the generic code below. For example:
8934   //
8935   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8936   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8937   //
8938   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8939   // and an existing 2-into-2 on the other half. In this case we may have to
8940   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8941   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8942   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8943   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8944   // half than the one we target for fixing) will be fixed when we re-enter this
8945   // path. We will also combine away any sequence of PSHUFD instructions that
8946   // result into a single instruction. Here is an example of the tricky case:
8947   //
8948   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8949   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8950   //
8951   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8952   //
8953   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8954   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8955   //
8956   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8957   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8958   //
8959   // The result is fine to be handled by the generic logic.
8960   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8961                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8962                           int AOffset, int BOffset) {
8963     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8964            "Must call this with A having 3 or 1 inputs from the A half.");
8965     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8966            "Must call this with B having 1 or 3 inputs from the B half.");
8967     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8968            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8969
8970     bool ThreeAInputs = AToAInputs.size() == 3;
8971
8972     // Compute the index of dword with only one word among the three inputs in
8973     // a half by taking the sum of the half with three inputs and subtracting
8974     // the sum of the actual three inputs. The difference is the remaining
8975     // slot.
8976     int ADWord, BDWord;
8977     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8978     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8979     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8980     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8981     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8982     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8983     int TripleNonInputIdx =
8984         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8985     TripleDWord = TripleNonInputIdx / 2;
8986
8987     // We use xor with one to compute the adjacent DWord to whichever one the
8988     // OneInput is in.
8989     OneInputDWord = (OneInput / 2) ^ 1;
8990
8991     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8992     // and BToA inputs. If there is also such a problem with the BToB and AToB
8993     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8994     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8995     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8996     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8997       // Compute how many inputs will be flipped by swapping these DWords. We
8998       // need
8999       // to balance this to ensure we don't form a 3-1 shuffle in the other
9000       // half.
9001       int NumFlippedAToBInputs =
9002           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9003           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9004       int NumFlippedBToBInputs =
9005           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9006           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9007       if ((NumFlippedAToBInputs == 1 &&
9008            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9009           (NumFlippedBToBInputs == 1 &&
9010            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9011         // We choose whether to fix the A half or B half based on whether that
9012         // half has zero flipped inputs. At zero, we may not be able to fix it
9013         // with that half. We also bias towards fixing the B half because that
9014         // will more commonly be the high half, and we have to bias one way.
9015         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9016                                                        ArrayRef<int> Inputs) {
9017           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9018           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9019                                          PinnedIdx ^ 1) != Inputs.end();
9020           // Determine whether the free index is in the flipped dword or the
9021           // unflipped dword based on where the pinned index is. We use this bit
9022           // in an xor to conditionally select the adjacent dword.
9023           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9024           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9025                                              FixFreeIdx) != Inputs.end();
9026           if (IsFixIdxInput == IsFixFreeIdxInput)
9027             FixFreeIdx += 1;
9028           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9029                                         FixFreeIdx) != Inputs.end();
9030           assert(IsFixIdxInput != IsFixFreeIdxInput &&
9031                  "We need to be changing the number of flipped inputs!");
9032           int PSHUFHalfMask[] = {0, 1, 2, 3};
9033           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9034           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9035                           MVT::v8i16, V,
9036                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9037
9038           for (int &M : Mask)
9039             if (M != -1 && M == FixIdx)
9040               M = FixFreeIdx;
9041             else if (M != -1 && M == FixFreeIdx)
9042               M = FixIdx;
9043         };
9044         if (NumFlippedBToBInputs != 0) {
9045           int BPinnedIdx =
9046               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9047           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9048         } else {
9049           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9050           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9051           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9052         }
9053       }
9054     }
9055
9056     int PSHUFDMask[] = {0, 1, 2, 3};
9057     PSHUFDMask[ADWord] = BDWord;
9058     PSHUFDMask[BDWord] = ADWord;
9059     V = DAG.getBitcast(
9060         VT,
9061         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9062                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9063
9064     // Adjust the mask to match the new locations of A and B.
9065     for (int &M : Mask)
9066       if (M != -1 && M/2 == ADWord)
9067         M = 2 * BDWord + M % 2;
9068       else if (M != -1 && M/2 == BDWord)
9069         M = 2 * ADWord + M % 2;
9070
9071     // Recurse back into this routine to re-compute state now that this isn't
9072     // a 3 and 1 problem.
9073     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9074                                                      DAG);
9075   };
9076   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9077     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9078   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9079     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9080
9081   // At this point there are at most two inputs to the low and high halves from
9082   // each half. That means the inputs can always be grouped into dwords and
9083   // those dwords can then be moved to the correct half with a dword shuffle.
9084   // We use at most one low and one high word shuffle to collect these paired
9085   // inputs into dwords, and finally a dword shuffle to place them.
9086   int PSHUFLMask[4] = {-1, -1, -1, -1};
9087   int PSHUFHMask[4] = {-1, -1, -1, -1};
9088   int PSHUFDMask[4] = {-1, -1, -1, -1};
9089
9090   // First fix the masks for all the inputs that are staying in their
9091   // original halves. This will then dictate the targets of the cross-half
9092   // shuffles.
9093   auto fixInPlaceInputs =
9094       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9095                     MutableArrayRef<int> SourceHalfMask,
9096                     MutableArrayRef<int> HalfMask, int HalfOffset) {
9097     if (InPlaceInputs.empty())
9098       return;
9099     if (InPlaceInputs.size() == 1) {
9100       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9101           InPlaceInputs[0] - HalfOffset;
9102       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9103       return;
9104     }
9105     if (IncomingInputs.empty()) {
9106       // Just fix all of the in place inputs.
9107       for (int Input : InPlaceInputs) {
9108         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9109         PSHUFDMask[Input / 2] = Input / 2;
9110       }
9111       return;
9112     }
9113
9114     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9115     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9116         InPlaceInputs[0] - HalfOffset;
9117     // Put the second input next to the first so that they are packed into
9118     // a dword. We find the adjacent index by toggling the low bit.
9119     int AdjIndex = InPlaceInputs[0] ^ 1;
9120     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9121     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9122     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9123   };
9124   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9125   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9126
9127   // Now gather the cross-half inputs and place them into a free dword of
9128   // their target half.
9129   // FIXME: This operation could almost certainly be simplified dramatically to
9130   // look more like the 3-1 fixing operation.
9131   auto moveInputsToRightHalf = [&PSHUFDMask](
9132       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9133       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9134       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9135       int DestOffset) {
9136     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9137       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9138     };
9139     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9140                                                int Word) {
9141       int LowWord = Word & ~1;
9142       int HighWord = Word | 1;
9143       return isWordClobbered(SourceHalfMask, LowWord) ||
9144              isWordClobbered(SourceHalfMask, HighWord);
9145     };
9146
9147     if (IncomingInputs.empty())
9148       return;
9149
9150     if (ExistingInputs.empty()) {
9151       // Map any dwords with inputs from them into the right half.
9152       for (int Input : IncomingInputs) {
9153         // If the source half mask maps over the inputs, turn those into
9154         // swaps and use the swapped lane.
9155         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9156           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9157             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9158                 Input - SourceOffset;
9159             // We have to swap the uses in our half mask in one sweep.
9160             for (int &M : HalfMask)
9161               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9162                 M = Input;
9163               else if (M == Input)
9164                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9165           } else {
9166             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9167                        Input - SourceOffset &&
9168                    "Previous placement doesn't match!");
9169           }
9170           // Note that this correctly re-maps both when we do a swap and when
9171           // we observe the other side of the swap above. We rely on that to
9172           // avoid swapping the members of the input list directly.
9173           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9174         }
9175
9176         // Map the input's dword into the correct half.
9177         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9178           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9179         else
9180           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9181                      Input / 2 &&
9182                  "Previous placement doesn't match!");
9183       }
9184
9185       // And just directly shift any other-half mask elements to be same-half
9186       // as we will have mirrored the dword containing the element into the
9187       // same position within that half.
9188       for (int &M : HalfMask)
9189         if (M >= SourceOffset && M < SourceOffset + 4) {
9190           M = M - SourceOffset + DestOffset;
9191           assert(M >= 0 && "This should never wrap below zero!");
9192         }
9193       return;
9194     }
9195
9196     // Ensure we have the input in a viable dword of its current half. This
9197     // is particularly tricky because the original position may be clobbered
9198     // by inputs being moved and *staying* in that half.
9199     if (IncomingInputs.size() == 1) {
9200       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9201         int InputFixed = std::find(std::begin(SourceHalfMask),
9202                                    std::end(SourceHalfMask), -1) -
9203                          std::begin(SourceHalfMask) + SourceOffset;
9204         SourceHalfMask[InputFixed - SourceOffset] =
9205             IncomingInputs[0] - SourceOffset;
9206         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9207                      InputFixed);
9208         IncomingInputs[0] = InputFixed;
9209       }
9210     } else if (IncomingInputs.size() == 2) {
9211       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9212           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9213         // We have two non-adjacent or clobbered inputs we need to extract from
9214         // the source half. To do this, we need to map them into some adjacent
9215         // dword slot in the source mask.
9216         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9217                               IncomingInputs[1] - SourceOffset};
9218
9219         // If there is a free slot in the source half mask adjacent to one of
9220         // the inputs, place the other input in it. We use (Index XOR 1) to
9221         // compute an adjacent index.
9222         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9223             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9224           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9225           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9226           InputsFixed[1] = InputsFixed[0] ^ 1;
9227         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9228                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9229           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9230           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9231           InputsFixed[0] = InputsFixed[1] ^ 1;
9232         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9233                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9234           // The two inputs are in the same DWord but it is clobbered and the
9235           // adjacent DWord isn't used at all. Move both inputs to the free
9236           // slot.
9237           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9238           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9239           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9240           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9241         } else {
9242           // The only way we hit this point is if there is no clobbering
9243           // (because there are no off-half inputs to this half) and there is no
9244           // free slot adjacent to one of the inputs. In this case, we have to
9245           // swap an input with a non-input.
9246           for (int i = 0; i < 4; ++i)
9247             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9248                    "We can't handle any clobbers here!");
9249           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9250                  "Cannot have adjacent inputs here!");
9251
9252           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9253           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9254
9255           // We also have to update the final source mask in this case because
9256           // it may need to undo the above swap.
9257           for (int &M : FinalSourceHalfMask)
9258             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9259               M = InputsFixed[1] + SourceOffset;
9260             else if (M == InputsFixed[1] + SourceOffset)
9261               M = (InputsFixed[0] ^ 1) + SourceOffset;
9262
9263           InputsFixed[1] = InputsFixed[0] ^ 1;
9264         }
9265
9266         // Point everything at the fixed inputs.
9267         for (int &M : HalfMask)
9268           if (M == IncomingInputs[0])
9269             M = InputsFixed[0] + SourceOffset;
9270           else if (M == IncomingInputs[1])
9271             M = InputsFixed[1] + SourceOffset;
9272
9273         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9274         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9275       }
9276     } else {
9277       llvm_unreachable("Unhandled input size!");
9278     }
9279
9280     // Now hoist the DWord down to the right half.
9281     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9282     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9283     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9284     for (int &M : HalfMask)
9285       for (int Input : IncomingInputs)
9286         if (M == Input)
9287           M = FreeDWord * 2 + Input % 2;
9288   };
9289   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9290                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9291   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9292                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9293
9294   // Now enact all the shuffles we've computed to move the inputs into their
9295   // target half.
9296   if (!isNoopShuffleMask(PSHUFLMask))
9297     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9298                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9299   if (!isNoopShuffleMask(PSHUFHMask))
9300     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9301                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9302   if (!isNoopShuffleMask(PSHUFDMask))
9303     V = DAG.getBitcast(
9304         VT,
9305         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9306                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9307
9308   // At this point, each half should contain all its inputs, and we can then
9309   // just shuffle them into their final position.
9310   assert(std::count_if(LoMask.begin(), LoMask.end(),
9311                        [](int M) { return M >= 4; }) == 0 &&
9312          "Failed to lift all the high half inputs to the low mask!");
9313   assert(std::count_if(HiMask.begin(), HiMask.end(),
9314                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9315          "Failed to lift all the low half inputs to the high mask!");
9316
9317   // Do a half shuffle for the low mask.
9318   if (!isNoopShuffleMask(LoMask))
9319     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9320                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9321
9322   // Do a half shuffle with the high mask after shifting its values down.
9323   for (int &M : HiMask)
9324     if (M >= 0)
9325       M -= 4;
9326   if (!isNoopShuffleMask(HiMask))
9327     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9328                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9329
9330   return V;
9331 }
9332
9333 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9334 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9335                                           SDValue V2, ArrayRef<int> Mask,
9336                                           SelectionDAG &DAG, bool &V1InUse,
9337                                           bool &V2InUse) {
9338   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9339   SDValue V1Mask[16];
9340   SDValue V2Mask[16];
9341   V1InUse = false;
9342   V2InUse = false;
9343
9344   int Size = Mask.size();
9345   int Scale = 16 / Size;
9346   for (int i = 0; i < 16; ++i) {
9347     if (Mask[i / Scale] == -1) {
9348       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9349     } else {
9350       const int ZeroMask = 0x80;
9351       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9352                                           : ZeroMask;
9353       int V2Idx = Mask[i / Scale] < Size
9354                       ? ZeroMask
9355                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9356       if (Zeroable[i / Scale])
9357         V1Idx = V2Idx = ZeroMask;
9358       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9359       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9360       V1InUse |= (ZeroMask != V1Idx);
9361       V2InUse |= (ZeroMask != V2Idx);
9362     }
9363   }
9364
9365   if (V1InUse)
9366     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9367                      DAG.getBitcast(MVT::v16i8, V1),
9368                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9369   if (V2InUse)
9370     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9371                      DAG.getBitcast(MVT::v16i8, V2),
9372                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9373
9374   // If we need shuffled inputs from both, blend the two.
9375   SDValue V;
9376   if (V1InUse && V2InUse)
9377     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9378   else
9379     V = V1InUse ? V1 : V2;
9380
9381   // Cast the result back to the correct type.
9382   return DAG.getBitcast(VT, V);
9383 }
9384
9385 /// \brief Generic lowering of 8-lane i16 shuffles.
9386 ///
9387 /// This handles both single-input shuffles and combined shuffle/blends with
9388 /// two inputs. The single input shuffles are immediately delegated to
9389 /// a dedicated lowering routine.
9390 ///
9391 /// The blends are lowered in one of three fundamental ways. If there are few
9392 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9393 /// of the input is significantly cheaper when lowered as an interleaving of
9394 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9395 /// halves of the inputs separately (making them have relatively few inputs)
9396 /// and then concatenate them.
9397 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9398                                        const X86Subtarget *Subtarget,
9399                                        SelectionDAG &DAG) {
9400   SDLoc DL(Op);
9401   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9402   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9403   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9404   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9405   ArrayRef<int> OrigMask = SVOp->getMask();
9406   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9407                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9408   MutableArrayRef<int> Mask(MaskStorage);
9409
9410   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9411
9412   // Whenever we can lower this as a zext, that instruction is strictly faster
9413   // than any alternative.
9414   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9415           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9416     return ZExt;
9417
9418   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9419   (void)isV1;
9420   auto isV2 = [](int M) { return M >= 8; };
9421
9422   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9423
9424   if (NumV2Inputs == 0) {
9425     // Check for being able to broadcast a single element.
9426     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9427                                                           Mask, Subtarget, DAG))
9428       return Broadcast;
9429
9430     // Try to use shift instructions.
9431     if (SDValue Shift =
9432             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9433       return Shift;
9434
9435     // Use dedicated unpack instructions for masks that match their pattern.
9436     if (SDValue V =
9437             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9438       return V;
9439
9440     // Try to use byte rotation instructions.
9441     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9442                                                         Mask, Subtarget, DAG))
9443       return Rotate;
9444
9445     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9446                                                      Subtarget, DAG);
9447   }
9448
9449   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9450          "All single-input shuffles should be canonicalized to be V1-input "
9451          "shuffles.");
9452
9453   // Try to use shift instructions.
9454   if (SDValue Shift =
9455           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9456     return Shift;
9457
9458   // See if we can use SSE4A Extraction / Insertion.
9459   if (Subtarget->hasSSE4A())
9460     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9461       return V;
9462
9463   // There are special ways we can lower some single-element blends.
9464   if (NumV2Inputs == 1)
9465     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9466                                                          Mask, Subtarget, DAG))
9467       return V;
9468
9469   // We have different paths for blend lowering, but they all must use the
9470   // *exact* same predicate.
9471   bool IsBlendSupported = Subtarget->hasSSE41();
9472   if (IsBlendSupported)
9473     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9474                                                   Subtarget, DAG))
9475       return Blend;
9476
9477   if (SDValue Masked =
9478           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9479     return Masked;
9480
9481   // Use dedicated unpack instructions for masks that match their pattern.
9482   if (SDValue V =
9483           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9484     return V;
9485
9486   // Try to use byte rotation instructions.
9487   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9488           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9489     return Rotate;
9490
9491   if (SDValue BitBlend =
9492           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9493     return BitBlend;
9494
9495   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9496                                                             V2, Mask, DAG))
9497     return Unpack;
9498
9499   // If we can't directly blend but can use PSHUFB, that will be better as it
9500   // can both shuffle and set up the inefficient blend.
9501   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9502     bool V1InUse, V2InUse;
9503     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9504                                       V1InUse, V2InUse);
9505   }
9506
9507   // We can always bit-blend if we have to so the fallback strategy is to
9508   // decompose into single-input permutes and blends.
9509   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9510                                                       Mask, DAG);
9511 }
9512
9513 /// \brief Check whether a compaction lowering can be done by dropping even
9514 /// elements and compute how many times even elements must be dropped.
9515 ///
9516 /// This handles shuffles which take every Nth element where N is a power of
9517 /// two. Example shuffle masks:
9518 ///
9519 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9520 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9521 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9522 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9523 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9524 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9525 ///
9526 /// Any of these lanes can of course be undef.
9527 ///
9528 /// This routine only supports N <= 3.
9529 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9530 /// for larger N.
9531 ///
9532 /// \returns N above, or the number of times even elements must be dropped if
9533 /// there is such a number. Otherwise returns zero.
9534 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9535   // Figure out whether we're looping over two inputs or just one.
9536   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9537
9538   // The modulus for the shuffle vector entries is based on whether this is
9539   // a single input or not.
9540   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9541   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9542          "We should only be called with masks with a power-of-2 size!");
9543
9544   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9545
9546   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9547   // and 2^3 simultaneously. This is because we may have ambiguity with
9548   // partially undef inputs.
9549   bool ViableForN[3] = {true, true, true};
9550
9551   for (int i = 0, e = Mask.size(); i < e; ++i) {
9552     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9553     // want.
9554     if (Mask[i] == -1)
9555       continue;
9556
9557     bool IsAnyViable = false;
9558     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9559       if (ViableForN[j]) {
9560         uint64_t N = j + 1;
9561
9562         // The shuffle mask must be equal to (i * 2^N) % M.
9563         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9564           IsAnyViable = true;
9565         else
9566           ViableForN[j] = false;
9567       }
9568     // Early exit if we exhaust the possible powers of two.
9569     if (!IsAnyViable)
9570       break;
9571   }
9572
9573   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9574     if (ViableForN[j])
9575       return j + 1;
9576
9577   // Return 0 as there is no viable power of two.
9578   return 0;
9579 }
9580
9581 /// \brief Generic lowering of v16i8 shuffles.
9582 ///
9583 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9584 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9585 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9586 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9587 /// back together.
9588 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9589                                        const X86Subtarget *Subtarget,
9590                                        SelectionDAG &DAG) {
9591   SDLoc DL(Op);
9592   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9593   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9594   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9595   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9596   ArrayRef<int> Mask = SVOp->getMask();
9597   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9598
9599   // Try to use shift instructions.
9600   if (SDValue Shift =
9601           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9602     return Shift;
9603
9604   // Try to use byte rotation instructions.
9605   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9606           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9607     return Rotate;
9608
9609   // Try to use a zext lowering.
9610   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9611           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9612     return ZExt;
9613
9614   // See if we can use SSE4A Extraction / Insertion.
9615   if (Subtarget->hasSSE4A())
9616     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9617       return V;
9618
9619   int NumV2Elements =
9620       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9621
9622   // For single-input shuffles, there are some nicer lowering tricks we can use.
9623   if (NumV2Elements == 0) {
9624     // Check for being able to broadcast a single element.
9625     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9626                                                           Mask, Subtarget, DAG))
9627       return Broadcast;
9628
9629     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9630     // Notably, this handles splat and partial-splat shuffles more efficiently.
9631     // However, it only makes sense if the pre-duplication shuffle simplifies
9632     // things significantly. Currently, this means we need to be able to
9633     // express the pre-duplication shuffle as an i16 shuffle.
9634     //
9635     // FIXME: We should check for other patterns which can be widened into an
9636     // i16 shuffle as well.
9637     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9638       for (int i = 0; i < 16; i += 2)
9639         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9640           return false;
9641
9642       return true;
9643     };
9644     auto tryToWidenViaDuplication = [&]() -> SDValue {
9645       if (!canWidenViaDuplication(Mask))
9646         return SDValue();
9647       SmallVector<int, 4> LoInputs;
9648       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9649                    [](int M) { return M >= 0 && M < 8; });
9650       std::sort(LoInputs.begin(), LoInputs.end());
9651       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9652                      LoInputs.end());
9653       SmallVector<int, 4> HiInputs;
9654       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9655                    [](int M) { return M >= 8; });
9656       std::sort(HiInputs.begin(), HiInputs.end());
9657       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9658                      HiInputs.end());
9659
9660       bool TargetLo = LoInputs.size() >= HiInputs.size();
9661       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9662       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9663
9664       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9665       SmallDenseMap<int, int, 8> LaneMap;
9666       for (int I : InPlaceInputs) {
9667         PreDupI16Shuffle[I/2] = I/2;
9668         LaneMap[I] = I;
9669       }
9670       int j = TargetLo ? 0 : 4, je = j + 4;
9671       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9672         // Check if j is already a shuffle of this input. This happens when
9673         // there are two adjacent bytes after we move the low one.
9674         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9675           // If we haven't yet mapped the input, search for a slot into which
9676           // we can map it.
9677           while (j < je && PreDupI16Shuffle[j] != -1)
9678             ++j;
9679
9680           if (j == je)
9681             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9682             return SDValue();
9683
9684           // Map this input with the i16 shuffle.
9685           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9686         }
9687
9688         // Update the lane map based on the mapping we ended up with.
9689         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9690       }
9691       V1 = DAG.getBitcast(
9692           MVT::v16i8,
9693           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9694                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9695
9696       // Unpack the bytes to form the i16s that will be shuffled into place.
9697       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9698                        MVT::v16i8, V1, V1);
9699
9700       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9701       for (int i = 0; i < 16; ++i)
9702         if (Mask[i] != -1) {
9703           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9704           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9705           if (PostDupI16Shuffle[i / 2] == -1)
9706             PostDupI16Shuffle[i / 2] = MappedMask;
9707           else
9708             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9709                    "Conflicting entrties in the original shuffle!");
9710         }
9711       return DAG.getBitcast(
9712           MVT::v16i8,
9713           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9714                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9715     };
9716     if (SDValue V = tryToWidenViaDuplication())
9717       return V;
9718   }
9719
9720   if (SDValue Masked =
9721           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9722     return Masked;
9723
9724   // Use dedicated unpack instructions for masks that match their pattern.
9725   if (SDValue V =
9726           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9727     return V;
9728
9729   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9730   // with PSHUFB. It is important to do this before we attempt to generate any
9731   // blends but after all of the single-input lowerings. If the single input
9732   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9733   // want to preserve that and we can DAG combine any longer sequences into
9734   // a PSHUFB in the end. But once we start blending from multiple inputs,
9735   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9736   // and there are *very* few patterns that would actually be faster than the
9737   // PSHUFB approach because of its ability to zero lanes.
9738   //
9739   // FIXME: The only exceptions to the above are blends which are exact
9740   // interleavings with direct instructions supporting them. We currently don't
9741   // handle those well here.
9742   if (Subtarget->hasSSSE3()) {
9743     bool V1InUse = false;
9744     bool V2InUse = false;
9745
9746     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9747                                                 DAG, V1InUse, V2InUse);
9748
9749     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9750     // do so. This avoids using them to handle blends-with-zero which is
9751     // important as a single pshufb is significantly faster for that.
9752     if (V1InUse && V2InUse) {
9753       if (Subtarget->hasSSE41())
9754         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9755                                                       Mask, Subtarget, DAG))
9756           return Blend;
9757
9758       // We can use an unpack to do the blending rather than an or in some
9759       // cases. Even though the or may be (very minorly) more efficient, we
9760       // preference this lowering because there are common cases where part of
9761       // the complexity of the shuffles goes away when we do the final blend as
9762       // an unpack.
9763       // FIXME: It might be worth trying to detect if the unpack-feeding
9764       // shuffles will both be pshufb, in which case we shouldn't bother with
9765       // this.
9766       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9767               DL, MVT::v16i8, V1, V2, Mask, DAG))
9768         return Unpack;
9769     }
9770
9771     return PSHUFB;
9772   }
9773
9774   // There are special ways we can lower some single-element blends.
9775   if (NumV2Elements == 1)
9776     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9777                                                          Mask, Subtarget, DAG))
9778       return V;
9779
9780   if (SDValue BitBlend =
9781           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9782     return BitBlend;
9783
9784   // Check whether a compaction lowering can be done. This handles shuffles
9785   // which take every Nth element for some even N. See the helper function for
9786   // details.
9787   //
9788   // We special case these as they can be particularly efficiently handled with
9789   // the PACKUSB instruction on x86 and they show up in common patterns of
9790   // rearranging bytes to truncate wide elements.
9791   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9792     // NumEvenDrops is the power of two stride of the elements. Another way of
9793     // thinking about it is that we need to drop the even elements this many
9794     // times to get the original input.
9795     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9796
9797     // First we need to zero all the dropped bytes.
9798     assert(NumEvenDrops <= 3 &&
9799            "No support for dropping even elements more than 3 times.");
9800     // We use the mask type to pick which bytes are preserved based on how many
9801     // elements are dropped.
9802     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9803     SDValue ByteClearMask = DAG.getBitcast(
9804         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9805     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9806     if (!IsSingleInput)
9807       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9808
9809     // Now pack things back together.
9810     V1 = DAG.getBitcast(MVT::v8i16, V1);
9811     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9812     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9813     for (int i = 1; i < NumEvenDrops; ++i) {
9814       Result = DAG.getBitcast(MVT::v8i16, Result);
9815       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9816     }
9817
9818     return Result;
9819   }
9820
9821   // Handle multi-input cases by blending single-input shuffles.
9822   if (NumV2Elements > 0)
9823     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9824                                                       Mask, DAG);
9825
9826   // The fallback path for single-input shuffles widens this into two v8i16
9827   // vectors with unpacks, shuffles those, and then pulls them back together
9828   // with a pack.
9829   SDValue V = V1;
9830
9831   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9832   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9833   for (int i = 0; i < 16; ++i)
9834     if (Mask[i] >= 0)
9835       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9836
9837   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9838
9839   SDValue VLoHalf, VHiHalf;
9840   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9841   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9842   // i16s.
9843   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9844                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9845       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9846                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9847     // Use a mask to drop the high bytes.
9848     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9849     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9850                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9851
9852     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9853     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9854
9855     // Squash the masks to point directly into VLoHalf.
9856     for (int &M : LoBlendMask)
9857       if (M >= 0)
9858         M /= 2;
9859     for (int &M : HiBlendMask)
9860       if (M >= 0)
9861         M /= 2;
9862   } else {
9863     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9864     // VHiHalf so that we can blend them as i16s.
9865     VLoHalf = DAG.getBitcast(
9866         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9867     VHiHalf = DAG.getBitcast(
9868         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9869   }
9870
9871   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9872   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9873
9874   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9875 }
9876
9877 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9878 ///
9879 /// This routine breaks down the specific type of 128-bit shuffle and
9880 /// dispatches to the lowering routines accordingly.
9881 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9882                                         MVT VT, const X86Subtarget *Subtarget,
9883                                         SelectionDAG &DAG) {
9884   switch (VT.SimpleTy) {
9885   case MVT::v2i64:
9886     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9887   case MVT::v2f64:
9888     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9889   case MVT::v4i32:
9890     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9891   case MVT::v4f32:
9892     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9893   case MVT::v8i16:
9894     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9895   case MVT::v16i8:
9896     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9897
9898   default:
9899     llvm_unreachable("Unimplemented!");
9900   }
9901 }
9902
9903 /// \brief Helper function to test whether a shuffle mask could be
9904 /// simplified by widening the elements being shuffled.
9905 ///
9906 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9907 /// leaves it in an unspecified state.
9908 ///
9909 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9910 /// shuffle masks. The latter have the special property of a '-2' representing
9911 /// a zero-ed lane of a vector.
9912 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9913                                     SmallVectorImpl<int> &WidenedMask) {
9914   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9915     // If both elements are undef, its trivial.
9916     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9917       WidenedMask.push_back(SM_SentinelUndef);
9918       continue;
9919     }
9920
9921     // Check for an undef mask and a mask value properly aligned to fit with
9922     // a pair of values. If we find such a case, use the non-undef mask's value.
9923     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9924       WidenedMask.push_back(Mask[i + 1] / 2);
9925       continue;
9926     }
9927     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9928       WidenedMask.push_back(Mask[i] / 2);
9929       continue;
9930     }
9931
9932     // When zeroing, we need to spread the zeroing across both lanes to widen.
9933     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9934       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9935           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9936         WidenedMask.push_back(SM_SentinelZero);
9937         continue;
9938       }
9939       return false;
9940     }
9941
9942     // Finally check if the two mask values are adjacent and aligned with
9943     // a pair.
9944     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9945       WidenedMask.push_back(Mask[i] / 2);
9946       continue;
9947     }
9948
9949     // Otherwise we can't safely widen the elements used in this shuffle.
9950     return false;
9951   }
9952   assert(WidenedMask.size() == Mask.size() / 2 &&
9953          "Incorrect size of mask after widening the elements!");
9954
9955   return true;
9956 }
9957
9958 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9959 ///
9960 /// This routine just extracts two subvectors, shuffles them independently, and
9961 /// then concatenates them back together. This should work effectively with all
9962 /// AVX vector shuffle types.
9963 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9964                                           SDValue V2, ArrayRef<int> Mask,
9965                                           SelectionDAG &DAG) {
9966   assert(VT.getSizeInBits() >= 256 &&
9967          "Only for 256-bit or wider vector shuffles!");
9968   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9969   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9970
9971   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9972   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9973
9974   int NumElements = VT.getVectorNumElements();
9975   int SplitNumElements = NumElements / 2;
9976   MVT ScalarVT = VT.getVectorElementType();
9977   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9978
9979   // Rather than splitting build-vectors, just build two narrower build
9980   // vectors. This helps shuffling with splats and zeros.
9981   auto SplitVector = [&](SDValue V) {
9982     while (V.getOpcode() == ISD::BITCAST)
9983       V = V->getOperand(0);
9984
9985     MVT OrigVT = V.getSimpleValueType();
9986     int OrigNumElements = OrigVT.getVectorNumElements();
9987     int OrigSplitNumElements = OrigNumElements / 2;
9988     MVT OrigScalarVT = OrigVT.getVectorElementType();
9989     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9990
9991     SDValue LoV, HiV;
9992
9993     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9994     if (!BV) {
9995       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9996                         DAG.getIntPtrConstant(0, DL));
9997       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9998                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9999     } else {
10000
10001       SmallVector<SDValue, 16> LoOps, HiOps;
10002       for (int i = 0; i < OrigSplitNumElements; ++i) {
10003         LoOps.push_back(BV->getOperand(i));
10004         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10005       }
10006       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10007       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10008     }
10009     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10010                           DAG.getBitcast(SplitVT, HiV));
10011   };
10012
10013   SDValue LoV1, HiV1, LoV2, HiV2;
10014   std::tie(LoV1, HiV1) = SplitVector(V1);
10015   std::tie(LoV2, HiV2) = SplitVector(V2);
10016
10017   // Now create two 4-way blends of these half-width vectors.
10018   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10019     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10020     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10021     for (int i = 0; i < SplitNumElements; ++i) {
10022       int M = HalfMask[i];
10023       if (M >= NumElements) {
10024         if (M >= NumElements + SplitNumElements)
10025           UseHiV2 = true;
10026         else
10027           UseLoV2 = true;
10028         V2BlendMask.push_back(M - NumElements);
10029         V1BlendMask.push_back(-1);
10030         BlendMask.push_back(SplitNumElements + i);
10031       } else if (M >= 0) {
10032         if (M >= SplitNumElements)
10033           UseHiV1 = true;
10034         else
10035           UseLoV1 = true;
10036         V2BlendMask.push_back(-1);
10037         V1BlendMask.push_back(M);
10038         BlendMask.push_back(i);
10039       } else {
10040         V2BlendMask.push_back(-1);
10041         V1BlendMask.push_back(-1);
10042         BlendMask.push_back(-1);
10043       }
10044     }
10045
10046     // Because the lowering happens after all combining takes place, we need to
10047     // manually combine these blend masks as much as possible so that we create
10048     // a minimal number of high-level vector shuffle nodes.
10049
10050     // First try just blending the halves of V1 or V2.
10051     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10052       return DAG.getUNDEF(SplitVT);
10053     if (!UseLoV2 && !UseHiV2)
10054       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10055     if (!UseLoV1 && !UseHiV1)
10056       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10057
10058     SDValue V1Blend, V2Blend;
10059     if (UseLoV1 && UseHiV1) {
10060       V1Blend =
10061         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10062     } else {
10063       // We only use half of V1 so map the usage down into the final blend mask.
10064       V1Blend = UseLoV1 ? LoV1 : HiV1;
10065       for (int i = 0; i < SplitNumElements; ++i)
10066         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10067           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10068     }
10069     if (UseLoV2 && UseHiV2) {
10070       V2Blend =
10071         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10072     } else {
10073       // We only use half of V2 so map the usage down into the final blend mask.
10074       V2Blend = UseLoV2 ? LoV2 : HiV2;
10075       for (int i = 0; i < SplitNumElements; ++i)
10076         if (BlendMask[i] >= SplitNumElements)
10077           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10078     }
10079     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10080   };
10081   SDValue Lo = HalfBlend(LoMask);
10082   SDValue Hi = HalfBlend(HiMask);
10083   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10084 }
10085
10086 /// \brief Either split a vector in halves or decompose the shuffles and the
10087 /// blend.
10088 ///
10089 /// This is provided as a good fallback for many lowerings of non-single-input
10090 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10091 /// between splitting the shuffle into 128-bit components and stitching those
10092 /// back together vs. extracting the single-input shuffles and blending those
10093 /// results.
10094 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10095                                                 SDValue V2, ArrayRef<int> Mask,
10096                                                 SelectionDAG &DAG) {
10097   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10098                                             "lower single-input shuffles as it "
10099                                             "could then recurse on itself.");
10100   int Size = Mask.size();
10101
10102   // If this can be modeled as a broadcast of two elements followed by a blend,
10103   // prefer that lowering. This is especially important because broadcasts can
10104   // often fold with memory operands.
10105   auto DoBothBroadcast = [&] {
10106     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10107     for (int M : Mask)
10108       if (M >= Size) {
10109         if (V2BroadcastIdx == -1)
10110           V2BroadcastIdx = M - Size;
10111         else if (M - Size != V2BroadcastIdx)
10112           return false;
10113       } else if (M >= 0) {
10114         if (V1BroadcastIdx == -1)
10115           V1BroadcastIdx = M;
10116         else if (M != V1BroadcastIdx)
10117           return false;
10118       }
10119     return true;
10120   };
10121   if (DoBothBroadcast())
10122     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10123                                                       DAG);
10124
10125   // If the inputs all stem from a single 128-bit lane of each input, then we
10126   // split them rather than blending because the split will decompose to
10127   // unusually few instructions.
10128   int LaneCount = VT.getSizeInBits() / 128;
10129   int LaneSize = Size / LaneCount;
10130   SmallBitVector LaneInputs[2];
10131   LaneInputs[0].resize(LaneCount, false);
10132   LaneInputs[1].resize(LaneCount, false);
10133   for (int i = 0; i < Size; ++i)
10134     if (Mask[i] >= 0)
10135       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10136   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10137     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10138
10139   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10140   // that the decomposed single-input shuffles don't end up here.
10141   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10142 }
10143
10144 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10145 /// a permutation and blend of those lanes.
10146 ///
10147 /// This essentially blends the out-of-lane inputs to each lane into the lane
10148 /// from a permuted copy of the vector. This lowering strategy results in four
10149 /// instructions in the worst case for a single-input cross lane shuffle which
10150 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10151 /// of. Special cases for each particular shuffle pattern should be handled
10152 /// prior to trying this lowering.
10153 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10154                                                        SDValue V1, SDValue V2,
10155                                                        ArrayRef<int> Mask,
10156                                                        SelectionDAG &DAG) {
10157   // FIXME: This should probably be generalized for 512-bit vectors as well.
10158   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10159   int LaneSize = Mask.size() / 2;
10160
10161   // If there are only inputs from one 128-bit lane, splitting will in fact be
10162   // less expensive. The flags track whether the given lane contains an element
10163   // that crosses to another lane.
10164   bool LaneCrossing[2] = {false, false};
10165   for (int i = 0, Size = Mask.size(); i < Size; ++i)
10166     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10167       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10168   if (!LaneCrossing[0] || !LaneCrossing[1])
10169     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10170
10171   if (isSingleInputShuffleMask(Mask)) {
10172     SmallVector<int, 32> FlippedBlendMask;
10173     for (int i = 0, Size = Mask.size(); i < Size; ++i)
10174       FlippedBlendMask.push_back(
10175           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10176                                   ? Mask[i]
10177                                   : Mask[i] % LaneSize +
10178                                         (i / LaneSize) * LaneSize + Size));
10179
10180     // Flip the vector, and blend the results which should now be in-lane. The
10181     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10182     // 5 for the high source. The value 3 selects the high half of source 2 and
10183     // the value 2 selects the low half of source 2. We only use source 2 to
10184     // allow folding it into a memory operand.
10185     unsigned PERMMask = 3 | 2 << 4;
10186     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10187                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10188     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10189   }
10190
10191   // This now reduces to two single-input shuffles of V1 and V2 which at worst
10192   // will be handled by the above logic and a blend of the results, much like
10193   // other patterns in AVX.
10194   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10195 }
10196
10197 /// \brief Handle lowering 2-lane 128-bit shuffles.
10198 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10199                                         SDValue V2, ArrayRef<int> Mask,
10200                                         const X86Subtarget *Subtarget,
10201                                         SelectionDAG &DAG) {
10202   // TODO: If minimizing size and one of the inputs is a zero vector and the
10203   // the zero vector has only one use, we could use a VPERM2X128 to save the
10204   // instruction bytes needed to explicitly generate the zero vector.
10205
10206   // Blends are faster and handle all the non-lane-crossing cases.
10207   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10208                                                 Subtarget, DAG))
10209     return Blend;
10210
10211   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10212   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10213
10214   // If either input operand is a zero vector, use VPERM2X128 because its mask
10215   // allows us to replace the zero input with an implicit zero.
10216   if (!IsV1Zero && !IsV2Zero) {
10217     // Check for patterns which can be matched with a single insert of a 128-bit
10218     // subvector.
10219     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10220     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10221       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10222                                    VT.getVectorNumElements() / 2);
10223       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10224                                 DAG.getIntPtrConstant(0, DL));
10225       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10226                                 OnlyUsesV1 ? V1 : V2,
10227                                 DAG.getIntPtrConstant(0, DL));
10228       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10229     }
10230   }
10231
10232   // Otherwise form a 128-bit permutation. After accounting for undefs,
10233   // convert the 64-bit shuffle mask selection values into 128-bit
10234   // selection bits by dividing the indexes by 2 and shifting into positions
10235   // defined by a vperm2*128 instruction's immediate control byte.
10236
10237   // The immediate permute control byte looks like this:
10238   //    [1:0] - select 128 bits from sources for low half of destination
10239   //    [2]   - ignore
10240   //    [3]   - zero low half of destination
10241   //    [5:4] - select 128 bits from sources for high half of destination
10242   //    [6]   - ignore
10243   //    [7]   - zero high half of destination
10244
10245   int MaskLO = Mask[0];
10246   if (MaskLO == SM_SentinelUndef)
10247     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10248
10249   int MaskHI = Mask[2];
10250   if (MaskHI == SM_SentinelUndef)
10251     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10252
10253   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10254
10255   // If either input is a zero vector, replace it with an undef input.
10256   // Shuffle mask values <  4 are selecting elements of V1.
10257   // Shuffle mask values >= 4 are selecting elements of V2.
10258   // Adjust each half of the permute mask by clearing the half that was
10259   // selecting the zero vector and setting the zero mask bit.
10260   if (IsV1Zero) {
10261     V1 = DAG.getUNDEF(VT);
10262     if (MaskLO < 4)
10263       PermMask = (PermMask & 0xf0) | 0x08;
10264     if (MaskHI < 4)
10265       PermMask = (PermMask & 0x0f) | 0x80;
10266   }
10267   if (IsV2Zero) {
10268     V2 = DAG.getUNDEF(VT);
10269     if (MaskLO >= 4)
10270       PermMask = (PermMask & 0xf0) | 0x08;
10271     if (MaskHI >= 4)
10272       PermMask = (PermMask & 0x0f) | 0x80;
10273   }
10274
10275   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10276                      DAG.getConstant(PermMask, DL, MVT::i8));
10277 }
10278
10279 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10280 /// shuffling each lane.
10281 ///
10282 /// This will only succeed when the result of fixing the 128-bit lanes results
10283 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10284 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10285 /// the lane crosses early and then use simpler shuffles within each lane.
10286 ///
10287 /// FIXME: It might be worthwhile at some point to support this without
10288 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10289 /// in x86 only floating point has interesting non-repeating shuffles, and even
10290 /// those are still *marginally* more expensive.
10291 static SDValue lowerVectorShuffleByMerging128BitLanes(
10292     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10293     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10294   assert(!isSingleInputShuffleMask(Mask) &&
10295          "This is only useful with multiple inputs.");
10296
10297   int Size = Mask.size();
10298   int LaneSize = 128 / VT.getScalarSizeInBits();
10299   int NumLanes = Size / LaneSize;
10300   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10301
10302   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10303   // check whether the in-128-bit lane shuffles share a repeating pattern.
10304   SmallVector<int, 4> Lanes;
10305   Lanes.resize(NumLanes, -1);
10306   SmallVector<int, 4> InLaneMask;
10307   InLaneMask.resize(LaneSize, -1);
10308   for (int i = 0; i < Size; ++i) {
10309     if (Mask[i] < 0)
10310       continue;
10311
10312     int j = i / LaneSize;
10313
10314     if (Lanes[j] < 0) {
10315       // First entry we've seen for this lane.
10316       Lanes[j] = Mask[i] / LaneSize;
10317     } else if (Lanes[j] != Mask[i] / LaneSize) {
10318       // This doesn't match the lane selected previously!
10319       return SDValue();
10320     }
10321
10322     // Check that within each lane we have a consistent shuffle mask.
10323     int k = i % LaneSize;
10324     if (InLaneMask[k] < 0) {
10325       InLaneMask[k] = Mask[i] % LaneSize;
10326     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10327       // This doesn't fit a repeating in-lane mask.
10328       return SDValue();
10329     }
10330   }
10331
10332   // First shuffle the lanes into place.
10333   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10334                                 VT.getSizeInBits() / 64);
10335   SmallVector<int, 8> LaneMask;
10336   LaneMask.resize(NumLanes * 2, -1);
10337   for (int i = 0; i < NumLanes; ++i)
10338     if (Lanes[i] >= 0) {
10339       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10340       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10341     }
10342
10343   V1 = DAG.getBitcast(LaneVT, V1);
10344   V2 = DAG.getBitcast(LaneVT, V2);
10345   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10346
10347   // Cast it back to the type we actually want.
10348   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10349
10350   // Now do a simple shuffle that isn't lane crossing.
10351   SmallVector<int, 8> NewMask;
10352   NewMask.resize(Size, -1);
10353   for (int i = 0; i < Size; ++i)
10354     if (Mask[i] >= 0)
10355       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10356   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10357          "Must not introduce lane crosses at this point!");
10358
10359   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10360 }
10361
10362 /// Lower shuffles where an entire half of a 256-bit vector is UNDEF.
10363 /// This allows for fast cases such as subvector extraction/insertion
10364 /// or shuffling smaller vector types which can lower more efficiently.
10365 static SDValue lowerVectorShuffleWithUndefHalf(SDLoc DL, MVT VT, SDValue V1,
10366                                                SDValue V2, ArrayRef<int> Mask,
10367                                                const X86Subtarget *Subtarget,
10368                                                SelectionDAG &DAG) {
10369   assert(VT.getSizeInBits() == 256 && "Expected 256-bit vector");
10370
10371   unsigned NumElts = VT.getVectorNumElements();
10372   unsigned HalfNumElts = NumElts / 2;
10373   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
10374
10375   bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
10376   bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
10377   if (!UndefLower && !UndefUpper)
10378     return SDValue();
10379
10380   // Upper half is undef and lower half is whole upper subvector.
10381   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
10382   if (UndefUpper &&
10383       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
10384     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10385                              DAG.getIntPtrConstant(HalfNumElts, DL));
10386     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10387                        DAG.getIntPtrConstant(0, DL));
10388   }
10389
10390   // Lower half is undef and upper half is whole lower subvector.
10391   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
10392   if (UndefLower &&
10393       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
10394     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10395                              DAG.getIntPtrConstant(0, DL));
10396     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10397                        DAG.getIntPtrConstant(HalfNumElts, DL));
10398   }
10399
10400   // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
10401   if (UndefLower && Subtarget->hasAVX2() &&
10402       (VT == MVT::v4f64 || VT == MVT::v4i64))
10403     return SDValue();
10404
10405   // If the shuffle only uses the lower halves of the input operands,
10406   // then extract them and perform the 'half' shuffle at half width.
10407   // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
10408   int HalfIdx1 = -1, HalfIdx2 = -1;
10409   SmallVector<int, 8> HalfMask;
10410   unsigned Offset = UndefLower ? HalfNumElts : 0;
10411   for (unsigned i = 0; i != HalfNumElts; ++i) {
10412     int M = Mask[i + Offset];
10413     if (M < 0) {
10414       HalfMask.push_back(M);
10415       continue;
10416     }
10417
10418     // Determine which of the 4 half vectors this element is from.
10419     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
10420     int HalfIdx = M / HalfNumElts;
10421
10422     // Only shuffle using the lower halves of the inputs.
10423     // TODO: Investigate usefulness of shuffling with upper halves.
10424     if (HalfIdx != 0 && HalfIdx != 2)
10425       return SDValue();
10426
10427     // Determine the element index into its half vector source.
10428     int HalfElt = M % HalfNumElts;
10429
10430     // We can shuffle with up to 2 half vectors, set the new 'half'
10431     // shuffle mask accordingly.
10432     if (-1 == HalfIdx1 || HalfIdx1 == HalfIdx) {
10433       HalfMask.push_back(HalfElt);
10434       HalfIdx1 = HalfIdx;
10435       continue;
10436     }
10437     if (-1 == HalfIdx2 || HalfIdx2 == HalfIdx) {
10438       HalfMask.push_back(HalfElt + HalfNumElts);
10439       HalfIdx2 = HalfIdx;
10440       continue;
10441     }
10442
10443     // Too many half vectors referenced.
10444     return SDValue();
10445   }
10446   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
10447
10448   auto GetHalfVector = [&](int HalfIdx) {
10449     if (HalfIdx < 0)
10450       return DAG.getUNDEF(HalfVT);
10451     SDValue V = (HalfIdx < 2 ? V1 : V2);
10452     HalfIdx = (HalfIdx % 2) * HalfNumElts;
10453     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
10454                        DAG.getIntPtrConstant(HalfIdx, DL));
10455   };
10456
10457   SDValue Half1 = GetHalfVector(HalfIdx1);
10458   SDValue Half2 = GetHalfVector(HalfIdx2);
10459   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
10460   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
10461                      DAG.getIntPtrConstant(Offset, DL));
10462 }
10463
10464 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10465 /// given mask.
10466 ///
10467 /// This returns true if the elements from a particular input are already in the
10468 /// slot required by the given mask and require no permutation.
10469 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10470   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10471   int Size = Mask.size();
10472   for (int i = 0; i < Size; ++i)
10473     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10474       return false;
10475
10476   return true;
10477 }
10478
10479 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10480                                             ArrayRef<int> Mask, SDValue V1,
10481                                             SDValue V2, SelectionDAG &DAG) {
10482
10483   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10484   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10485   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10486   int NumElts = VT.getVectorNumElements();
10487   bool ShufpdMask = true;
10488   bool CommutableMask = true;
10489   unsigned Immediate = 0;
10490   for (int i = 0; i < NumElts; ++i) {
10491     if (Mask[i] < 0)
10492       continue;
10493     int Val = (i & 6) + NumElts * (i & 1);
10494     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10495     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10496       ShufpdMask = false;
10497     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10498       CommutableMask = false;
10499     Immediate |= (Mask[i] % 2) << i;
10500   }
10501   if (ShufpdMask)
10502     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10503                        DAG.getConstant(Immediate, DL, MVT::i8));
10504   if (CommutableMask)
10505     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10506                        DAG.getConstant(Immediate, DL, MVT::i8));
10507   return SDValue();
10508 }
10509
10510 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10511 ///
10512 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10513 /// isn't available.
10514 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10515                                        const X86Subtarget *Subtarget,
10516                                        SelectionDAG &DAG) {
10517   SDLoc DL(Op);
10518   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10519   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10520   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10521   ArrayRef<int> Mask = SVOp->getMask();
10522   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10523
10524   SmallVector<int, 4> WidenedMask;
10525   if (canWidenShuffleElements(Mask, WidenedMask))
10526     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10527                                     DAG);
10528
10529   if (isSingleInputShuffleMask(Mask)) {
10530     // Check for being able to broadcast a single element.
10531     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10532                                                           Mask, Subtarget, DAG))
10533       return Broadcast;
10534
10535     // Use low duplicate instructions for masks that match their pattern.
10536     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10537       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10538
10539     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10540       // Non-half-crossing single input shuffles can be lowerid with an
10541       // interleaved permutation.
10542       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10543                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10544       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10545                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10546     }
10547
10548     // With AVX2 we have direct support for this permutation.
10549     if (Subtarget->hasAVX2())
10550       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10551                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10552
10553     // Otherwise, fall back.
10554     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10555                                                    DAG);
10556   }
10557
10558   // Use dedicated unpack instructions for masks that match their pattern.
10559   if (SDValue V =
10560           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10561     return V;
10562
10563   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10564                                                 Subtarget, DAG))
10565     return Blend;
10566
10567   // Check if the blend happens to exactly fit that of SHUFPD.
10568   if (SDValue Op =
10569       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10570     return Op;
10571
10572   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10573   // shuffle. However, if we have AVX2 and either inputs are already in place,
10574   // we will be able to shuffle even across lanes the other input in a single
10575   // instruction so skip this pattern.
10576   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10577                                  isShuffleMaskInputInPlace(1, Mask))))
10578     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10579             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10580       return Result;
10581
10582   // If we have AVX2 then we always want to lower with a blend because an v4 we
10583   // can fully permute the elements.
10584   if (Subtarget->hasAVX2())
10585     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10586                                                       Mask, DAG);
10587
10588   // Otherwise fall back on generic lowering.
10589   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10590 }
10591
10592 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10593 ///
10594 /// This routine is only called when we have AVX2 and thus a reasonable
10595 /// instruction set for v4i64 shuffling..
10596 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10597                                        const X86Subtarget *Subtarget,
10598                                        SelectionDAG &DAG) {
10599   SDLoc DL(Op);
10600   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10601   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10602   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10603   ArrayRef<int> Mask = SVOp->getMask();
10604   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10605   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10606
10607   SmallVector<int, 4> WidenedMask;
10608   if (canWidenShuffleElements(Mask, WidenedMask))
10609     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10610                                     DAG);
10611
10612   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10613                                                 Subtarget, DAG))
10614     return Blend;
10615
10616   // Check for being able to broadcast a single element.
10617   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10618                                                         Mask, Subtarget, DAG))
10619     return Broadcast;
10620
10621   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10622   // use lower latency instructions that will operate on both 128-bit lanes.
10623   SmallVector<int, 2> RepeatedMask;
10624   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10625     if (isSingleInputShuffleMask(Mask)) {
10626       int PSHUFDMask[] = {-1, -1, -1, -1};
10627       for (int i = 0; i < 2; ++i)
10628         if (RepeatedMask[i] >= 0) {
10629           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10630           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10631         }
10632       return DAG.getBitcast(
10633           MVT::v4i64,
10634           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10635                       DAG.getBitcast(MVT::v8i32, V1),
10636                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10637     }
10638   }
10639
10640   // AVX2 provides a direct instruction for permuting a single input across
10641   // lanes.
10642   if (isSingleInputShuffleMask(Mask))
10643     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10644                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10645
10646   // Try to use shift instructions.
10647   if (SDValue Shift =
10648           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10649     return Shift;
10650
10651   // Use dedicated unpack instructions for masks that match their pattern.
10652   if (SDValue V =
10653           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10654     return V;
10655
10656   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10657   // shuffle. However, if we have AVX2 and either inputs are already in place,
10658   // we will be able to shuffle even across lanes the other input in a single
10659   // instruction so skip this pattern.
10660   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10661                                  isShuffleMaskInputInPlace(1, Mask))))
10662     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10663             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10664       return Result;
10665
10666   // Otherwise fall back on generic blend lowering.
10667   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10668                                                     Mask, DAG);
10669 }
10670
10671 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10672 ///
10673 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10674 /// isn't available.
10675 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10676                                        const X86Subtarget *Subtarget,
10677                                        SelectionDAG &DAG) {
10678   SDLoc DL(Op);
10679   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10680   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10681   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10682   ArrayRef<int> Mask = SVOp->getMask();
10683   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10684
10685   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10686                                                 Subtarget, DAG))
10687     return Blend;
10688
10689   // Check for being able to broadcast a single element.
10690   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10691                                                         Mask, Subtarget, DAG))
10692     return Broadcast;
10693
10694   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10695   // options to efficiently lower the shuffle.
10696   SmallVector<int, 4> RepeatedMask;
10697   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10698     assert(RepeatedMask.size() == 4 &&
10699            "Repeated masks must be half the mask width!");
10700
10701     // Use even/odd duplicate instructions for masks that match their pattern.
10702     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10703       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10704     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10705       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10706
10707     if (isSingleInputShuffleMask(Mask))
10708       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10709                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10710
10711     // Use dedicated unpack instructions for masks that match their pattern.
10712     if (SDValue V =
10713             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10714       return V;
10715
10716     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10717     // have already handled any direct blends. We also need to squash the
10718     // repeated mask into a simulated v4f32 mask.
10719     for (int i = 0; i < 4; ++i)
10720       if (RepeatedMask[i] >= 8)
10721         RepeatedMask[i] -= 4;
10722     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10723   }
10724
10725   // If we have a single input shuffle with different shuffle patterns in the
10726   // two 128-bit lanes use the variable mask to VPERMILPS.
10727   if (isSingleInputShuffleMask(Mask)) {
10728     SDValue VPermMask[8];
10729     for (int i = 0; i < 8; ++i)
10730       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10731                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10732     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10733       return DAG.getNode(
10734           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10735           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10736
10737     if (Subtarget->hasAVX2())
10738       return DAG.getNode(
10739           X86ISD::VPERMV, DL, MVT::v8f32,
10740           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10741
10742     // Otherwise, fall back.
10743     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10744                                                    DAG);
10745   }
10746
10747   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10748   // shuffle.
10749   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10750           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10751     return Result;
10752
10753   // If we have AVX2 then we always want to lower with a blend because at v8 we
10754   // can fully permute the elements.
10755   if (Subtarget->hasAVX2())
10756     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10757                                                       Mask, DAG);
10758
10759   // Otherwise fall back on generic lowering.
10760   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10761 }
10762
10763 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10764 ///
10765 /// This routine is only called when we have AVX2 and thus a reasonable
10766 /// instruction set for v8i32 shuffling..
10767 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10768                                        const X86Subtarget *Subtarget,
10769                                        SelectionDAG &DAG) {
10770   SDLoc DL(Op);
10771   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10772   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10773   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10774   ArrayRef<int> Mask = SVOp->getMask();
10775   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10776   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10777
10778   // Whenever we can lower this as a zext, that instruction is strictly faster
10779   // than any alternative. It also allows us to fold memory operands into the
10780   // shuffle in many cases.
10781   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10782                                                          Mask, Subtarget, DAG))
10783     return ZExt;
10784
10785   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10786                                                 Subtarget, DAG))
10787     return Blend;
10788
10789   // Check for being able to broadcast a single element.
10790   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10791                                                         Mask, Subtarget, DAG))
10792     return Broadcast;
10793
10794   // If the shuffle mask is repeated in each 128-bit lane we can use more
10795   // efficient instructions that mirror the shuffles across the two 128-bit
10796   // lanes.
10797   SmallVector<int, 4> RepeatedMask;
10798   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10799     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10800     if (isSingleInputShuffleMask(Mask))
10801       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10802                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10803
10804     // Use dedicated unpack instructions for masks that match their pattern.
10805     if (SDValue V =
10806             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10807       return V;
10808   }
10809
10810   // Try to use shift instructions.
10811   if (SDValue Shift =
10812           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10813     return Shift;
10814
10815   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10816           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10817     return Rotate;
10818
10819   // If the shuffle patterns aren't repeated but it is a single input, directly
10820   // generate a cross-lane VPERMD instruction.
10821   if (isSingleInputShuffleMask(Mask)) {
10822     SDValue VPermMask[8];
10823     for (int i = 0; i < 8; ++i)
10824       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10825                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10826     return DAG.getNode(
10827         X86ISD::VPERMV, DL, MVT::v8i32,
10828         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10829   }
10830
10831   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10832   // shuffle.
10833   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10834           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10835     return Result;
10836
10837   // Otherwise fall back on generic blend lowering.
10838   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10839                                                     Mask, DAG);
10840 }
10841
10842 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10843 ///
10844 /// This routine is only called when we have AVX2 and thus a reasonable
10845 /// instruction set for v16i16 shuffling..
10846 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10847                                         const X86Subtarget *Subtarget,
10848                                         SelectionDAG &DAG) {
10849   SDLoc DL(Op);
10850   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10851   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10852   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10853   ArrayRef<int> Mask = SVOp->getMask();
10854   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10855   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10856
10857   // Whenever we can lower this as a zext, that instruction is strictly faster
10858   // than any alternative. It also allows us to fold memory operands into the
10859   // shuffle in many cases.
10860   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10861                                                          Mask, Subtarget, DAG))
10862     return ZExt;
10863
10864   // Check for being able to broadcast a single element.
10865   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10866                                                         Mask, Subtarget, DAG))
10867     return Broadcast;
10868
10869   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10870                                                 Subtarget, DAG))
10871     return Blend;
10872
10873   // Use dedicated unpack instructions for masks that match their pattern.
10874   if (SDValue V =
10875           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10876     return V;
10877
10878   // Try to use shift instructions.
10879   if (SDValue Shift =
10880           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10881     return Shift;
10882
10883   // Try to use byte rotation instructions.
10884   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10885           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10886     return Rotate;
10887
10888   if (isSingleInputShuffleMask(Mask)) {
10889     // There are no generalized cross-lane shuffle operations available on i16
10890     // element types.
10891     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10892       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10893                                                      Mask, DAG);
10894
10895     SmallVector<int, 8> RepeatedMask;
10896     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10897       // As this is a single-input shuffle, the repeated mask should be
10898       // a strictly valid v8i16 mask that we can pass through to the v8i16
10899       // lowering to handle even the v16 case.
10900       return lowerV8I16GeneralSingleInputVectorShuffle(
10901           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10902     }
10903
10904     SDValue PSHUFBMask[32];
10905     for (int i = 0; i < 16; ++i) {
10906       if (Mask[i] == -1) {
10907         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10908         continue;
10909       }
10910
10911       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10912       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10913       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10914       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10915     }
10916     return DAG.getBitcast(MVT::v16i16,
10917                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10918                                       DAG.getBitcast(MVT::v32i8, V1),
10919                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10920                                                   MVT::v32i8, PSHUFBMask)));
10921   }
10922
10923   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10924   // shuffle.
10925   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10926           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10927     return Result;
10928
10929   // Otherwise fall back on generic lowering.
10930   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10931 }
10932
10933 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10934 ///
10935 /// This routine is only called when we have AVX2 and thus a reasonable
10936 /// instruction set for v32i8 shuffling..
10937 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10938                                        const X86Subtarget *Subtarget,
10939                                        SelectionDAG &DAG) {
10940   SDLoc DL(Op);
10941   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10942   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10943   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10944   ArrayRef<int> Mask = SVOp->getMask();
10945   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10946   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10947
10948   // Whenever we can lower this as a zext, that instruction is strictly faster
10949   // than any alternative. It also allows us to fold memory operands into the
10950   // shuffle in many cases.
10951   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10952                                                          Mask, Subtarget, DAG))
10953     return ZExt;
10954
10955   // Check for being able to broadcast a single element.
10956   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10957                                                         Mask, Subtarget, DAG))
10958     return Broadcast;
10959
10960   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10961                                                 Subtarget, DAG))
10962     return Blend;
10963
10964   // Use dedicated unpack instructions for masks that match their pattern.
10965   if (SDValue V =
10966           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10967     return V;
10968
10969   // Try to use shift instructions.
10970   if (SDValue Shift =
10971           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10972     return Shift;
10973
10974   // Try to use byte rotation instructions.
10975   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10976           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10977     return Rotate;
10978
10979   if (isSingleInputShuffleMask(Mask)) {
10980     // There are no generalized cross-lane shuffle operations available on i8
10981     // element types.
10982     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10983       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10984                                                      Mask, DAG);
10985
10986     SDValue PSHUFBMask[32];
10987     for (int i = 0; i < 32; ++i)
10988       PSHUFBMask[i] =
10989           Mask[i] < 0
10990               ? DAG.getUNDEF(MVT::i8)
10991               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10992                                 MVT::i8);
10993
10994     return DAG.getNode(
10995         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10996         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10997   }
10998
10999   // Try to simplify this by merging 128-bit lanes to enable a lane-based
11000   // shuffle.
11001   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11002           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11003     return Result;
11004
11005   // Otherwise fall back on generic lowering.
11006   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11007 }
11008
11009 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11010 ///
11011 /// This routine either breaks down the specific type of a 256-bit x86 vector
11012 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11013 /// together based on the available instructions.
11014 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11015                                         MVT VT, const X86Subtarget *Subtarget,
11016                                         SelectionDAG &DAG) {
11017   SDLoc DL(Op);
11018   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11019   ArrayRef<int> Mask = SVOp->getMask();
11020
11021   // If we have a single input to the zero element, insert that into V1 if we
11022   // can do so cheaply.
11023   int NumElts = VT.getVectorNumElements();
11024   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
11025     return M >= NumElts;
11026   });
11027
11028   if (NumV2Elements == 1 && Mask[0] >= NumElts)
11029     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
11030                               DL, VT, V1, V2, Mask, Subtarget, DAG))
11031       return Insertion;
11032
11033   // Handle special cases where the lower or upper half is UNDEF.
11034   if (SDValue V =
11035           lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
11036     return V;
11037
11038   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
11039   // can check for those subtargets here and avoid much of the subtarget
11040   // querying in the per-vector-type lowering routines. With AVX1 we have
11041   // essentially *zero* ability to manipulate a 256-bit vector with integer
11042   // types. Since we'll use floating point types there eventually, just
11043   // immediately cast everything to a float and operate entirely in that domain.
11044   if (VT.isInteger() && !Subtarget->hasAVX2()) {
11045     int ElementBits = VT.getScalarSizeInBits();
11046     if (ElementBits < 32)
11047       // No floating point type available, decompose into 128-bit vectors.
11048       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11049
11050     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11051                                 VT.getVectorNumElements());
11052     V1 = DAG.getBitcast(FpVT, V1);
11053     V2 = DAG.getBitcast(FpVT, V2);
11054     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11055   }
11056
11057   switch (VT.SimpleTy) {
11058   case MVT::v4f64:
11059     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11060   case MVT::v4i64:
11061     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11062   case MVT::v8f32:
11063     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11064   case MVT::v8i32:
11065     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11066   case MVT::v16i16:
11067     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11068   case MVT::v32i8:
11069     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11070
11071   default:
11072     llvm_unreachable("Not a valid 256-bit x86 vector type!");
11073   }
11074 }
11075
11076 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
11077 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
11078                                         ArrayRef<int> Mask,
11079                                         SDValue V1, SDValue V2,
11080                                         SelectionDAG &DAG) {
11081   assert(VT.getScalarSizeInBits() == 64 &&
11082          "Unexpected element type size for 128bit shuffle.");
11083
11084   // To handle 256 bit vector requires VLX and most probably
11085   // function lowerV2X128VectorShuffle() is better solution.
11086   assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
11087
11088   SmallVector<int, 4> WidenedMask;
11089   if (!canWidenShuffleElements(Mask, WidenedMask))
11090     return SDValue();
11091
11092   // Form a 128-bit permutation.
11093   // Convert the 64-bit shuffle mask selection values into 128-bit selection
11094   // bits defined by a vshuf64x2 instruction's immediate control byte.
11095   unsigned PermMask = 0, Imm = 0;
11096   unsigned ControlBitsNum = WidenedMask.size() / 2;
11097
11098   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11099     if (WidenedMask[i] == SM_SentinelZero)
11100       return SDValue();
11101
11102     // Use first element in place of undef mask.
11103     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
11104     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
11105   }
11106
11107   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
11108                      DAG.getConstant(PermMask, DL, MVT::i8));
11109 }
11110
11111 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
11112                                            ArrayRef<int> Mask, SDValue V1,
11113                                            SDValue V2, SelectionDAG &DAG) {
11114
11115   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11116
11117   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11118   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11119
11120   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11121   if (isSingleInputShuffleMask(Mask))
11122     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11123
11124   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11125 }
11126
11127 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11128 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11129                                        const X86Subtarget *Subtarget,
11130                                        SelectionDAG &DAG) {
11131   SDLoc DL(Op);
11132   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11133   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11134   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11135   ArrayRef<int> Mask = SVOp->getMask();
11136   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11137
11138   if (SDValue Shuf128 =
11139           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11140     return Shuf128;
11141
11142   if (SDValue Unpck =
11143           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11144     return Unpck;
11145
11146   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11147 }
11148
11149 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11150 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11151                                         const X86Subtarget *Subtarget,
11152                                         SelectionDAG &DAG) {
11153   SDLoc DL(Op);
11154   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11155   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11156   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11157   ArrayRef<int> Mask = SVOp->getMask();
11158   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11159
11160   if (SDValue Unpck =
11161           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11162     return Unpck;
11163
11164   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11165 }
11166
11167 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11168 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11169                                        const X86Subtarget *Subtarget,
11170                                        SelectionDAG &DAG) {
11171   SDLoc DL(Op);
11172   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11173   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11174   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11175   ArrayRef<int> Mask = SVOp->getMask();
11176   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11177
11178   if (SDValue Shuf128 =
11179           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11180     return Shuf128;
11181
11182   if (SDValue Unpck =
11183           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11184     return Unpck;
11185
11186   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11187 }
11188
11189 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11190 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11191                                         const X86Subtarget *Subtarget,
11192                                         SelectionDAG &DAG) {
11193   SDLoc DL(Op);
11194   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11195   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11196   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11197   ArrayRef<int> Mask = SVOp->getMask();
11198   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11199
11200   if (SDValue Unpck =
11201           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11202     return Unpck;
11203
11204   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11205 }
11206
11207 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11208 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11209                                         const X86Subtarget *Subtarget,
11210                                         SelectionDAG &DAG) {
11211   SDLoc DL(Op);
11212   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11213   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11214   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11215   ArrayRef<int> Mask = SVOp->getMask();
11216   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11217   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11218
11219   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11220 }
11221
11222 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11223 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11224                                        const X86Subtarget *Subtarget,
11225                                        SelectionDAG &DAG) {
11226   SDLoc DL(Op);
11227   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11228   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11229   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11230   ArrayRef<int> Mask = SVOp->getMask();
11231   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11232   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11233
11234   // FIXME: Implement direct support for this type!
11235   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11236 }
11237
11238 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11239 ///
11240 /// This routine either breaks down the specific type of a 512-bit x86 vector
11241 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11242 /// together based on the available instructions.
11243 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11244                                         MVT VT, const X86Subtarget *Subtarget,
11245                                         SelectionDAG &DAG) {
11246   SDLoc DL(Op);
11247   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11248   ArrayRef<int> Mask = SVOp->getMask();
11249   assert(Subtarget->hasAVX512() &&
11250          "Cannot lower 512-bit vectors w/ basic ISA!");
11251
11252   // Check for being able to broadcast a single element.
11253   if (SDValue Broadcast =
11254           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11255     return Broadcast;
11256
11257   // Dispatch to each element type for lowering. If we don't have supprot for
11258   // specific element type shuffles at 512 bits, immediately split them and
11259   // lower them. Each lowering routine of a given type is allowed to assume that
11260   // the requisite ISA extensions for that element type are available.
11261   switch (VT.SimpleTy) {
11262   case MVT::v8f64:
11263     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11264   case MVT::v16f32:
11265     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11266   case MVT::v8i64:
11267     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11268   case MVT::v16i32:
11269     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11270   case MVT::v32i16:
11271     if (Subtarget->hasBWI())
11272       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11273     break;
11274   case MVT::v64i8:
11275     if (Subtarget->hasBWI())
11276       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11277     break;
11278
11279   default:
11280     llvm_unreachable("Not a valid 512-bit x86 vector type!");
11281   }
11282
11283   // Otherwise fall back on splitting.
11284   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11285 }
11286
11287 // Lower vXi1 vector shuffles.
11288 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11289 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11290 // vector, shuffle and then truncate it back.
11291 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11292                                       MVT VT, const X86Subtarget *Subtarget,
11293                                       SelectionDAG &DAG) {
11294   SDLoc DL(Op);
11295   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11296   ArrayRef<int> Mask = SVOp->getMask();
11297   assert(Subtarget->hasAVX512() &&
11298          "Cannot lower 512-bit vectors w/o basic ISA!");
11299   MVT ExtVT;
11300   switch (VT.SimpleTy) {
11301   default:
11302     llvm_unreachable("Expected a vector of i1 elements");
11303   case MVT::v2i1:
11304     ExtVT = MVT::v2i64;
11305     break;
11306   case MVT::v4i1:
11307     ExtVT = MVT::v4i32;
11308     break;
11309   case MVT::v8i1:
11310     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11311     break;
11312   case MVT::v16i1:
11313     ExtVT = MVT::v16i32;
11314     break;
11315   case MVT::v32i1:
11316     ExtVT = MVT::v32i16;
11317     break;
11318   case MVT::v64i1:
11319     ExtVT = MVT::v64i8;
11320     break;
11321   }
11322
11323   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11324     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11325   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11326     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11327   else
11328     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11329
11330   if (V2.isUndef())
11331     V2 = DAG.getUNDEF(ExtVT);
11332   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11333     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11334   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11335     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11336   else
11337     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11338   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11339                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11340 }
11341 /// \brief Top-level lowering for x86 vector shuffles.
11342 ///
11343 /// This handles decomposition, canonicalization, and lowering of all x86
11344 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11345 /// above in helper routines. The canonicalization attempts to widen shuffles
11346 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11347 /// s.t. only one of the two inputs needs to be tested, etc.
11348 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11349                                   SelectionDAG &DAG) {
11350   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11351   ArrayRef<int> Mask = SVOp->getMask();
11352   SDValue V1 = Op.getOperand(0);
11353   SDValue V2 = Op.getOperand(1);
11354   MVT VT = Op.getSimpleValueType();
11355   int NumElements = VT.getVectorNumElements();
11356   SDLoc dl(Op);
11357   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11358
11359   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11360          "Can't lower MMX shuffles");
11361
11362   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11363   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11364   if (V1IsUndef && V2IsUndef)
11365     return DAG.getUNDEF(VT);
11366
11367   // When we create a shuffle node we put the UNDEF node to second operand,
11368   // but in some cases the first operand may be transformed to UNDEF.
11369   // In this case we should just commute the node.
11370   if (V1IsUndef)
11371     return DAG.getCommutedVectorShuffle(*SVOp);
11372
11373   // Check for non-undef masks pointing at an undef vector and make the masks
11374   // undef as well. This makes it easier to match the shuffle based solely on
11375   // the mask.
11376   if (V2IsUndef)
11377     for (int M : Mask)
11378       if (M >= NumElements) {
11379         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11380         for (int &M : NewMask)
11381           if (M >= NumElements)
11382             M = -1;
11383         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11384       }
11385
11386   // We actually see shuffles that are entirely re-arrangements of a set of
11387   // zero inputs. This mostly happens while decomposing complex shuffles into
11388   // simple ones. Directly lower these as a buildvector of zeros.
11389   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11390   if (Zeroable.all())
11391     return getZeroVector(VT, Subtarget, DAG, dl);
11392
11393   // Try to collapse shuffles into using a vector type with fewer elements but
11394   // wider element types. We cap this to not form integers or floating point
11395   // elements wider than 64 bits, but it might be interesting to form i128
11396   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11397   SmallVector<int, 16> WidenedMask;
11398   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11399       canWidenShuffleElements(Mask, WidenedMask)) {
11400     MVT NewEltVT = VT.isFloatingPoint()
11401                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11402                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11403     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11404     // Make sure that the new vector type is legal. For example, v2f64 isn't
11405     // legal on SSE1.
11406     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11407       V1 = DAG.getBitcast(NewVT, V1);
11408       V2 = DAG.getBitcast(NewVT, V2);
11409       return DAG.getBitcast(
11410           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11411     }
11412   }
11413
11414   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11415   for (int M : SVOp->getMask())
11416     if (M < 0)
11417       ++NumUndefElements;
11418     else if (M < NumElements)
11419       ++NumV1Elements;
11420     else
11421       ++NumV2Elements;
11422
11423   // Commute the shuffle as needed such that more elements come from V1 than
11424   // V2. This allows us to match the shuffle pattern strictly on how many
11425   // elements come from V1 without handling the symmetric cases.
11426   if (NumV2Elements > NumV1Elements)
11427     return DAG.getCommutedVectorShuffle(*SVOp);
11428
11429   // When the number of V1 and V2 elements are the same, try to minimize the
11430   // number of uses of V2 in the low half of the vector. When that is tied,
11431   // ensure that the sum of indices for V1 is equal to or lower than the sum
11432   // indices for V2. When those are equal, try to ensure that the number of odd
11433   // indices for V1 is lower than the number of odd indices for V2.
11434   if (NumV1Elements == NumV2Elements) {
11435     int LowV1Elements = 0, LowV2Elements = 0;
11436     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11437       if (M >= NumElements)
11438         ++LowV2Elements;
11439       else if (M >= 0)
11440         ++LowV1Elements;
11441     if (LowV2Elements > LowV1Elements) {
11442       return DAG.getCommutedVectorShuffle(*SVOp);
11443     } else if (LowV2Elements == LowV1Elements) {
11444       int SumV1Indices = 0, SumV2Indices = 0;
11445       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11446         if (SVOp->getMask()[i] >= NumElements)
11447           SumV2Indices += i;
11448         else if (SVOp->getMask()[i] >= 0)
11449           SumV1Indices += i;
11450       if (SumV2Indices < SumV1Indices) {
11451         return DAG.getCommutedVectorShuffle(*SVOp);
11452       } else if (SumV2Indices == SumV1Indices) {
11453         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11454         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11455           if (SVOp->getMask()[i] >= NumElements)
11456             NumV2OddIndices += i % 2;
11457           else if (SVOp->getMask()[i] >= 0)
11458             NumV1OddIndices += i % 2;
11459         if (NumV2OddIndices < NumV1OddIndices)
11460           return DAG.getCommutedVectorShuffle(*SVOp);
11461       }
11462     }
11463   }
11464
11465   // For each vector width, delegate to a specialized lowering routine.
11466   if (VT.is128BitVector())
11467     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11468
11469   if (VT.is256BitVector())
11470     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11471
11472   if (VT.is512BitVector())
11473     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11474
11475   if (Is1BitVector)
11476     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11477   llvm_unreachable("Unimplemented!");
11478 }
11479
11480 // This function assumes its argument is a BUILD_VECTOR of constants or
11481 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11482 // true.
11483 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11484                                     unsigned &MaskValue) {
11485   MaskValue = 0;
11486   unsigned NumElems = BuildVector->getNumOperands();
11487
11488   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11489   // We don't handle the >2 lanes case right now.
11490   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11491   if (NumLanes > 2)
11492     return false;
11493
11494   unsigned NumElemsInLane = NumElems / NumLanes;
11495
11496   // Blend for v16i16 should be symmetric for the both lanes.
11497   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11498     SDValue EltCond = BuildVector->getOperand(i);
11499     SDValue SndLaneEltCond =
11500         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11501
11502     int Lane1Cond = -1, Lane2Cond = -1;
11503     if (isa<ConstantSDNode>(EltCond))
11504       Lane1Cond = !isNullConstant(EltCond);
11505     if (isa<ConstantSDNode>(SndLaneEltCond))
11506       Lane2Cond = !isNullConstant(SndLaneEltCond);
11507
11508     unsigned LaneMask = 0;
11509     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11510       // Lane1Cond != 0, means we want the first argument.
11511       // Lane1Cond == 0, means we want the second argument.
11512       // The encoding of this argument is 0 for the first argument, 1
11513       // for the second. Therefore, invert the condition.
11514       LaneMask = !Lane1Cond << i;
11515     else if (Lane1Cond < 0)
11516       LaneMask = !Lane2Cond << i;
11517     else
11518       return false;
11519
11520     MaskValue |= LaneMask;
11521     if (NumLanes == 2)
11522       MaskValue |= LaneMask << NumElemsInLane;
11523   }
11524   return true;
11525 }
11526
11527 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11528 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11529                                            const X86Subtarget *Subtarget,
11530                                            SelectionDAG &DAG) {
11531   SDValue Cond = Op.getOperand(0);
11532   SDValue LHS = Op.getOperand(1);
11533   SDValue RHS = Op.getOperand(2);
11534   SDLoc dl(Op);
11535   MVT VT = Op.getSimpleValueType();
11536
11537   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11538     return SDValue();
11539   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11540
11541   // Only non-legal VSELECTs reach this lowering, convert those into generic
11542   // shuffles and re-use the shuffle lowering path for blends.
11543   SmallVector<int, 32> Mask;
11544   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11545     SDValue CondElt = CondBV->getOperand(i);
11546     Mask.push_back(
11547         isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11548                                      : -1);
11549   }
11550   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11551 }
11552
11553 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11554   // A vselect where all conditions and data are constants can be optimized into
11555   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11556   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11557       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11558       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11559     return SDValue();
11560
11561   // Try to lower this to a blend-style vector shuffle. This can handle all
11562   // constant condition cases.
11563   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11564     return BlendOp;
11565
11566   // Variable blends are only legal from SSE4.1 onward.
11567   if (!Subtarget->hasSSE41())
11568     return SDValue();
11569
11570   // Only some types will be legal on some subtargets. If we can emit a legal
11571   // VSELECT-matching blend, return Op, and but if we need to expand, return
11572   // a null value.
11573   switch (Op.getSimpleValueType().SimpleTy) {
11574   default:
11575     // Most of the vector types have blends past SSE4.1.
11576     return Op;
11577
11578   case MVT::v32i8:
11579     // The byte blends for AVX vectors were introduced only in AVX2.
11580     if (Subtarget->hasAVX2())
11581       return Op;
11582
11583     return SDValue();
11584
11585   case MVT::v8i16:
11586   case MVT::v16i16:
11587     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11588     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11589       return Op;
11590
11591     // FIXME: We should custom lower this by fixing the condition and using i8
11592     // blends.
11593     return SDValue();
11594   }
11595 }
11596
11597 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11598   MVT VT = Op.getSimpleValueType();
11599   SDLoc dl(Op);
11600
11601   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11602     return SDValue();
11603
11604   if (VT.getSizeInBits() == 8) {
11605     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11606                                   Op.getOperand(0), Op.getOperand(1));
11607     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11608                                   DAG.getValueType(VT));
11609     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11610   }
11611
11612   if (VT.getSizeInBits() == 16) {
11613     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11614     if (isNullConstant(Op.getOperand(1)))
11615       return DAG.getNode(
11616           ISD::TRUNCATE, dl, MVT::i16,
11617           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11618                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11619                       Op.getOperand(1)));
11620     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11621                                   Op.getOperand(0), Op.getOperand(1));
11622     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11623                                   DAG.getValueType(VT));
11624     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11625   }
11626
11627   if (VT == MVT::f32) {
11628     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11629     // the result back to FR32 register. It's only worth matching if the
11630     // result has a single use which is a store or a bitcast to i32.  And in
11631     // the case of a store, it's not worth it if the index is a constant 0,
11632     // because a MOVSSmr can be used instead, which is smaller and faster.
11633     if (!Op.hasOneUse())
11634       return SDValue();
11635     SDNode *User = *Op.getNode()->use_begin();
11636     if ((User->getOpcode() != ISD::STORE ||
11637          isNullConstant(Op.getOperand(1))) &&
11638         (User->getOpcode() != ISD::BITCAST ||
11639          User->getValueType(0) != MVT::i32))
11640       return SDValue();
11641     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11642                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11643                                   Op.getOperand(1));
11644     return DAG.getBitcast(MVT::f32, Extract);
11645   }
11646
11647   if (VT == MVT::i32 || VT == MVT::i64) {
11648     // ExtractPS/pextrq works with constant index.
11649     if (isa<ConstantSDNode>(Op.getOperand(1)))
11650       return Op;
11651   }
11652   return SDValue();
11653 }
11654
11655 /// Extract one bit from mask vector, like v16i1 or v8i1.
11656 /// AVX-512 feature.
11657 SDValue
11658 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11659   SDValue Vec = Op.getOperand(0);
11660   SDLoc dl(Vec);
11661   MVT VecVT = Vec.getSimpleValueType();
11662   SDValue Idx = Op.getOperand(1);
11663   MVT EltVT = Op.getSimpleValueType();
11664
11665   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11666   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11667          "Unexpected vector type in ExtractBitFromMaskVector");
11668
11669   // variable index can't be handled in mask registers,
11670   // extend vector to VR512
11671   if (!isa<ConstantSDNode>(Idx)) {
11672     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11673     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11674     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11675                               ExtVT.getVectorElementType(), Ext, Idx);
11676     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11677   }
11678
11679   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11680   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11681   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11682     rc = getRegClassFor(MVT::v16i1);
11683   unsigned MaxSift = rc->getSize()*8 - 1;
11684   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11685                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11686   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11687                     DAG.getConstant(MaxSift, dl, MVT::i8));
11688   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11689                        DAG.getIntPtrConstant(0, dl));
11690 }
11691
11692 SDValue
11693 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11694                                            SelectionDAG &DAG) const {
11695   SDLoc dl(Op);
11696   SDValue Vec = Op.getOperand(0);
11697   MVT VecVT = Vec.getSimpleValueType();
11698   SDValue Idx = Op.getOperand(1);
11699
11700   if (Op.getSimpleValueType() == MVT::i1)
11701     return ExtractBitFromMaskVector(Op, DAG);
11702
11703   if (!isa<ConstantSDNode>(Idx)) {
11704     if (VecVT.is512BitVector() ||
11705         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11706          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11707
11708       MVT MaskEltVT =
11709         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11710       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11711                                     MaskEltVT.getSizeInBits());
11712
11713       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11714       auto PtrVT = getPointerTy(DAG.getDataLayout());
11715       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11716                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11717                                  DAG.getConstant(0, dl, PtrVT));
11718       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11719       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11720                          DAG.getConstant(0, dl, PtrVT));
11721     }
11722     return SDValue();
11723   }
11724
11725   // If this is a 256-bit vector result, first extract the 128-bit vector and
11726   // then extract the element from the 128-bit vector.
11727   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11728
11729     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11730     // Get the 128-bit vector.
11731     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11732     MVT EltVT = VecVT.getVectorElementType();
11733
11734     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11735     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11736
11737     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11738     // this can be done with a mask.
11739     IdxVal &= ElemsPerChunk - 1;
11740     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11741                        DAG.getConstant(IdxVal, dl, MVT::i32));
11742   }
11743
11744   assert(VecVT.is128BitVector() && "Unexpected vector length");
11745
11746   if (Subtarget->hasSSE41())
11747     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11748       return Res;
11749
11750   MVT VT = Op.getSimpleValueType();
11751   // TODO: handle v16i8.
11752   if (VT.getSizeInBits() == 16) {
11753     SDValue Vec = Op.getOperand(0);
11754     if (isNullConstant(Op.getOperand(1)))
11755       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11756                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11757                                      DAG.getBitcast(MVT::v4i32, Vec),
11758                                      Op.getOperand(1)));
11759     // Transform it so it match pextrw which produces a 32-bit result.
11760     MVT EltVT = MVT::i32;
11761     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11762                                   Op.getOperand(0), Op.getOperand(1));
11763     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11764                                   DAG.getValueType(VT));
11765     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11766   }
11767
11768   if (VT.getSizeInBits() == 32) {
11769     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11770     if (Idx == 0)
11771       return Op;
11772
11773     // SHUFPS the element to the lowest double word, then movss.
11774     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11775     MVT VVT = Op.getOperand(0).getSimpleValueType();
11776     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11777                                        DAG.getUNDEF(VVT), Mask);
11778     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11779                        DAG.getIntPtrConstant(0, dl));
11780   }
11781
11782   if (VT.getSizeInBits() == 64) {
11783     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11784     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11785     //        to match extract_elt for f64.
11786     if (isNullConstant(Op.getOperand(1)))
11787       return Op;
11788
11789     // UNPCKHPD the element to the lowest double word, then movsd.
11790     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11791     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11792     int Mask[2] = { 1, -1 };
11793     MVT VVT = Op.getOperand(0).getSimpleValueType();
11794     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11795                                        DAG.getUNDEF(VVT), Mask);
11796     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11797                        DAG.getIntPtrConstant(0, dl));
11798   }
11799
11800   return SDValue();
11801 }
11802
11803 /// Insert one bit to mask vector, like v16i1 or v8i1.
11804 /// AVX-512 feature.
11805 SDValue
11806 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11807   SDLoc dl(Op);
11808   SDValue Vec = Op.getOperand(0);
11809   SDValue Elt = Op.getOperand(1);
11810   SDValue Idx = Op.getOperand(2);
11811   MVT VecVT = Vec.getSimpleValueType();
11812
11813   if (!isa<ConstantSDNode>(Idx)) {
11814     // Non constant index. Extend source and destination,
11815     // insert element and then truncate the result.
11816     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11817     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11818     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11819       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11820       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11821     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11822   }
11823
11824   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11825   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11826   if (IdxVal)
11827     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11828                            DAG.getConstant(IdxVal, dl, MVT::i8));
11829   if (Vec.getOpcode() == ISD::UNDEF)
11830     return EltInVec;
11831   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11832 }
11833
11834 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11835                                                   SelectionDAG &DAG) const {
11836   MVT VT = Op.getSimpleValueType();
11837   MVT EltVT = VT.getVectorElementType();
11838
11839   if (EltVT == MVT::i1)
11840     return InsertBitToMaskVector(Op, DAG);
11841
11842   SDLoc dl(Op);
11843   SDValue N0 = Op.getOperand(0);
11844   SDValue N1 = Op.getOperand(1);
11845   SDValue N2 = Op.getOperand(2);
11846   if (!isa<ConstantSDNode>(N2))
11847     return SDValue();
11848   auto *N2C = cast<ConstantSDNode>(N2);
11849   unsigned IdxVal = N2C->getZExtValue();
11850
11851   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11852   // into that, and then insert the subvector back into the result.
11853   if (VT.is256BitVector() || VT.is512BitVector()) {
11854     // With a 256-bit vector, we can insert into the zero element efficiently
11855     // using a blend if we have AVX or AVX2 and the right data type.
11856     if (VT.is256BitVector() && IdxVal == 0) {
11857       // TODO: It is worthwhile to cast integer to floating point and back
11858       // and incur a domain crossing penalty if that's what we'll end up
11859       // doing anyway after extracting to a 128-bit vector.
11860       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11861           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11862         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11863         N2 = DAG.getIntPtrConstant(1, dl);
11864         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11865       }
11866     }
11867
11868     // Get the desired 128-bit vector chunk.
11869     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11870
11871     // Insert the element into the desired chunk.
11872     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11873     assert(isPowerOf2_32(NumEltsIn128));
11874     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11875     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11876
11877     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11878                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11879
11880     // Insert the changed part back into the bigger vector
11881     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11882   }
11883   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11884
11885   if (Subtarget->hasSSE41()) {
11886     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11887       unsigned Opc;
11888       if (VT == MVT::v8i16) {
11889         Opc = X86ISD::PINSRW;
11890       } else {
11891         assert(VT == MVT::v16i8);
11892         Opc = X86ISD::PINSRB;
11893       }
11894
11895       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11896       // argument.
11897       if (N1.getValueType() != MVT::i32)
11898         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11899       if (N2.getValueType() != MVT::i32)
11900         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11901       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11902     }
11903
11904     if (EltVT == MVT::f32) {
11905       // Bits [7:6] of the constant are the source select. This will always be
11906       //   zero here. The DAG Combiner may combine an extract_elt index into
11907       //   these bits. For example (insert (extract, 3), 2) could be matched by
11908       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11909       // Bits [5:4] of the constant are the destination select. This is the
11910       //   value of the incoming immediate.
11911       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11912       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11913
11914       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11915       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11916         // If this is an insertion of 32-bits into the low 32-bits of
11917         // a vector, we prefer to generate a blend with immediate rather
11918         // than an insertps. Blends are simpler operations in hardware and so
11919         // will always have equal or better performance than insertps.
11920         // But if optimizing for size and there's a load folding opportunity,
11921         // generate insertps because blendps does not have a 32-bit memory
11922         // operand form.
11923         N2 = DAG.getIntPtrConstant(1, dl);
11924         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11925         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11926       }
11927       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11928       // Create this as a scalar to vector..
11929       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11930       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11931     }
11932
11933     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11934       // PINSR* works with constant index.
11935       return Op;
11936     }
11937   }
11938
11939   if (EltVT == MVT::i8)
11940     return SDValue();
11941
11942   if (EltVT.getSizeInBits() == 16) {
11943     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11944     // as its second argument.
11945     if (N1.getValueType() != MVT::i32)
11946       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11947     if (N2.getValueType() != MVT::i32)
11948       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11949     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11950   }
11951   return SDValue();
11952 }
11953
11954 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11955   SDLoc dl(Op);
11956   MVT OpVT = Op.getSimpleValueType();
11957
11958   // If this is a 256-bit vector result, first insert into a 128-bit
11959   // vector and then insert into the 256-bit vector.
11960   if (!OpVT.is128BitVector()) {
11961     // Insert into a 128-bit vector.
11962     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11963     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11964                                  OpVT.getVectorNumElements() / SizeFactor);
11965
11966     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11967
11968     // Insert the 128-bit vector.
11969     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11970   }
11971
11972   if (OpVT == MVT::v1i64 &&
11973       Op.getOperand(0).getValueType() == MVT::i64)
11974     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11975
11976   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11977   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11978   return DAG.getBitcast(
11979       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11980 }
11981
11982 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11983 // a simple subregister reference or explicit instructions to grab
11984 // upper bits of a vector.
11985 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11986                                       SelectionDAG &DAG) {
11987   SDLoc dl(Op);
11988   SDValue In =  Op.getOperand(0);
11989   SDValue Idx = Op.getOperand(1);
11990   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11991   MVT ResVT   = Op.getSimpleValueType();
11992   MVT InVT    = In.getSimpleValueType();
11993
11994   if (Subtarget->hasFp256()) {
11995     if (ResVT.is128BitVector() &&
11996         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11997         isa<ConstantSDNode>(Idx)) {
11998       return Extract128BitVector(In, IdxVal, DAG, dl);
11999     }
12000     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12001         isa<ConstantSDNode>(Idx)) {
12002       return Extract256BitVector(In, IdxVal, DAG, dl);
12003     }
12004   }
12005   return SDValue();
12006 }
12007
12008 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
12009 // simple superregister reference or explicit instructions to insert
12010 // the upper bits of a vector.
12011 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12012                                      SelectionDAG &DAG) {
12013   if (!Subtarget->hasAVX())
12014     return SDValue();
12015
12016   SDLoc dl(Op);
12017   SDValue Vec = Op.getOperand(0);
12018   SDValue SubVec = Op.getOperand(1);
12019   SDValue Idx = Op.getOperand(2);
12020
12021   if (!isa<ConstantSDNode>(Idx))
12022     return SDValue();
12023
12024   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12025   MVT OpVT = Op.getSimpleValueType();
12026   MVT SubVecVT = SubVec.getSimpleValueType();
12027
12028   // Fold two 16-byte subvector loads into one 32-byte load:
12029   // (insert_subvector (insert_subvector undef, (load addr), 0),
12030   //                   (load addr + 16), Elts/2)
12031   // --> load32 addr
12032   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
12033       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
12034       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
12035     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
12036     if (Idx2 && Idx2->getZExtValue() == 0) {
12037       SDValue SubVec2 = Vec.getOperand(1);
12038       // If needed, look through a bitcast to get to the load.
12039       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
12040         SubVec2 = SubVec2.getOperand(0);
12041
12042       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
12043         bool Fast;
12044         unsigned Alignment = FirstLd->getAlignment();
12045         unsigned AS = FirstLd->getAddressSpace();
12046         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
12047         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
12048                                     OpVT, AS, Alignment, &Fast) && Fast) {
12049           SDValue Ops[] = { SubVec2, SubVec };
12050           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
12051             return Ld;
12052         }
12053       }
12054     }
12055   }
12056
12057   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
12058       SubVecVT.is128BitVector())
12059     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12060
12061   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
12062     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12063
12064   if (OpVT.getVectorElementType() == MVT::i1)
12065     return Insert1BitVector(Op, DAG);
12066
12067   return SDValue();
12068 }
12069
12070 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12071 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12072 // one of the above mentioned nodes. It has to be wrapped because otherwise
12073 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12074 // be used to form addressing mode. These wrapped nodes will be selected
12075 // into MOV32ri.
12076 SDValue
12077 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12078   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12079
12080   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12081   // global base reg.
12082   unsigned char OpFlag = 0;
12083   unsigned WrapperKind = X86ISD::Wrapper;
12084   CodeModel::Model M = DAG.getTarget().getCodeModel();
12085
12086   if (Subtarget->isPICStyleRIPRel() &&
12087       (M == CodeModel::Small || M == CodeModel::Kernel))
12088     WrapperKind = X86ISD::WrapperRIP;
12089   else if (Subtarget->isPICStyleGOT())
12090     OpFlag = X86II::MO_GOTOFF;
12091   else if (Subtarget->isPICStyleStubPIC())
12092     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12093
12094   auto PtrVT = getPointerTy(DAG.getDataLayout());
12095   SDValue Result = DAG.getTargetConstantPool(
12096       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
12097   SDLoc DL(CP);
12098   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12099   // With PIC, the address is actually $g + Offset.
12100   if (OpFlag) {
12101     Result =
12102         DAG.getNode(ISD::ADD, DL, PtrVT,
12103                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12104   }
12105
12106   return Result;
12107 }
12108
12109 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12110   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12111
12112   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12113   // global base reg.
12114   unsigned char OpFlag = 0;
12115   unsigned WrapperKind = X86ISD::Wrapper;
12116   CodeModel::Model M = DAG.getTarget().getCodeModel();
12117
12118   if (Subtarget->isPICStyleRIPRel() &&
12119       (M == CodeModel::Small || M == CodeModel::Kernel))
12120     WrapperKind = X86ISD::WrapperRIP;
12121   else if (Subtarget->isPICStyleGOT())
12122     OpFlag = X86II::MO_GOTOFF;
12123   else if (Subtarget->isPICStyleStubPIC())
12124     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12125
12126   auto PtrVT = getPointerTy(DAG.getDataLayout());
12127   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12128   SDLoc DL(JT);
12129   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12130
12131   // With PIC, the address is actually $g + Offset.
12132   if (OpFlag)
12133     Result =
12134         DAG.getNode(ISD::ADD, DL, PtrVT,
12135                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12136
12137   return Result;
12138 }
12139
12140 SDValue
12141 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12142   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12143
12144   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12145   // global base reg.
12146   unsigned char OpFlag = 0;
12147   unsigned WrapperKind = X86ISD::Wrapper;
12148   CodeModel::Model M = DAG.getTarget().getCodeModel();
12149
12150   if (Subtarget->isPICStyleRIPRel() &&
12151       (M == CodeModel::Small || M == CodeModel::Kernel)) {
12152     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12153       OpFlag = X86II::MO_GOTPCREL;
12154     WrapperKind = X86ISD::WrapperRIP;
12155   } else if (Subtarget->isPICStyleGOT()) {
12156     OpFlag = X86II::MO_GOT;
12157   } else if (Subtarget->isPICStyleStubPIC()) {
12158     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12159   } else if (Subtarget->isPICStyleStubNoDynamic()) {
12160     OpFlag = X86II::MO_DARWIN_NONLAZY;
12161   }
12162
12163   auto PtrVT = getPointerTy(DAG.getDataLayout());
12164   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12165
12166   SDLoc DL(Op);
12167   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12168
12169   // With PIC, the address is actually $g + Offset.
12170   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12171       !Subtarget->is64Bit()) {
12172     Result =
12173         DAG.getNode(ISD::ADD, DL, PtrVT,
12174                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12175   }
12176
12177   // For symbols that require a load from a stub to get the address, emit the
12178   // load.
12179   if (isGlobalStubReference(OpFlag))
12180     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12181                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12182                          false, false, false, 0);
12183
12184   return Result;
12185 }
12186
12187 SDValue
12188 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12189   // Create the TargetBlockAddressAddress node.
12190   unsigned char OpFlags =
12191     Subtarget->ClassifyBlockAddressReference();
12192   CodeModel::Model M = DAG.getTarget().getCodeModel();
12193   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12194   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12195   SDLoc dl(Op);
12196   auto PtrVT = getPointerTy(DAG.getDataLayout());
12197   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12198
12199   if (Subtarget->isPICStyleRIPRel() &&
12200       (M == CodeModel::Small || M == CodeModel::Kernel))
12201     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12202   else
12203     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12204
12205   // With PIC, the address is actually $g + Offset.
12206   if (isGlobalRelativeToPICBase(OpFlags)) {
12207     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12208                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12209   }
12210
12211   return Result;
12212 }
12213
12214 SDValue
12215 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12216                                       int64_t Offset, SelectionDAG &DAG) const {
12217   // Create the TargetGlobalAddress node, folding in the constant
12218   // offset if it is legal.
12219   unsigned char OpFlags =
12220       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12221   CodeModel::Model M = DAG.getTarget().getCodeModel();
12222   auto PtrVT = getPointerTy(DAG.getDataLayout());
12223   SDValue Result;
12224   if (OpFlags == X86II::MO_NO_FLAG &&
12225       X86::isOffsetSuitableForCodeModel(Offset, M)) {
12226     // A direct static reference to a global.
12227     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12228     Offset = 0;
12229   } else {
12230     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12231   }
12232
12233   if (Subtarget->isPICStyleRIPRel() &&
12234       (M == CodeModel::Small || M == CodeModel::Kernel))
12235     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12236   else
12237     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12238
12239   // With PIC, the address is actually $g + Offset.
12240   if (isGlobalRelativeToPICBase(OpFlags)) {
12241     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12242                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12243   }
12244
12245   // For globals that require a load from a stub to get the address, emit the
12246   // load.
12247   if (isGlobalStubReference(OpFlags))
12248     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12249                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12250                          false, false, false, 0);
12251
12252   // If there was a non-zero offset that we didn't fold, create an explicit
12253   // addition for it.
12254   if (Offset != 0)
12255     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12256                          DAG.getConstant(Offset, dl, PtrVT));
12257
12258   return Result;
12259 }
12260
12261 SDValue
12262 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12263   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12264   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12265   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12266 }
12267
12268 static SDValue
12269 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12270            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12271            unsigned char OperandFlags, bool LocalDynamic = false) {
12272   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12273   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12274   SDLoc dl(GA);
12275   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12276                                            GA->getValueType(0),
12277                                            GA->getOffset(),
12278                                            OperandFlags);
12279
12280   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12281                                            : X86ISD::TLSADDR;
12282
12283   if (InFlag) {
12284     SDValue Ops[] = { Chain,  TGA, *InFlag };
12285     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12286   } else {
12287     SDValue Ops[]  = { Chain, TGA };
12288     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12289   }
12290
12291   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12292   MFI->setAdjustsStack(true);
12293   MFI->setHasCalls(true);
12294
12295   SDValue Flag = Chain.getValue(1);
12296   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12297 }
12298
12299 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12300 static SDValue
12301 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12302                                 const EVT PtrVT) {
12303   SDValue InFlag;
12304   SDLoc dl(GA);  // ? function entry point might be better
12305   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12306                                    DAG.getNode(X86ISD::GlobalBaseReg,
12307                                                SDLoc(), PtrVT), InFlag);
12308   InFlag = Chain.getValue(1);
12309
12310   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12311 }
12312
12313 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12314 static SDValue
12315 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12316                                 const EVT PtrVT) {
12317   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12318                     X86::RAX, X86II::MO_TLSGD);
12319 }
12320
12321 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12322                                            SelectionDAG &DAG,
12323                                            const EVT PtrVT,
12324                                            bool is64Bit) {
12325   SDLoc dl(GA);
12326
12327   // Get the start address of the TLS block for this module.
12328   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12329       .getInfo<X86MachineFunctionInfo>();
12330   MFI->incNumLocalDynamicTLSAccesses();
12331
12332   SDValue Base;
12333   if (is64Bit) {
12334     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12335                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12336   } else {
12337     SDValue InFlag;
12338     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12339         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12340     InFlag = Chain.getValue(1);
12341     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12342                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12343   }
12344
12345   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12346   // of Base.
12347
12348   // Build x@dtpoff.
12349   unsigned char OperandFlags = X86II::MO_DTPOFF;
12350   unsigned WrapperKind = X86ISD::Wrapper;
12351   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12352                                            GA->getValueType(0),
12353                                            GA->getOffset(), OperandFlags);
12354   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12355
12356   // Add x@dtpoff with the base.
12357   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12358 }
12359
12360 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12361 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12362                                    const EVT PtrVT, TLSModel::Model model,
12363                                    bool is64Bit, bool isPIC) {
12364   SDLoc dl(GA);
12365
12366   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12367   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12368                                                          is64Bit ? 257 : 256));
12369
12370   SDValue ThreadPointer =
12371       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12372                   MachinePointerInfo(Ptr), false, false, false, 0);
12373
12374   unsigned char OperandFlags = 0;
12375   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12376   // initialexec.
12377   unsigned WrapperKind = X86ISD::Wrapper;
12378   if (model == TLSModel::LocalExec) {
12379     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12380   } else if (model == TLSModel::InitialExec) {
12381     if (is64Bit) {
12382       OperandFlags = X86II::MO_GOTTPOFF;
12383       WrapperKind = X86ISD::WrapperRIP;
12384     } else {
12385       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12386     }
12387   } else {
12388     llvm_unreachable("Unexpected model");
12389   }
12390
12391   // emit "addl x@ntpoff,%eax" (local exec)
12392   // or "addl x@indntpoff,%eax" (initial exec)
12393   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12394   SDValue TGA =
12395       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12396                                  GA->getOffset(), OperandFlags);
12397   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12398
12399   if (model == TLSModel::InitialExec) {
12400     if (isPIC && !is64Bit) {
12401       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12402                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12403                            Offset);
12404     }
12405
12406     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12407                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12408                          false, false, false, 0);
12409   }
12410
12411   // The address of the thread local variable is the add of the thread
12412   // pointer with the offset of the variable.
12413   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12414 }
12415
12416 SDValue
12417 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12418
12419   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12420
12421   // Cygwin uses emutls.
12422   // FIXME: It may be EmulatedTLS-generic also for X86-Android.
12423   if (Subtarget->isTargetWindowsCygwin())
12424     return LowerToTLSEmulatedModel(GA, DAG);
12425
12426   const GlobalValue *GV = GA->getGlobal();
12427   auto PtrVT = getPointerTy(DAG.getDataLayout());
12428
12429   if (Subtarget->isTargetELF()) {
12430     if (DAG.getTarget().Options.EmulatedTLS)
12431       return LowerToTLSEmulatedModel(GA, DAG);
12432     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12433     switch (model) {
12434       case TLSModel::GeneralDynamic:
12435         if (Subtarget->is64Bit())
12436           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12437         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12438       case TLSModel::LocalDynamic:
12439         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12440                                            Subtarget->is64Bit());
12441       case TLSModel::InitialExec:
12442       case TLSModel::LocalExec:
12443         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12444                                    DAG.getTarget().getRelocationModel() ==
12445                                        Reloc::PIC_);
12446     }
12447     llvm_unreachable("Unknown TLS model.");
12448   }
12449
12450   if (Subtarget->isTargetDarwin()) {
12451     // Darwin only has one model of TLS.  Lower to that.
12452     unsigned char OpFlag = 0;
12453     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12454                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12455
12456     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12457     // global base reg.
12458     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12459                  !Subtarget->is64Bit();
12460     if (PIC32)
12461       OpFlag = X86II::MO_TLVP_PIC_BASE;
12462     else
12463       OpFlag = X86II::MO_TLVP;
12464     SDLoc DL(Op);
12465     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12466                                                 GA->getValueType(0),
12467                                                 GA->getOffset(), OpFlag);
12468     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12469
12470     // With PIC32, the address is actually $g + Offset.
12471     if (PIC32)
12472       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12473                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12474                            Offset);
12475
12476     // Lowering the machine isd will make sure everything is in the right
12477     // location.
12478     SDValue Chain = DAG.getEntryNode();
12479     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12480     SDValue Args[] = { Chain, Offset };
12481     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12482
12483     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12484     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12485     MFI->setAdjustsStack(true);
12486
12487     // And our return value (tls address) is in the standard call return value
12488     // location.
12489     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12490     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12491   }
12492
12493   if (Subtarget->isTargetKnownWindowsMSVC() ||
12494       Subtarget->isTargetWindowsGNU()) {
12495     // Just use the implicit TLS architecture
12496     // Need to generate someting similar to:
12497     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12498     //                                  ; from TEB
12499     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12500     //   mov     rcx, qword [rdx+rcx*8]
12501     //   mov     eax, .tls$:tlsvar
12502     //   [rax+rcx] contains the address
12503     // Windows 64bit: gs:0x58
12504     // Windows 32bit: fs:__tls_array
12505
12506     SDLoc dl(GA);
12507     SDValue Chain = DAG.getEntryNode();
12508
12509     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12510     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12511     // use its literal value of 0x2C.
12512     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12513                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12514                                                              256)
12515                                         : Type::getInt32PtrTy(*DAG.getContext(),
12516                                                               257));
12517
12518     SDValue TlsArray = Subtarget->is64Bit()
12519                            ? DAG.getIntPtrConstant(0x58, dl)
12520                            : (Subtarget->isTargetWindowsGNU()
12521                                   ? DAG.getIntPtrConstant(0x2C, dl)
12522                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12523
12524     SDValue ThreadPointer =
12525         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12526                     false, false, 0);
12527
12528     SDValue res;
12529     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12530       res = ThreadPointer;
12531     } else {
12532       // Load the _tls_index variable
12533       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12534       if (Subtarget->is64Bit())
12535         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12536                              MachinePointerInfo(), MVT::i32, false, false,
12537                              false, 0);
12538       else
12539         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12540                           false, false, 0);
12541
12542       auto &DL = DAG.getDataLayout();
12543       SDValue Scale =
12544           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12545       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12546
12547       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12548     }
12549
12550     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12551                       false, 0);
12552
12553     // Get the offset of start of .tls section
12554     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12555                                              GA->getValueType(0),
12556                                              GA->getOffset(), X86II::MO_SECREL);
12557     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12558
12559     // The address of the thread local variable is the add of the thread
12560     // pointer with the offset of the variable.
12561     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12562   }
12563
12564   llvm_unreachable("TLS not implemented for this target.");
12565 }
12566
12567 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12568 /// and take a 2 x i32 value to shift plus a shift amount.
12569 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12570   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12571   MVT VT = Op.getSimpleValueType();
12572   unsigned VTBits = VT.getSizeInBits();
12573   SDLoc dl(Op);
12574   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12575   SDValue ShOpLo = Op.getOperand(0);
12576   SDValue ShOpHi = Op.getOperand(1);
12577   SDValue ShAmt  = Op.getOperand(2);
12578   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12579   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12580   // during isel.
12581   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12582                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12583   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12584                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12585                        : DAG.getConstant(0, dl, VT);
12586
12587   SDValue Tmp2, Tmp3;
12588   if (Op.getOpcode() == ISD::SHL_PARTS) {
12589     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12590     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12591   } else {
12592     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12593     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12594   }
12595
12596   // If the shift amount is larger or equal than the width of a part we can't
12597   // rely on the results of shld/shrd. Insert a test and select the appropriate
12598   // values for large shift amounts.
12599   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12600                                 DAG.getConstant(VTBits, dl, MVT::i8));
12601   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12602                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12603
12604   SDValue Hi, Lo;
12605   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12606   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12607   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12608
12609   if (Op.getOpcode() == ISD::SHL_PARTS) {
12610     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12611     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12612   } else {
12613     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12614     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12615   }
12616
12617   SDValue Ops[2] = { Lo, Hi };
12618   return DAG.getMergeValues(Ops, dl);
12619 }
12620
12621 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12622                                            SelectionDAG &DAG) const {
12623   SDValue Src = Op.getOperand(0);
12624   MVT SrcVT = Src.getSimpleValueType();
12625   MVT VT = Op.getSimpleValueType();
12626   SDLoc dl(Op);
12627
12628   if (SrcVT.isVector()) {
12629     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12630       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12631                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12632                          DAG.getUNDEF(SrcVT)));
12633     }
12634     if (SrcVT.getVectorElementType() == MVT::i1) {
12635       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12636       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12637                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12638     }
12639     return SDValue();
12640   }
12641
12642   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12643          "Unknown SINT_TO_FP to lower!");
12644
12645   // These are really Legal; return the operand so the caller accepts it as
12646   // Legal.
12647   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12648     return Op;
12649   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12650       Subtarget->is64Bit()) {
12651     return Op;
12652   }
12653
12654   unsigned Size = SrcVT.getSizeInBits()/8;
12655   MachineFunction &MF = DAG.getMachineFunction();
12656   auto PtrVT = getPointerTy(MF.getDataLayout());
12657   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12658   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12659   SDValue Chain = DAG.getStore(
12660       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12661       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12662       false, 0);
12663   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12664 }
12665
12666 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12667                                      SDValue StackSlot,
12668                                      SelectionDAG &DAG) const {
12669   // Build the FILD
12670   SDLoc DL(Op);
12671   SDVTList Tys;
12672   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12673   if (useSSE)
12674     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12675   else
12676     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12677
12678   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12679
12680   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12681   MachineMemOperand *MMO;
12682   if (FI) {
12683     int SSFI = FI->getIndex();
12684     MMO = DAG.getMachineFunction().getMachineMemOperand(
12685         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12686         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12687   } else {
12688     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12689     StackSlot = StackSlot.getOperand(1);
12690   }
12691   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12692   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12693                                            X86ISD::FILD, DL,
12694                                            Tys, Ops, SrcVT, MMO);
12695
12696   if (useSSE) {
12697     Chain = Result.getValue(1);
12698     SDValue InFlag = Result.getValue(2);
12699
12700     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12701     // shouldn't be necessary except that RFP cannot be live across
12702     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12703     MachineFunction &MF = DAG.getMachineFunction();
12704     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12705     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12706     auto PtrVT = getPointerTy(MF.getDataLayout());
12707     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12708     Tys = DAG.getVTList(MVT::Other);
12709     SDValue Ops[] = {
12710       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12711     };
12712     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12713         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12714         MachineMemOperand::MOStore, SSFISize, SSFISize);
12715
12716     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12717                                     Ops, Op.getValueType(), MMO);
12718     Result = DAG.getLoad(
12719         Op.getValueType(), DL, Chain, StackSlot,
12720         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12721         false, false, false, 0);
12722   }
12723
12724   return Result;
12725 }
12726
12727 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12728 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12729                                                SelectionDAG &DAG) const {
12730   // This algorithm is not obvious. Here it is what we're trying to output:
12731   /*
12732      movq       %rax,  %xmm0
12733      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12734      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12735      #ifdef __SSE3__
12736        haddpd   %xmm0, %xmm0
12737      #else
12738        pshufd   $0x4e, %xmm0, %xmm1
12739        addpd    %xmm1, %xmm0
12740      #endif
12741   */
12742
12743   SDLoc dl(Op);
12744   LLVMContext *Context = DAG.getContext();
12745
12746   // Build some magic constants.
12747   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12748   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12749   auto PtrVT = getPointerTy(DAG.getDataLayout());
12750   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12751
12752   SmallVector<Constant*,2> CV1;
12753   CV1.push_back(
12754     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12755                                       APInt(64, 0x4330000000000000ULL))));
12756   CV1.push_back(
12757     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12758                                       APInt(64, 0x4530000000000000ULL))));
12759   Constant *C1 = ConstantVector::get(CV1);
12760   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12761
12762   // Load the 64-bit value into an XMM register.
12763   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12764                             Op.getOperand(0));
12765   SDValue CLod0 =
12766       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12767                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12768                   false, false, false, 16);
12769   SDValue Unpck1 =
12770       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12771
12772   SDValue CLod1 =
12773       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12774                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12775                   false, false, false, 16);
12776   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12777   // TODO: Are there any fast-math-flags to propagate here?
12778   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12779   SDValue Result;
12780
12781   if (Subtarget->hasSSE3()) {
12782     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12783     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12784   } else {
12785     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12786     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12787                                            S2F, 0x4E, DAG);
12788     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12789                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12790   }
12791
12792   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12793                      DAG.getIntPtrConstant(0, dl));
12794 }
12795
12796 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12797 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12798                                                SelectionDAG &DAG) const {
12799   SDLoc dl(Op);
12800   // FP constant to bias correct the final result.
12801   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12802                                    MVT::f64);
12803
12804   // Load the 32-bit value into an XMM register.
12805   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12806                              Op.getOperand(0));
12807
12808   // Zero out the upper parts of the register.
12809   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12810
12811   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12812                      DAG.getBitcast(MVT::v2f64, Load),
12813                      DAG.getIntPtrConstant(0, dl));
12814
12815   // Or the load with the bias.
12816   SDValue Or = DAG.getNode(
12817       ISD::OR, dl, MVT::v2i64,
12818       DAG.getBitcast(MVT::v2i64,
12819                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12820       DAG.getBitcast(MVT::v2i64,
12821                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12822   Or =
12823       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12824                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12825
12826   // Subtract the bias.
12827   // TODO: Are there any fast-math-flags to propagate here?
12828   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12829
12830   // Handle final rounding.
12831   MVT DestVT = Op.getSimpleValueType();
12832
12833   if (DestVT.bitsLT(MVT::f64))
12834     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12835                        DAG.getIntPtrConstant(0, dl));
12836   if (DestVT.bitsGT(MVT::f64))
12837     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12838
12839   // Handle final rounding.
12840   return Sub;
12841 }
12842
12843 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12844                                      const X86Subtarget &Subtarget) {
12845   // The algorithm is the following:
12846   // #ifdef __SSE4_1__
12847   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12848   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12849   //                                 (uint4) 0x53000000, 0xaa);
12850   // #else
12851   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12852   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12853   // #endif
12854   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12855   //     return (float4) lo + fhi;
12856
12857   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12858   // reassociate the two FADDs, and if we do that, the algorithm fails
12859   // spectacularly (PR24512).
12860   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12861   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12862   // there's also the MachineCombiner reassociations happening on Machine IR.
12863   if (DAG.getTarget().Options.UnsafeFPMath)
12864     return SDValue();
12865
12866   SDLoc DL(Op);
12867   SDValue V = Op->getOperand(0);
12868   MVT VecIntVT = V.getSimpleValueType();
12869   bool Is128 = VecIntVT == MVT::v4i32;
12870   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12871   // If we convert to something else than the supported type, e.g., to v4f64,
12872   // abort early.
12873   if (VecFloatVT != Op->getSimpleValueType(0))
12874     return SDValue();
12875
12876   unsigned NumElts = VecIntVT.getVectorNumElements();
12877   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12878          "Unsupported custom type");
12879   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12880
12881   // In the #idef/#else code, we have in common:
12882   // - The vector of constants:
12883   // -- 0x4b000000
12884   // -- 0x53000000
12885   // - A shift:
12886   // -- v >> 16
12887
12888   // Create the splat vector for 0x4b000000.
12889   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12890   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12891                            CstLow, CstLow, CstLow, CstLow};
12892   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12893                                   makeArrayRef(&CstLowArray[0], NumElts));
12894   // Create the splat vector for 0x53000000.
12895   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12896   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12897                             CstHigh, CstHigh, CstHigh, CstHigh};
12898   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12899                                    makeArrayRef(&CstHighArray[0], NumElts));
12900
12901   // Create the right shift.
12902   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12903   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12904                              CstShift, CstShift, CstShift, CstShift};
12905   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12906                                     makeArrayRef(&CstShiftArray[0], NumElts));
12907   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12908
12909   SDValue Low, High;
12910   if (Subtarget.hasSSE41()) {
12911     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12912     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12913     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12914     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12915     // Low will be bitcasted right away, so do not bother bitcasting back to its
12916     // original type.
12917     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12918                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12919     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12920     //                                 (uint4) 0x53000000, 0xaa);
12921     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12922     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12923     // High will be bitcasted right away, so do not bother bitcasting back to
12924     // its original type.
12925     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12926                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12927   } else {
12928     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12929     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12930                                      CstMask, CstMask, CstMask);
12931     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12932     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12933     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12934
12935     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12936     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12937   }
12938
12939   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12940   SDValue CstFAdd = DAG.getConstantFP(
12941       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12942   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12943                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12944   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12945                                    makeArrayRef(&CstFAddArray[0], NumElts));
12946
12947   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12948   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12949   // TODO: Are there any fast-math-flags to propagate here?
12950   SDValue FHigh =
12951       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12952   //     return (float4) lo + fhi;
12953   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12954   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12955 }
12956
12957 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12958                                                SelectionDAG &DAG) const {
12959   SDValue N0 = Op.getOperand(0);
12960   MVT SVT = N0.getSimpleValueType();
12961   SDLoc dl(Op);
12962
12963   switch (SVT.SimpleTy) {
12964   default:
12965     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12966   case MVT::v4i8:
12967   case MVT::v4i16:
12968   case MVT::v8i8:
12969   case MVT::v8i16: {
12970     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12971     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12972                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12973   }
12974   case MVT::v4i32:
12975   case MVT::v8i32:
12976     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12977   case MVT::v16i8:
12978   case MVT::v16i16:
12979     assert(Subtarget->hasAVX512());
12980     return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12981                        DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12982   }
12983 }
12984
12985 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12986                                            SelectionDAG &DAG) const {
12987   SDValue N0 = Op.getOperand(0);
12988   SDLoc dl(Op);
12989   auto PtrVT = getPointerTy(DAG.getDataLayout());
12990
12991   if (Op.getSimpleValueType().isVector())
12992     return lowerUINT_TO_FP_vec(Op, DAG);
12993
12994   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12995   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12996   // the optimization here.
12997   if (DAG.SignBitIsZero(N0))
12998     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12999
13000   MVT SrcVT = N0.getSimpleValueType();
13001   MVT DstVT = Op.getSimpleValueType();
13002
13003   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
13004       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
13005     // Conversions from unsigned i32 to f32/f64 are legal,
13006     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
13007     return Op;
13008   }
13009
13010   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13011     return LowerUINT_TO_FP_i64(Op, DAG);
13012   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13013     return LowerUINT_TO_FP_i32(Op, DAG);
13014   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13015     return SDValue();
13016
13017   // Make a 64-bit buffer, and use it to build an FILD.
13018   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13019   if (SrcVT == MVT::i32) {
13020     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
13021     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
13022     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13023                                   StackSlot, MachinePointerInfo(),
13024                                   false, false, 0);
13025     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
13026                                   OffsetSlot, MachinePointerInfo(),
13027                                   false, false, 0);
13028     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13029     return Fild;
13030   }
13031
13032   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13033   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13034                                StackSlot, MachinePointerInfo(),
13035                                false, false, 0);
13036   // For i64 source, we need to add the appropriate power of 2 if the input
13037   // was negative.  This is the same as the optimization in
13038   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13039   // we must be careful to do the computation in x87 extended precision, not
13040   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13041   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13042   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13043       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13044       MachineMemOperand::MOLoad, 8, 8);
13045
13046   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13047   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13048   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13049                                          MVT::i64, MMO);
13050
13051   APInt FF(32, 0x5F800000ULL);
13052
13053   // Check whether the sign bit is set.
13054   SDValue SignSet = DAG.getSetCC(
13055       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
13056       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
13057
13058   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13059   SDValue FudgePtr = DAG.getConstantPool(
13060       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
13061
13062   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13063   SDValue Zero = DAG.getIntPtrConstant(0, dl);
13064   SDValue Four = DAG.getIntPtrConstant(4, dl);
13065   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13066                                Zero, Four);
13067   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
13068
13069   // Load the value out, extending it from f32 to f80.
13070   // FIXME: Avoid the extend by constructing the right constant pool?
13071   SDValue Fudge = DAG.getExtLoad(
13072       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
13073       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
13074       false, false, false, 4);
13075   // Extend everything to 80 bits to force it to be done on x87.
13076   // TODO: Are there any fast-math-flags to propagate here?
13077   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13078   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
13079                      DAG.getIntPtrConstant(0, dl));
13080 }
13081
13082 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
13083 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
13084 // just return an <SDValue(), SDValue()> pair.
13085 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
13086 // to i16, i32 or i64, and we lower it to a legal sequence.
13087 // If lowered to the final integer result we return a <result, SDValue()> pair.
13088 // Otherwise we lower it to a sequence ending with a FIST, return a
13089 // <FIST, StackSlot> pair, and the caller is responsible for loading
13090 // the final integer result from StackSlot.
13091 std::pair<SDValue,SDValue>
13092 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13093                                    bool IsSigned, bool IsReplace) const {
13094   SDLoc DL(Op);
13095
13096   EVT DstTy = Op.getValueType();
13097   EVT TheVT = Op.getOperand(0).getValueType();
13098   auto PtrVT = getPointerTy(DAG.getDataLayout());
13099
13100   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
13101     // f16 must be promoted before using the lowering in this routine.
13102     // fp128 does not use this lowering.
13103     return std::make_pair(SDValue(), SDValue());
13104   }
13105
13106   // If using FIST to compute an unsigned i64, we'll need some fixup
13107   // to handle values above the maximum signed i64.  A FIST is always
13108   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13109   bool UnsignedFixup = !IsSigned &&
13110                        DstTy == MVT::i64 &&
13111                        (!Subtarget->is64Bit() ||
13112                         !isScalarFPTypeInSSEReg(TheVT));
13113
13114   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
13115     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13116     // The low 32 bits of the fist result will have the correct uint32 result.
13117     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13118     DstTy = MVT::i64;
13119   }
13120
13121   assert(DstTy.getSimpleVT() <= MVT::i64 &&
13122          DstTy.getSimpleVT() >= MVT::i16 &&
13123          "Unknown FP_TO_INT to lower!");
13124
13125   // These are really Legal.
13126   if (DstTy == MVT::i32 &&
13127       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13128     return std::make_pair(SDValue(), SDValue());
13129   if (Subtarget->is64Bit() &&
13130       DstTy == MVT::i64 &&
13131       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13132     return std::make_pair(SDValue(), SDValue());
13133
13134   // We lower FP->int64 into FISTP64 followed by a load from a temporary
13135   // stack slot.
13136   MachineFunction &MF = DAG.getMachineFunction();
13137   unsigned MemSize = DstTy.getSizeInBits()/8;
13138   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13139   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13140
13141   unsigned Opc;
13142   switch (DstTy.getSimpleVT().SimpleTy) {
13143   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13144   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13145   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13146   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13147   }
13148
13149   SDValue Chain = DAG.getEntryNode();
13150   SDValue Value = Op.getOperand(0);
13151   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13152
13153   if (UnsignedFixup) {
13154     //
13155     // Conversion to unsigned i64 is implemented with a select,
13156     // depending on whether the source value fits in the range
13157     // of a signed i64.  Let Thresh be the FP equivalent of
13158     // 0x8000000000000000ULL.
13159     //
13160     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13161     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
13162     //  Fist-to-mem64 FistSrc
13163     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13164     //  to XOR'ing the high 32 bits with Adjust.
13165     //
13166     // Being a power of 2, Thresh is exactly representable in all FP formats.
13167     // For X87 we'd like to use the smallest FP type for this constant, but
13168     // for DAG type consistency we have to match the FP operand type.
13169
13170     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13171     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13172     bool LosesInfo = false;
13173     if (TheVT == MVT::f64)
13174       // The rounding mode is irrelevant as the conversion should be exact.
13175       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13176                               &LosesInfo);
13177     else if (TheVT == MVT::f80)
13178       Status = Thresh.convert(APFloat::x87DoubleExtended,
13179                               APFloat::rmNearestTiesToEven, &LosesInfo);
13180
13181     assert(Status == APFloat::opOK && !LosesInfo &&
13182            "FP conversion should have been exact");
13183
13184     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13185
13186     SDValue Cmp = DAG.getSetCC(DL,
13187                                getSetCCResultType(DAG.getDataLayout(),
13188                                                   *DAG.getContext(), TheVT),
13189                                Value, ThreshVal, ISD::SETLT);
13190     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13191                            DAG.getConstant(0, DL, MVT::i32),
13192                            DAG.getConstant(0x80000000, DL, MVT::i32));
13193     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13194     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13195                                               *DAG.getContext(), TheVT),
13196                        Value, ThreshVal, ISD::SETLT);
13197     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13198   }
13199
13200   // FIXME This causes a redundant load/store if the SSE-class value is already
13201   // in memory, such as if it is on the callstack.
13202   if (isScalarFPTypeInSSEReg(TheVT)) {
13203     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13204     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13205                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
13206                          false, 0);
13207     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13208     SDValue Ops[] = {
13209       Chain, StackSlot, DAG.getValueType(TheVT)
13210     };
13211
13212     MachineMemOperand *MMO =
13213         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13214                                 MachineMemOperand::MOLoad, MemSize, MemSize);
13215     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13216     Chain = Value.getValue(1);
13217     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13218     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13219   }
13220
13221   MachineMemOperand *MMO =
13222       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13223                               MachineMemOperand::MOStore, MemSize, MemSize);
13224
13225   if (UnsignedFixup) {
13226
13227     // Insert the FIST, load its result as two i32's,
13228     // and XOR the high i32 with Adjust.
13229
13230     SDValue FistOps[] = { Chain, Value, StackSlot };
13231     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13232                                            FistOps, DstTy, MMO);
13233
13234     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13235                                 MachinePointerInfo(),
13236                                 false, false, false, 0);
13237     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13238                                    DAG.getConstant(4, DL, PtrVT));
13239
13240     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13241                                  MachinePointerInfo(),
13242                                  false, false, false, 0);
13243     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13244
13245     if (Subtarget->is64Bit()) {
13246       // Join High32 and Low32 into a 64-bit result.
13247       // (High32 << 32) | Low32
13248       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13249       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13250       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13251                            DAG.getConstant(32, DL, MVT::i8));
13252       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13253       return std::make_pair(Result, SDValue());
13254     }
13255
13256     SDValue ResultOps[] = { Low32, High32 };
13257
13258     SDValue pair = IsReplace
13259       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13260       : DAG.getMergeValues(ResultOps, DL);
13261     return std::make_pair(pair, SDValue());
13262   } else {
13263     // Build the FP_TO_INT*_IN_MEM
13264     SDValue Ops[] = { Chain, Value, StackSlot };
13265     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13266                                            Ops, DstTy, MMO);
13267     return std::make_pair(FIST, StackSlot);
13268   }
13269 }
13270
13271 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13272                               const X86Subtarget *Subtarget) {
13273   MVT VT = Op->getSimpleValueType(0);
13274   SDValue In = Op->getOperand(0);
13275   MVT InVT = In.getSimpleValueType();
13276   SDLoc dl(Op);
13277
13278   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13279     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13280
13281   // Optimize vectors in AVX mode:
13282   //
13283   //   v8i16 -> v8i32
13284   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13285   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13286   //   Concat upper and lower parts.
13287   //
13288   //   v4i32 -> v4i64
13289   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13290   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13291   //   Concat upper and lower parts.
13292   //
13293
13294   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13295       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13296       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13297     return SDValue();
13298
13299   if (Subtarget->hasInt256())
13300     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13301
13302   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13303   SDValue Undef = DAG.getUNDEF(InVT);
13304   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13305   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13306   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13307
13308   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13309                              VT.getVectorNumElements()/2);
13310
13311   OpLo = DAG.getBitcast(HVT, OpLo);
13312   OpHi = DAG.getBitcast(HVT, OpHi);
13313
13314   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13315 }
13316
13317 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13318                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13319   MVT VT = Op->getSimpleValueType(0);
13320   SDValue In = Op->getOperand(0);
13321   MVT InVT = In.getSimpleValueType();
13322   SDLoc DL(Op);
13323   unsigned int NumElts = VT.getVectorNumElements();
13324   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13325     return SDValue();
13326
13327   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13328     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13329
13330   assert(InVT.getVectorElementType() == MVT::i1);
13331   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13332   SDValue One =
13333    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13334   SDValue Zero =
13335    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13336
13337   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13338   if (VT.is512BitVector())
13339     return V;
13340   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13341 }
13342
13343 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13344                                SelectionDAG &DAG) {
13345   if (Subtarget->hasFp256())
13346     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13347       return Res;
13348
13349   return SDValue();
13350 }
13351
13352 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13353                                 SelectionDAG &DAG) {
13354   SDLoc DL(Op);
13355   MVT VT = Op.getSimpleValueType();
13356   SDValue In = Op.getOperand(0);
13357   MVT SVT = In.getSimpleValueType();
13358
13359   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13360     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13361
13362   if (Subtarget->hasFp256())
13363     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13364       return Res;
13365
13366   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13367          VT.getVectorNumElements() != SVT.getVectorNumElements());
13368   return SDValue();
13369 }
13370
13371 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
13372                                   const X86Subtarget *Subtarget) {
13373
13374   SDLoc DL(Op);
13375   MVT VT = Op.getSimpleValueType();
13376   SDValue In = Op.getOperand(0);
13377   MVT InVT = In.getSimpleValueType();
13378
13379   assert(VT.getVectorElementType() == MVT::i1 && "Unexected vector type.");
13380
13381   // Shift LSB to MSB and use VPMOVB2M - SKX.
13382   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
13383   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13384          Subtarget->hasBWI()) ||     // legal, will go to VPMOVB2M, VPMOVW2M
13385       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13386              InVT.getScalarSizeInBits() <= 16 && Subtarget->hasBWI() &&
13387              Subtarget->hasVLX())) { // legal, will go to VPMOVB2M, VPMOVW2M
13388     // Shift packed bytes not supported natively, bitcast to dword
13389     MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
13390     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, ExtVT,
13391                                      DAG.getBitcast(ExtVT, In),
13392                                      DAG.getConstant(ShiftInx, DL, ExtVT));
13393     ShiftNode = DAG.getBitcast(InVT, ShiftNode);
13394     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13395   }
13396   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13397          Subtarget->hasDQI()) ||  // legal, will go to VPMOVD2M, VPMOVQ2M
13398       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13399          InVT.getScalarSizeInBits() >= 32 && Subtarget->hasDQI() &&
13400          Subtarget->hasVLX())) {  // legal, will go to VPMOVD2M, VPMOVQ2M
13401
13402     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13403                                      DAG.getConstant(ShiftInx, DL, InVT));
13404     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13405   }
13406
13407   // Shift LSB to MSB, extend if necessary and use TESTM.
13408   unsigned NumElts = InVT.getVectorNumElements();
13409   if (InVT.getSizeInBits() < 512 &&
13410       (InVT.getScalarType() == MVT::i8 || InVT.getScalarType() == MVT::i16 ||
13411        !Subtarget->hasVLX())) {
13412     assert((NumElts == 8 || NumElts == 16) && "Unexected vector type.");
13413
13414     // TESTD/Q should be used (if BW supported we use CVT2MASK above),
13415     // so vector should be extended to packed dword/qword.
13416     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(512/NumElts), NumElts);
13417     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13418     InVT = ExtVT;
13419     ShiftInx = InVT.getScalarSizeInBits() - 1;
13420   }
13421
13422   SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13423                                    DAG.getConstant(ShiftInx, DL, InVT));
13424   return DAG.getNode(X86ISD::TESTM, DL, VT, ShiftNode, ShiftNode);
13425 }
13426
13427 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13428   SDLoc DL(Op);
13429   MVT VT = Op.getSimpleValueType();
13430   SDValue In = Op.getOperand(0);
13431   MVT InVT = In.getSimpleValueType();
13432
13433   if (VT == MVT::i1) {
13434     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13435            "Invalid scalar TRUNCATE operation");
13436     if (InVT.getSizeInBits() >= 32)
13437       return SDValue();
13438     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13439     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13440   }
13441   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13442          "Invalid TRUNCATE operation");
13443
13444   if (VT.getVectorElementType() == MVT::i1)
13445     return LowerTruncateVecI1(Op, DAG, Subtarget);
13446
13447   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13448   if (Subtarget->hasAVX512()) {
13449     // word to byte only under BWI
13450     if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13451       return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13452                          DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13453     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13454   }
13455   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13456     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13457     if (Subtarget->hasInt256()) {
13458       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13459       In = DAG.getBitcast(MVT::v8i32, In);
13460       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13461                                 ShufMask);
13462       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13463                          DAG.getIntPtrConstant(0, DL));
13464     }
13465
13466     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13467                                DAG.getIntPtrConstant(0, DL));
13468     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13469                                DAG.getIntPtrConstant(2, DL));
13470     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13471     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13472     static const int ShufMask[] = {0, 2, 4, 6};
13473     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13474   }
13475
13476   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13477     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13478     if (Subtarget->hasInt256()) {
13479       In = DAG.getBitcast(MVT::v32i8, In);
13480
13481       SmallVector<SDValue,32> pshufbMask;
13482       for (unsigned i = 0; i < 2; ++i) {
13483         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13484         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13485         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13486         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13487         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13488         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13489         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13490         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13491         for (unsigned j = 0; j < 8; ++j)
13492           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13493       }
13494       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13495       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13496       In = DAG.getBitcast(MVT::v4i64, In);
13497
13498       static const int ShufMask[] = {0,  2,  -1,  -1};
13499       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13500                                 &ShufMask[0]);
13501       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13502                        DAG.getIntPtrConstant(0, DL));
13503       return DAG.getBitcast(VT, In);
13504     }
13505
13506     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13507                                DAG.getIntPtrConstant(0, DL));
13508
13509     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13510                                DAG.getIntPtrConstant(4, DL));
13511
13512     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13513     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13514
13515     // The PSHUFB mask:
13516     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13517                                    -1, -1, -1, -1, -1, -1, -1, -1};
13518
13519     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13520     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13521     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13522
13523     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13524     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13525
13526     // The MOVLHPS Mask:
13527     static const int ShufMask2[] = {0, 1, 4, 5};
13528     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13529     return DAG.getBitcast(MVT::v8i16, res);
13530   }
13531
13532   // Handle truncation of V256 to V128 using shuffles.
13533   if (!VT.is128BitVector() || !InVT.is256BitVector())
13534     return SDValue();
13535
13536   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13537
13538   unsigned NumElems = VT.getVectorNumElements();
13539   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13540
13541   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13542   // Prepare truncation shuffle mask
13543   for (unsigned i = 0; i != NumElems; ++i)
13544     MaskVec[i] = i * 2;
13545   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13546                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13547   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13548                      DAG.getIntPtrConstant(0, DL));
13549 }
13550
13551 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13552                                            SelectionDAG &DAG) const {
13553   assert(!Op.getSimpleValueType().isVector());
13554
13555   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13556     /*IsSigned=*/ true, /*IsReplace=*/ false);
13557   SDValue FIST = Vals.first, StackSlot = Vals.second;
13558   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13559   if (!FIST.getNode())
13560     return Op;
13561
13562   if (StackSlot.getNode())
13563     // Load the result.
13564     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13565                        FIST, StackSlot, MachinePointerInfo(),
13566                        false, false, false, 0);
13567
13568   // The node is the result.
13569   return FIST;
13570 }
13571
13572 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13573                                            SelectionDAG &DAG) const {
13574   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13575     /*IsSigned=*/ false, /*IsReplace=*/ false);
13576   SDValue FIST = Vals.first, StackSlot = Vals.second;
13577   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13578   if (!FIST.getNode())
13579     return Op;
13580
13581   if (StackSlot.getNode())
13582     // Load the result.
13583     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13584                        FIST, StackSlot, MachinePointerInfo(),
13585                        false, false, false, 0);
13586
13587   // The node is the result.
13588   return FIST;
13589 }
13590
13591 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13592   SDLoc DL(Op);
13593   MVT VT = Op.getSimpleValueType();
13594   SDValue In = Op.getOperand(0);
13595   MVT SVT = In.getSimpleValueType();
13596
13597   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13598
13599   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13600                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13601                                  In, DAG.getUNDEF(SVT)));
13602 }
13603
13604 /// The only differences between FABS and FNEG are the mask and the logic op.
13605 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13606 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13607   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13608          "Wrong opcode for lowering FABS or FNEG.");
13609
13610   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13611
13612   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13613   // into an FNABS. We'll lower the FABS after that if it is still in use.
13614   if (IsFABS)
13615     for (SDNode *User : Op->uses())
13616       if (User->getOpcode() == ISD::FNEG)
13617         return Op;
13618
13619   SDLoc dl(Op);
13620   MVT VT = Op.getSimpleValueType();
13621
13622   bool IsF128 = (VT == MVT::f128);
13623
13624   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13625   // decide if we should generate a 16-byte constant mask when we only need 4 or
13626   // 8 bytes for the scalar case.
13627
13628   MVT LogicVT;
13629   MVT EltVT;
13630   unsigned NumElts;
13631
13632   if (VT.isVector()) {
13633     LogicVT = VT;
13634     EltVT = VT.getVectorElementType();
13635     NumElts = VT.getVectorNumElements();
13636   } else if (IsF128) {
13637     // SSE instructions are used for optimized f128 logical operations.
13638     LogicVT = MVT::f128;
13639     EltVT = VT;
13640     NumElts = 1;
13641   } else {
13642     // There are no scalar bitwise logical SSE/AVX instructions, so we
13643     // generate a 16-byte vector constant and logic op even for the scalar case.
13644     // Using a 16-byte mask allows folding the load of the mask with
13645     // the logic op, so it can save (~4 bytes) on code size.
13646     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13647     EltVT = VT;
13648     NumElts = (VT == MVT::f64) ? 2 : 4;
13649   }
13650
13651   unsigned EltBits = EltVT.getSizeInBits();
13652   LLVMContext *Context = DAG.getContext();
13653   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13654   APInt MaskElt =
13655     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13656   Constant *C = ConstantInt::get(*Context, MaskElt);
13657   C = ConstantVector::getSplat(NumElts, C);
13658   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13659   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13660   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13661   SDValue Mask =
13662       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13663                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13664                   false, false, false, Alignment);
13665
13666   SDValue Op0 = Op.getOperand(0);
13667   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13668   unsigned LogicOp =
13669     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13670   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13671
13672   if (VT.isVector() || IsF128)
13673     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13674
13675   // For the scalar case extend to a 128-bit vector, perform the logic op,
13676   // and extract the scalar result back out.
13677   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13678   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13679   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13680                      DAG.getIntPtrConstant(0, dl));
13681 }
13682
13683 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13684   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13685   LLVMContext *Context = DAG.getContext();
13686   SDValue Op0 = Op.getOperand(0);
13687   SDValue Op1 = Op.getOperand(1);
13688   SDLoc dl(Op);
13689   MVT VT = Op.getSimpleValueType();
13690   MVT SrcVT = Op1.getSimpleValueType();
13691   bool IsF128 = (VT == MVT::f128);
13692
13693   // If second operand is smaller, extend it first.
13694   if (SrcVT.bitsLT(VT)) {
13695     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13696     SrcVT = VT;
13697   }
13698   // And if it is bigger, shrink it first.
13699   if (SrcVT.bitsGT(VT)) {
13700     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13701     SrcVT = VT;
13702   }
13703
13704   // At this point the operands and the result should have the same
13705   // type, and that won't be f80 since that is not custom lowered.
13706   assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13707          "Unexpected type in LowerFCOPYSIGN");
13708
13709   const fltSemantics &Sem =
13710       VT == MVT::f64 ? APFloat::IEEEdouble :
13711           (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13712   const unsigned SizeInBits = VT.getSizeInBits();
13713
13714   SmallVector<Constant *, 4> CV(
13715       VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13716       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13717
13718   // First, clear all bits but the sign bit from the second operand (sign).
13719   CV[0] = ConstantFP::get(*Context,
13720                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13721   Constant *C = ConstantVector::get(CV);
13722   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13723   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13724
13725   // Perform all logic operations as 16-byte vectors because there are no
13726   // scalar FP logic instructions in SSE. This allows load folding of the
13727   // constants into the logic instructions.
13728   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13729   SDValue Mask1 =
13730       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13731                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13732                   false, false, false, 16);
13733   if (!IsF128)
13734     Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13735   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13736
13737   // Next, clear the sign bit from the first operand (magnitude).
13738   // If it's a constant, we can clear it here.
13739   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13740     APFloat APF = Op0CN->getValueAPF();
13741     // If the magnitude is a positive zero, the sign bit alone is enough.
13742     if (APF.isPosZero())
13743       return IsF128 ? SignBit :
13744           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13745                       DAG.getIntPtrConstant(0, dl));
13746     APF.clearSign();
13747     CV[0] = ConstantFP::get(*Context, APF);
13748   } else {
13749     CV[0] = ConstantFP::get(
13750         *Context,
13751         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13752   }
13753   C = ConstantVector::get(CV);
13754   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13755   SDValue Val =
13756       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13757                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13758                   false, false, false, 16);
13759   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13760   if (!isa<ConstantFPSDNode>(Op0)) {
13761     if (!IsF128)
13762       Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13763     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13764   }
13765   // OR the magnitude value with the sign bit.
13766   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13767   return IsF128 ? Val :
13768       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13769                   DAG.getIntPtrConstant(0, dl));
13770 }
13771
13772 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13773   SDValue N0 = Op.getOperand(0);
13774   SDLoc dl(Op);
13775   MVT VT = Op.getSimpleValueType();
13776
13777   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13778   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13779                                   DAG.getConstant(1, dl, VT));
13780   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13781 }
13782
13783 // Check whether an OR'd tree is PTEST-able.
13784 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13785                                       SelectionDAG &DAG) {
13786   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13787
13788   if (!Subtarget->hasSSE41())
13789     return SDValue();
13790
13791   if (!Op->hasOneUse())
13792     return SDValue();
13793
13794   SDNode *N = Op.getNode();
13795   SDLoc DL(N);
13796
13797   SmallVector<SDValue, 8> Opnds;
13798   DenseMap<SDValue, unsigned> VecInMap;
13799   SmallVector<SDValue, 8> VecIns;
13800   EVT VT = MVT::Other;
13801
13802   // Recognize a special case where a vector is casted into wide integer to
13803   // test all 0s.
13804   Opnds.push_back(N->getOperand(0));
13805   Opnds.push_back(N->getOperand(1));
13806
13807   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13808     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13809     // BFS traverse all OR'd operands.
13810     if (I->getOpcode() == ISD::OR) {
13811       Opnds.push_back(I->getOperand(0));
13812       Opnds.push_back(I->getOperand(1));
13813       // Re-evaluate the number of nodes to be traversed.
13814       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13815       continue;
13816     }
13817
13818     // Quit if a non-EXTRACT_VECTOR_ELT
13819     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13820       return SDValue();
13821
13822     // Quit if without a constant index.
13823     SDValue Idx = I->getOperand(1);
13824     if (!isa<ConstantSDNode>(Idx))
13825       return SDValue();
13826
13827     SDValue ExtractedFromVec = I->getOperand(0);
13828     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13829     if (M == VecInMap.end()) {
13830       VT = ExtractedFromVec.getValueType();
13831       // Quit if not 128/256-bit vector.
13832       if (!VT.is128BitVector() && !VT.is256BitVector())
13833         return SDValue();
13834       // Quit if not the same type.
13835       if (VecInMap.begin() != VecInMap.end() &&
13836           VT != VecInMap.begin()->first.getValueType())
13837         return SDValue();
13838       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13839       VecIns.push_back(ExtractedFromVec);
13840     }
13841     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13842   }
13843
13844   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13845          "Not extracted from 128-/256-bit vector.");
13846
13847   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13848
13849   for (DenseMap<SDValue, unsigned>::const_iterator
13850         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13851     // Quit if not all elements are used.
13852     if (I->second != FullMask)
13853       return SDValue();
13854   }
13855
13856   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13857
13858   // Cast all vectors into TestVT for PTEST.
13859   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13860     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13861
13862   // If more than one full vectors are evaluated, OR them first before PTEST.
13863   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13864     // Each iteration will OR 2 nodes and append the result until there is only
13865     // 1 node left, i.e. the final OR'd value of all vectors.
13866     SDValue LHS = VecIns[Slot];
13867     SDValue RHS = VecIns[Slot + 1];
13868     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13869   }
13870
13871   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13872                      VecIns.back(), VecIns.back());
13873 }
13874
13875 /// \brief return true if \c Op has a use that doesn't just read flags.
13876 static bool hasNonFlagsUse(SDValue Op) {
13877   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13878        ++UI) {
13879     SDNode *User = *UI;
13880     unsigned UOpNo = UI.getOperandNo();
13881     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13882       // Look pass truncate.
13883       UOpNo = User->use_begin().getOperandNo();
13884       User = *User->use_begin();
13885     }
13886
13887     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13888         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13889       return true;
13890   }
13891   return false;
13892 }
13893
13894 /// Emit nodes that will be selected as "test Op0,Op0", or something
13895 /// equivalent.
13896 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13897                                     SelectionDAG &DAG) const {
13898   if (Op.getValueType() == MVT::i1) {
13899     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13900     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13901                        DAG.getConstant(0, dl, MVT::i8));
13902   }
13903   // CF and OF aren't always set the way we want. Determine which
13904   // of these we need.
13905   bool NeedCF = false;
13906   bool NeedOF = false;
13907   switch (X86CC) {
13908   default: break;
13909   case X86::COND_A: case X86::COND_AE:
13910   case X86::COND_B: case X86::COND_BE:
13911     NeedCF = true;
13912     break;
13913   case X86::COND_G: case X86::COND_GE:
13914   case X86::COND_L: case X86::COND_LE:
13915   case X86::COND_O: case X86::COND_NO: {
13916     // Check if we really need to set the
13917     // Overflow flag. If NoSignedWrap is present
13918     // that is not actually needed.
13919     switch (Op->getOpcode()) {
13920     case ISD::ADD:
13921     case ISD::SUB:
13922     case ISD::MUL:
13923     case ISD::SHL: {
13924       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13925       if (BinNode->Flags.hasNoSignedWrap())
13926         break;
13927     }
13928     default:
13929       NeedOF = true;
13930       break;
13931     }
13932     break;
13933   }
13934   }
13935   // See if we can use the EFLAGS value from the operand instead of
13936   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13937   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13938   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13939     // Emit a CMP with 0, which is the TEST pattern.
13940     //if (Op.getValueType() == MVT::i1)
13941     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13942     //                     DAG.getConstant(0, MVT::i1));
13943     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13944                        DAG.getConstant(0, dl, Op.getValueType()));
13945   }
13946   unsigned Opcode = 0;
13947   unsigned NumOperands = 0;
13948
13949   // Truncate operations may prevent the merge of the SETCC instruction
13950   // and the arithmetic instruction before it. Attempt to truncate the operands
13951   // of the arithmetic instruction and use a reduced bit-width instruction.
13952   bool NeedTruncation = false;
13953   SDValue ArithOp = Op;
13954   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13955     SDValue Arith = Op->getOperand(0);
13956     // Both the trunc and the arithmetic op need to have one user each.
13957     if (Arith->hasOneUse())
13958       switch (Arith.getOpcode()) {
13959         default: break;
13960         case ISD::ADD:
13961         case ISD::SUB:
13962         case ISD::AND:
13963         case ISD::OR:
13964         case ISD::XOR: {
13965           NeedTruncation = true;
13966           ArithOp = Arith;
13967         }
13968       }
13969   }
13970
13971   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13972   // which may be the result of a CAST.  We use the variable 'Op', which is the
13973   // non-casted variable when we check for possible users.
13974   switch (ArithOp.getOpcode()) {
13975   case ISD::ADD:
13976     // Due to an isel shortcoming, be conservative if this add is likely to be
13977     // selected as part of a load-modify-store instruction. When the root node
13978     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13979     // uses of other nodes in the match, such as the ADD in this case. This
13980     // leads to the ADD being left around and reselected, with the result being
13981     // two adds in the output.  Alas, even if none our users are stores, that
13982     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13983     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13984     // climbing the DAG back to the root, and it doesn't seem to be worth the
13985     // effort.
13986     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13987          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13988       if (UI->getOpcode() != ISD::CopyToReg &&
13989           UI->getOpcode() != ISD::SETCC &&
13990           UI->getOpcode() != ISD::STORE)
13991         goto default_case;
13992
13993     if (ConstantSDNode *C =
13994         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13995       // An add of one will be selected as an INC.
13996       if (C->isOne() && !Subtarget->slowIncDec()) {
13997         Opcode = X86ISD::INC;
13998         NumOperands = 1;
13999         break;
14000       }
14001
14002       // An add of negative one (subtract of one) will be selected as a DEC.
14003       if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
14004         Opcode = X86ISD::DEC;
14005         NumOperands = 1;
14006         break;
14007       }
14008     }
14009
14010     // Otherwise use a regular EFLAGS-setting add.
14011     Opcode = X86ISD::ADD;
14012     NumOperands = 2;
14013     break;
14014   case ISD::SHL:
14015   case ISD::SRL:
14016     // If we have a constant logical shift that's only used in a comparison
14017     // against zero turn it into an equivalent AND. This allows turning it into
14018     // a TEST instruction later.
14019     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14020         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14021       EVT VT = Op.getValueType();
14022       unsigned BitWidth = VT.getSizeInBits();
14023       unsigned ShAmt = Op->getConstantOperandVal(1);
14024       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14025         break;
14026       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14027                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14028                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14029       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14030         break;
14031       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14032                                 DAG.getConstant(Mask, dl, VT));
14033       DAG.ReplaceAllUsesWith(Op, New);
14034       Op = New;
14035     }
14036     break;
14037
14038   case ISD::AND:
14039     // If the primary and result isn't used, don't bother using X86ISD::AND,
14040     // because a TEST instruction will be better.
14041     if (!hasNonFlagsUse(Op))
14042       break;
14043     // FALL THROUGH
14044   case ISD::SUB:
14045   case ISD::OR:
14046   case ISD::XOR:
14047     // Due to the ISEL shortcoming noted above, be conservative if this op is
14048     // likely to be selected as part of a load-modify-store instruction.
14049     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14050            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14051       if (UI->getOpcode() == ISD::STORE)
14052         goto default_case;
14053
14054     // Otherwise use a regular EFLAGS-setting instruction.
14055     switch (ArithOp.getOpcode()) {
14056     default: llvm_unreachable("unexpected operator!");
14057     case ISD::SUB: Opcode = X86ISD::SUB; break;
14058     case ISD::XOR: Opcode = X86ISD::XOR; break;
14059     case ISD::AND: Opcode = X86ISD::AND; break;
14060     case ISD::OR: {
14061       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14062         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14063         if (EFLAGS.getNode())
14064           return EFLAGS;
14065       }
14066       Opcode = X86ISD::OR;
14067       break;
14068     }
14069     }
14070
14071     NumOperands = 2;
14072     break;
14073   case X86ISD::ADD:
14074   case X86ISD::SUB:
14075   case X86ISD::INC:
14076   case X86ISD::DEC:
14077   case X86ISD::OR:
14078   case X86ISD::XOR:
14079   case X86ISD::AND:
14080     return SDValue(Op.getNode(), 1);
14081   default:
14082   default_case:
14083     break;
14084   }
14085
14086   // If we found that truncation is beneficial, perform the truncation and
14087   // update 'Op'.
14088   if (NeedTruncation) {
14089     EVT VT = Op.getValueType();
14090     SDValue WideVal = Op->getOperand(0);
14091     EVT WideVT = WideVal.getValueType();
14092     unsigned ConvertedOp = 0;
14093     // Use a target machine opcode to prevent further DAGCombine
14094     // optimizations that may separate the arithmetic operations
14095     // from the setcc node.
14096     switch (WideVal.getOpcode()) {
14097       default: break;
14098       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14099       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14100       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14101       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14102       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14103     }
14104
14105     if (ConvertedOp) {
14106       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14107       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14108         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14109         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14110         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14111       }
14112     }
14113   }
14114
14115   if (Opcode == 0)
14116     // Emit a CMP with 0, which is the TEST pattern.
14117     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14118                        DAG.getConstant(0, dl, Op.getValueType()));
14119
14120   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14121   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
14122
14123   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14124   DAG.ReplaceAllUsesWith(Op, New);
14125   return SDValue(New.getNode(), 1);
14126 }
14127
14128 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14129 /// equivalent.
14130 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14131                                    SDLoc dl, SelectionDAG &DAG) const {
14132   if (isNullConstant(Op1))
14133     return EmitTest(Op0, X86CC, dl, DAG);
14134
14135   assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14136          "Unexpected comparison operation for MVT::i1 operands");
14137
14138   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14139        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14140     // Do the comparison at i32 if it's smaller, besides the Atom case.
14141     // This avoids subregister aliasing issues. Keep the smaller reference
14142     // if we're optimizing for size, however, as that'll allow better folding
14143     // of memory operations.
14144     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14145         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14146         !Subtarget->isAtom()) {
14147       unsigned ExtendOp =
14148           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14149       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14150       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14151     }
14152     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14153     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14154     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14155                               Op0, Op1);
14156     return SDValue(Sub.getNode(), 1);
14157   }
14158   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14159 }
14160
14161 /// Convert a comparison if required by the subtarget.
14162 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14163                                                  SelectionDAG &DAG) const {
14164   // If the subtarget does not support the FUCOMI instruction, floating-point
14165   // comparisons have to be converted.
14166   if (Subtarget->hasCMov() ||
14167       Cmp.getOpcode() != X86ISD::CMP ||
14168       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14169       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14170     return Cmp;
14171
14172   // The instruction selector will select an FUCOM instruction instead of
14173   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14174   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14175   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14176   SDLoc dl(Cmp);
14177   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14178   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14179   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14180                             DAG.getConstant(8, dl, MVT::i8));
14181   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14182
14183   // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14184   assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14185   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14186 }
14187
14188 /// The minimum architected relative accuracy is 2^-12. We need one
14189 /// Newton-Raphson step to have a good float result (24 bits of precision).
14190 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14191                                             DAGCombinerInfo &DCI,
14192                                             unsigned &RefinementSteps,
14193                                             bool &UseOneConstNR) const {
14194   EVT VT = Op.getValueType();
14195   const char *RecipOp;
14196
14197   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14198   // TODO: Add support for AVX512 (v16f32).
14199   // It is likely not profitable to do this for f64 because a double-precision
14200   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14201   // instructions: convert to single, rsqrtss, convert back to double, refine
14202   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14203   // along with FMA, this could be a throughput win.
14204   if (VT == MVT::f32 && Subtarget->hasSSE1())
14205     RecipOp = "sqrtf";
14206   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14207            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14208     RecipOp = "vec-sqrtf";
14209   else
14210     return SDValue();
14211
14212   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14213   if (!Recips.isEnabled(RecipOp))
14214     return SDValue();
14215
14216   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14217   UseOneConstNR = false;
14218   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14219 }
14220
14221 /// The minimum architected relative accuracy is 2^-12. We need one
14222 /// Newton-Raphson step to have a good float result (24 bits of precision).
14223 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14224                                             DAGCombinerInfo &DCI,
14225                                             unsigned &RefinementSteps) const {
14226   EVT VT = Op.getValueType();
14227   const char *RecipOp;
14228
14229   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14230   // TODO: Add support for AVX512 (v16f32).
14231   // It is likely not profitable to do this for f64 because a double-precision
14232   // reciprocal estimate with refinement on x86 prior to FMA requires
14233   // 15 instructions: convert to single, rcpss, convert back to double, refine
14234   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14235   // along with FMA, this could be a throughput win.
14236   if (VT == MVT::f32 && Subtarget->hasSSE1())
14237     RecipOp = "divf";
14238   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14239            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14240     RecipOp = "vec-divf";
14241   else
14242     return SDValue();
14243
14244   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14245   if (!Recips.isEnabled(RecipOp))
14246     return SDValue();
14247
14248   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14249   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14250 }
14251
14252 /// If we have at least two divisions that use the same divisor, convert to
14253 /// multplication by a reciprocal. This may need to be adjusted for a given
14254 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14255 /// This is because we still need one division to calculate the reciprocal and
14256 /// then we need two multiplies by that reciprocal as replacements for the
14257 /// original divisions.
14258 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14259   return 2;
14260 }
14261
14262 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14263 /// if it's possible.
14264 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14265                                      SDLoc dl, SelectionDAG &DAG) const {
14266   SDValue Op0 = And.getOperand(0);
14267   SDValue Op1 = And.getOperand(1);
14268   if (Op0.getOpcode() == ISD::TRUNCATE)
14269     Op0 = Op0.getOperand(0);
14270   if (Op1.getOpcode() == ISD::TRUNCATE)
14271     Op1 = Op1.getOperand(0);
14272
14273   SDValue LHS, RHS;
14274   if (Op1.getOpcode() == ISD::SHL)
14275     std::swap(Op0, Op1);
14276   if (Op0.getOpcode() == ISD::SHL) {
14277     if (isOneConstant(Op0.getOperand(0))) {
14278         // If we looked past a truncate, check that it's only truncating away
14279         // known zeros.
14280         unsigned BitWidth = Op0.getValueSizeInBits();
14281         unsigned AndBitWidth = And.getValueSizeInBits();
14282         if (BitWidth > AndBitWidth) {
14283           APInt Zeros, Ones;
14284           DAG.computeKnownBits(Op0, Zeros, Ones);
14285           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14286             return SDValue();
14287         }
14288         LHS = Op1;
14289         RHS = Op0.getOperand(1);
14290       }
14291   } else if (Op1.getOpcode() == ISD::Constant) {
14292     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14293     uint64_t AndRHSVal = AndRHS->getZExtValue();
14294     SDValue AndLHS = Op0;
14295
14296     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14297       LHS = AndLHS.getOperand(0);
14298       RHS = AndLHS.getOperand(1);
14299     }
14300
14301     // Use BT if the immediate can't be encoded in a TEST instruction.
14302     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14303       LHS = AndLHS;
14304       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14305     }
14306   }
14307
14308   if (LHS.getNode()) {
14309     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
14310     // instruction.  Since the shift amount is in-range-or-undefined, we know
14311     // that doing a bittest on the i32 value is ok.  We extend to i32 because
14312     // the encoding for the i16 version is larger than the i32 version.
14313     // Also promote i16 to i32 for performance / code size reason.
14314     if (LHS.getValueType() == MVT::i8 ||
14315         LHS.getValueType() == MVT::i16)
14316       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14317
14318     // If the operand types disagree, extend the shift amount to match.  Since
14319     // BT ignores high bits (like shifts) we can use anyextend.
14320     if (LHS.getValueType() != RHS.getValueType())
14321       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14322
14323     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14324     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14325     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14326                        DAG.getConstant(Cond, dl, MVT::i8), BT);
14327   }
14328
14329   return SDValue();
14330 }
14331
14332 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14333 /// mask CMPs.
14334 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14335                               SDValue &Op1) {
14336   unsigned SSECC;
14337   bool Swap = false;
14338
14339   // SSE Condition code mapping:
14340   //  0 - EQ
14341   //  1 - LT
14342   //  2 - LE
14343   //  3 - UNORD
14344   //  4 - NEQ
14345   //  5 - NLT
14346   //  6 - NLE
14347   //  7 - ORD
14348   switch (SetCCOpcode) {
14349   default: llvm_unreachable("Unexpected SETCC condition");
14350   case ISD::SETOEQ:
14351   case ISD::SETEQ:  SSECC = 0; break;
14352   case ISD::SETOGT:
14353   case ISD::SETGT:  Swap = true; // Fallthrough
14354   case ISD::SETLT:
14355   case ISD::SETOLT: SSECC = 1; break;
14356   case ISD::SETOGE:
14357   case ISD::SETGE:  Swap = true; // Fallthrough
14358   case ISD::SETLE:
14359   case ISD::SETOLE: SSECC = 2; break;
14360   case ISD::SETUO:  SSECC = 3; break;
14361   case ISD::SETUNE:
14362   case ISD::SETNE:  SSECC = 4; break;
14363   case ISD::SETULE: Swap = true; // Fallthrough
14364   case ISD::SETUGE: SSECC = 5; break;
14365   case ISD::SETULT: Swap = true; // Fallthrough
14366   case ISD::SETUGT: SSECC = 6; break;
14367   case ISD::SETO:   SSECC = 7; break;
14368   case ISD::SETUEQ:
14369   case ISD::SETONE: SSECC = 8; break;
14370   }
14371   if (Swap)
14372     std::swap(Op0, Op1);
14373
14374   return SSECC;
14375 }
14376
14377 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14378 // ones, and then concatenate the result back.
14379 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14380   MVT VT = Op.getSimpleValueType();
14381
14382   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14383          "Unsupported value type for operation");
14384
14385   unsigned NumElems = VT.getVectorNumElements();
14386   SDLoc dl(Op);
14387   SDValue CC = Op.getOperand(2);
14388
14389   // Extract the LHS vectors
14390   SDValue LHS = Op.getOperand(0);
14391   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14392   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14393
14394   // Extract the RHS vectors
14395   SDValue RHS = Op.getOperand(1);
14396   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14397   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14398
14399   // Issue the operation on the smaller types and concatenate the result back
14400   MVT EltVT = VT.getVectorElementType();
14401   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14402   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14403                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14404                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14405 }
14406
14407 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14408   SDValue Op0 = Op.getOperand(0);
14409   SDValue Op1 = Op.getOperand(1);
14410   SDValue CC = Op.getOperand(2);
14411   MVT VT = Op.getSimpleValueType();
14412   SDLoc dl(Op);
14413
14414   assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14415          "Unexpected type for boolean compare operation");
14416   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14417   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14418                                DAG.getConstant(-1, dl, VT));
14419   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14420                                DAG.getConstant(-1, dl, VT));
14421   switch (SetCCOpcode) {
14422   default: llvm_unreachable("Unexpected SETCC condition");
14423   case ISD::SETEQ:
14424     // (x == y) -> ~(x ^ y)
14425     return DAG.getNode(ISD::XOR, dl, VT,
14426                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14427                        DAG.getConstant(-1, dl, VT));
14428   case ISD::SETNE:
14429     // (x != y) -> (x ^ y)
14430     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14431   case ISD::SETUGT:
14432   case ISD::SETGT:
14433     // (x > y) -> (x & ~y)
14434     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14435   case ISD::SETULT:
14436   case ISD::SETLT:
14437     // (x < y) -> (~x & y)
14438     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14439   case ISD::SETULE:
14440   case ISD::SETLE:
14441     // (x <= y) -> (~x | y)
14442     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14443   case ISD::SETUGE:
14444   case ISD::SETGE:
14445     // (x >=y) -> (x | ~y)
14446     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14447   }
14448 }
14449
14450 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14451                                      const X86Subtarget *Subtarget) {
14452   SDValue Op0 = Op.getOperand(0);
14453   SDValue Op1 = Op.getOperand(1);
14454   SDValue CC = Op.getOperand(2);
14455   MVT VT = Op.getSimpleValueType();
14456   SDLoc dl(Op);
14457
14458   assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14459          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14460          "Cannot set masked compare for this operation");
14461
14462   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14463   unsigned  Opc = 0;
14464   bool Unsigned = false;
14465   bool Swap = false;
14466   unsigned SSECC;
14467   switch (SetCCOpcode) {
14468   default: llvm_unreachable("Unexpected SETCC condition");
14469   case ISD::SETNE:  SSECC = 4; break;
14470   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14471   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14472   case ISD::SETLT:  Swap = true; //fall-through
14473   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14474   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14475   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14476   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14477   case ISD::SETULE: Unsigned = true; //fall-through
14478   case ISD::SETLE:  SSECC = 2; break;
14479   }
14480
14481   if (Swap)
14482     std::swap(Op0, Op1);
14483   if (Opc)
14484     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14485   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14486   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14487                      DAG.getConstant(SSECC, dl, MVT::i8));
14488 }
14489
14490 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14491 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14492 /// return an empty value.
14493 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14494 {
14495   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14496   if (!BV)
14497     return SDValue();
14498
14499   MVT VT = Op1.getSimpleValueType();
14500   MVT EVT = VT.getVectorElementType();
14501   unsigned n = VT.getVectorNumElements();
14502   SmallVector<SDValue, 8> ULTOp1;
14503
14504   for (unsigned i = 0; i < n; ++i) {
14505     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14506     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14507       return SDValue();
14508
14509     // Avoid underflow.
14510     APInt Val = Elt->getAPIntValue();
14511     if (Val == 0)
14512       return SDValue();
14513
14514     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14515   }
14516
14517   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14518 }
14519
14520 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14521                            SelectionDAG &DAG) {
14522   SDValue Op0 = Op.getOperand(0);
14523   SDValue Op1 = Op.getOperand(1);
14524   SDValue CC = Op.getOperand(2);
14525   MVT VT = Op.getSimpleValueType();
14526   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14527   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14528   SDLoc dl(Op);
14529
14530   if (isFP) {
14531 #ifndef NDEBUG
14532     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14533     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14534 #endif
14535
14536     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14537     unsigned Opc = X86ISD::CMPP;
14538     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14539       assert(VT.getVectorNumElements() <= 16);
14540       Opc = X86ISD::CMPM;
14541     }
14542     // In the two special cases we can't handle, emit two comparisons.
14543     if (SSECC == 8) {
14544       unsigned CC0, CC1;
14545       unsigned CombineOpc;
14546       if (SetCCOpcode == ISD::SETUEQ) {
14547         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14548       } else {
14549         assert(SetCCOpcode == ISD::SETONE);
14550         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14551       }
14552
14553       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14554                                  DAG.getConstant(CC0, dl, MVT::i8));
14555       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14556                                  DAG.getConstant(CC1, dl, MVT::i8));
14557       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14558     }
14559     // Handle all other FP comparisons here.
14560     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14561                        DAG.getConstant(SSECC, dl, MVT::i8));
14562   }
14563
14564   MVT VTOp0 = Op0.getSimpleValueType();
14565   assert(VTOp0 == Op1.getSimpleValueType() &&
14566          "Expected operands with same type!");
14567   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14568          "Invalid number of packed elements for source and destination!");
14569
14570   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14571     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14572     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14573     // legalizer firstly checks if the first operand in input to the setcc has
14574     // a legal type. If so, then it promotes the return type to that same type.
14575     // Otherwise, the return type is promoted to the 'next legal type' which,
14576     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14577     //
14578     // We reach this code only if the following two conditions are met:
14579     // 1. Both return type and operand type have been promoted to wider types
14580     //    by the type legalizer.
14581     // 2. The original operand type has been promoted to a 256-bit vector.
14582     //
14583     // Note that condition 2. only applies for AVX targets.
14584     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14585     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14586   }
14587
14588   // The non-AVX512 code below works under the assumption that source and
14589   // destination types are the same.
14590   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14591          "Value types for source and destination must be the same!");
14592
14593   // Break 256-bit integer vector compare into smaller ones.
14594   if (VT.is256BitVector() && !Subtarget->hasInt256())
14595     return Lower256IntVSETCC(Op, DAG);
14596
14597   MVT OpVT = Op1.getSimpleValueType();
14598   if (OpVT.getVectorElementType() == MVT::i1)
14599     return LowerBoolVSETCC_AVX512(Op, DAG);
14600
14601   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14602   if (Subtarget->hasAVX512()) {
14603     if (Op1.getSimpleValueType().is512BitVector() ||
14604         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14605         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14606       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14607
14608     // In AVX-512 architecture setcc returns mask with i1 elements,
14609     // But there is no compare instruction for i8 and i16 elements in KNL.
14610     // We are not talking about 512-bit operands in this case, these
14611     // types are illegal.
14612     if (MaskResult &&
14613         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14614          OpVT.getVectorElementType().getSizeInBits() >= 8))
14615       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14616                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14617   }
14618
14619   // Lower using XOP integer comparisons.
14620   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14621        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14622     // Translate compare code to XOP PCOM compare mode.
14623     unsigned CmpMode = 0;
14624     switch (SetCCOpcode) {
14625     default: llvm_unreachable("Unexpected SETCC condition");
14626     case ISD::SETULT:
14627     case ISD::SETLT: CmpMode = 0x00; break;
14628     case ISD::SETULE:
14629     case ISD::SETLE: CmpMode = 0x01; break;
14630     case ISD::SETUGT:
14631     case ISD::SETGT: CmpMode = 0x02; break;
14632     case ISD::SETUGE:
14633     case ISD::SETGE: CmpMode = 0x03; break;
14634     case ISD::SETEQ: CmpMode = 0x04; break;
14635     case ISD::SETNE: CmpMode = 0x05; break;
14636     }
14637
14638     // Are we comparing unsigned or signed integers?
14639     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14640       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14641
14642     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14643                        DAG.getConstant(CmpMode, dl, MVT::i8));
14644   }
14645
14646   // We are handling one of the integer comparisons here.  Since SSE only has
14647   // GT and EQ comparisons for integer, swapping operands and multiple
14648   // operations may be required for some comparisons.
14649   unsigned Opc;
14650   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14651   bool Subus = false;
14652
14653   switch (SetCCOpcode) {
14654   default: llvm_unreachable("Unexpected SETCC condition");
14655   case ISD::SETNE:  Invert = true;
14656   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14657   case ISD::SETLT:  Swap = true;
14658   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14659   case ISD::SETGE:  Swap = true;
14660   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14661                     Invert = true; break;
14662   case ISD::SETULT: Swap = true;
14663   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14664                     FlipSigns = true; break;
14665   case ISD::SETUGE: Swap = true;
14666   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14667                     FlipSigns = true; Invert = true; break;
14668   }
14669
14670   // Special case: Use min/max operations for SETULE/SETUGE
14671   MVT VET = VT.getVectorElementType();
14672   bool hasMinMax =
14673        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14674     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14675
14676   if (hasMinMax) {
14677     switch (SetCCOpcode) {
14678     default: break;
14679     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14680     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14681     }
14682
14683     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14684   }
14685
14686   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14687   if (!MinMax && hasSubus) {
14688     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14689     // Op0 u<= Op1:
14690     //   t = psubus Op0, Op1
14691     //   pcmpeq t, <0..0>
14692     switch (SetCCOpcode) {
14693     default: break;
14694     case ISD::SETULT: {
14695       // If the comparison is against a constant we can turn this into a
14696       // setule.  With psubus, setule does not require a swap.  This is
14697       // beneficial because the constant in the register is no longer
14698       // destructed as the destination so it can be hoisted out of a loop.
14699       // Only do this pre-AVX since vpcmp* is no longer destructive.
14700       if (Subtarget->hasAVX())
14701         break;
14702       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14703       if (ULEOp1.getNode()) {
14704         Op1 = ULEOp1;
14705         Subus = true; Invert = false; Swap = false;
14706       }
14707       break;
14708     }
14709     // Psubus is better than flip-sign because it requires no inversion.
14710     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14711     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14712     }
14713
14714     if (Subus) {
14715       Opc = X86ISD::SUBUS;
14716       FlipSigns = false;
14717     }
14718   }
14719
14720   if (Swap)
14721     std::swap(Op0, Op1);
14722
14723   // Check that the operation in question is available (most are plain SSE2,
14724   // but PCMPGTQ and PCMPEQQ have different requirements).
14725   if (VT == MVT::v2i64) {
14726     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14727       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14728
14729       // First cast everything to the right type.
14730       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14731       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14732
14733       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14734       // bits of the inputs before performing those operations. The lower
14735       // compare is always unsigned.
14736       SDValue SB;
14737       if (FlipSigns) {
14738         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14739       } else {
14740         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14741         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14742         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14743                          Sign, Zero, Sign, Zero);
14744       }
14745       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14746       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14747
14748       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14749       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14750       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14751
14752       // Create masks for only the low parts/high parts of the 64 bit integers.
14753       static const int MaskHi[] = { 1, 1, 3, 3 };
14754       static const int MaskLo[] = { 0, 0, 2, 2 };
14755       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14756       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14757       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14758
14759       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14760       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14761
14762       if (Invert)
14763         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14764
14765       return DAG.getBitcast(VT, Result);
14766     }
14767
14768     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14769       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14770       // pcmpeqd + pshufd + pand.
14771       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14772
14773       // First cast everything to the right type.
14774       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14775       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14776
14777       // Do the compare.
14778       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14779
14780       // Make sure the lower and upper halves are both all-ones.
14781       static const int Mask[] = { 1, 0, 3, 2 };
14782       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14783       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14784
14785       if (Invert)
14786         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14787
14788       return DAG.getBitcast(VT, Result);
14789     }
14790   }
14791
14792   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14793   // bits of the inputs before performing those operations.
14794   if (FlipSigns) {
14795     MVT EltVT = VT.getVectorElementType();
14796     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14797                                  VT);
14798     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14799     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14800   }
14801
14802   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14803
14804   // If the logical-not of the result is required, perform that now.
14805   if (Invert)
14806     Result = DAG.getNOT(dl, Result, VT);
14807
14808   if (MinMax)
14809     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14810
14811   if (Subus)
14812     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14813                          getZeroVector(VT, Subtarget, DAG, dl));
14814
14815   return Result;
14816 }
14817
14818 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14819
14820   MVT VT = Op.getSimpleValueType();
14821
14822   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14823
14824   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14825          && "SetCC type must be 8-bit or 1-bit integer");
14826   SDValue Op0 = Op.getOperand(0);
14827   SDValue Op1 = Op.getOperand(1);
14828   SDLoc dl(Op);
14829   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14830
14831   // Optimize to BT if possible.
14832   // Lower (X & (1 << N)) == 0 to BT(X, N).
14833   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14834   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14835   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14836       isNullConstant(Op1) &&
14837       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14838     if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14839       if (VT == MVT::i1)
14840         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14841       return NewSetCC;
14842     }
14843   }
14844
14845   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14846   // these.
14847   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14848       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14849
14850     // If the input is a setcc, then reuse the input setcc or use a new one with
14851     // the inverted condition.
14852     if (Op0.getOpcode() == X86ISD::SETCC) {
14853       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14854       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14855       if (!Invert)
14856         return Op0;
14857
14858       CCode = X86::GetOppositeBranchCondition(CCode);
14859       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14860                                   DAG.getConstant(CCode, dl, MVT::i8),
14861                                   Op0.getOperand(1));
14862       if (VT == MVT::i1)
14863         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14864       return SetCC;
14865     }
14866   }
14867   if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14868       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14869
14870     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14871     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14872   }
14873
14874   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14875   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14876   if (X86CC == X86::COND_INVALID)
14877     return SDValue();
14878
14879   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14880   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14881   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14882                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14883   if (VT == MVT::i1)
14884     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14885   return SetCC;
14886 }
14887
14888 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14889   SDValue LHS = Op.getOperand(0);
14890   SDValue RHS = Op.getOperand(1);
14891   SDValue Carry = Op.getOperand(2);
14892   SDValue Cond = Op.getOperand(3);
14893   SDLoc DL(Op);
14894
14895   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14896   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14897
14898   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14899   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14900   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14901   return DAG.getNode(X86ISD::SETCC, DL, Op.getValueType(),
14902                      DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14903 }
14904
14905 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14906 static bool isX86LogicalCmp(SDValue Op) {
14907   unsigned Opc = Op.getNode()->getOpcode();
14908   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14909       Opc == X86ISD::SAHF)
14910     return true;
14911   if (Op.getResNo() == 1 &&
14912       (Opc == X86ISD::ADD ||
14913        Opc == X86ISD::SUB ||
14914        Opc == X86ISD::ADC ||
14915        Opc == X86ISD::SBB ||
14916        Opc == X86ISD::SMUL ||
14917        Opc == X86ISD::UMUL ||
14918        Opc == X86ISD::INC ||
14919        Opc == X86ISD::DEC ||
14920        Opc == X86ISD::OR ||
14921        Opc == X86ISD::XOR ||
14922        Opc == X86ISD::AND))
14923     return true;
14924
14925   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14926     return true;
14927
14928   return false;
14929 }
14930
14931 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14932   if (V.getOpcode() != ISD::TRUNCATE)
14933     return false;
14934
14935   SDValue VOp0 = V.getOperand(0);
14936   unsigned InBits = VOp0.getValueSizeInBits();
14937   unsigned Bits = V.getValueSizeInBits();
14938   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14939 }
14940
14941 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14942   bool addTest = true;
14943   SDValue Cond  = Op.getOperand(0);
14944   SDValue Op1 = Op.getOperand(1);
14945   SDValue Op2 = Op.getOperand(2);
14946   SDLoc DL(Op);
14947   MVT VT = Op1.getSimpleValueType();
14948   SDValue CC;
14949
14950   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14951   // are available or VBLENDV if AVX is available.
14952   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14953   if (Cond.getOpcode() == ISD::SETCC &&
14954       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14955        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14956       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
14957     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14958     int SSECC = translateX86FSETCC(
14959         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14960
14961     if (SSECC != 8) {
14962       if (Subtarget->hasAVX512()) {
14963         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14964                                   DAG.getConstant(SSECC, DL, MVT::i8));
14965         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14966       }
14967
14968       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14969                                 DAG.getConstant(SSECC, DL, MVT::i8));
14970
14971       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14972       // of 3 logic instructions for size savings and potentially speed.
14973       // Unfortunately, there is no scalar form of VBLENDV.
14974
14975       // If either operand is a constant, don't try this. We can expect to
14976       // optimize away at least one of the logic instructions later in that
14977       // case, so that sequence would be faster than a variable blend.
14978
14979       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14980       // uses XMM0 as the selection register. That may need just as many
14981       // instructions as the AND/ANDN/OR sequence due to register moves, so
14982       // don't bother.
14983
14984       if (Subtarget->hasAVX() &&
14985           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14986
14987         // Convert to vectors, do a VSELECT, and convert back to scalar.
14988         // All of the conversions should be optimized away.
14989
14990         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14991         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14992         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14993         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14994
14995         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14996         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14997
14998         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14999
15000         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
15001                            VSel, DAG.getIntPtrConstant(0, DL));
15002       }
15003       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15004       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15005       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15006     }
15007   }
15008
15009   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
15010     SDValue Op1Scalar;
15011     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
15012       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
15013     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
15014       Op1Scalar = Op1.getOperand(0);
15015     SDValue Op2Scalar;
15016     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
15017       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
15018     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
15019       Op2Scalar = Op2.getOperand(0);
15020     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
15021       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
15022                                       Op1Scalar.getValueType(),
15023                                       Cond, Op1Scalar, Op2Scalar);
15024       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
15025         return DAG.getBitcast(VT, newSelect);
15026       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
15027       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
15028                          DAG.getIntPtrConstant(0, DL));
15029     }
15030   }
15031
15032   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
15033     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
15034     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15035                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
15036     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15037                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
15038     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
15039                                     Cond, Op1, Op2);
15040     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
15041   }
15042
15043   if (Cond.getOpcode() == ISD::SETCC) {
15044     SDValue NewCond = LowerSETCC(Cond, DAG);
15045     if (NewCond.getNode())
15046       Cond = NewCond;
15047   }
15048
15049   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15050   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15051   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15052   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15053   if (Cond.getOpcode() == X86ISD::SETCC &&
15054       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15055       isNullConstant(Cond.getOperand(1).getOperand(1))) {
15056     SDValue Cmp = Cond.getOperand(1);
15057
15058     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15059
15060     if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15061         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15062       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
15063
15064       SDValue CmpOp0 = Cmp.getOperand(0);
15065       // Apply further optimizations for special cases
15066       // (select (x != 0), -1, 0) -> neg & sbb
15067       // (select (x == 0), 0, -1) -> neg & sbb
15068       if (isNullConstant(Y) &&
15069             (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
15070           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15071           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15072                                     DAG.getConstant(0, DL,
15073                                                     CmpOp0.getValueType()),
15074                                     CmpOp0);
15075           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15076                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
15077                                     SDValue(Neg.getNode(), 1));
15078           return Res;
15079         }
15080
15081       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15082                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
15083       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15084
15085       SDValue Res =   // Res = 0 or -1.
15086         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15087                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
15088
15089       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
15090         Res = DAG.getNOT(DL, Res, Res.getValueType());
15091
15092       if (!isNullConstant(Op2))
15093         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15094       return Res;
15095     }
15096   }
15097
15098   // Look past (and (setcc_carry (cmp ...)), 1).
15099   if (Cond.getOpcode() == ISD::AND &&
15100       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15101       isOneConstant(Cond.getOperand(1)))
15102     Cond = Cond.getOperand(0);
15103
15104   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15105   // setting operand in place of the X86ISD::SETCC.
15106   unsigned CondOpcode = Cond.getOpcode();
15107   if (CondOpcode == X86ISD::SETCC ||
15108       CondOpcode == X86ISD::SETCC_CARRY) {
15109     CC = Cond.getOperand(0);
15110
15111     SDValue Cmp = Cond.getOperand(1);
15112     unsigned Opc = Cmp.getOpcode();
15113     MVT VT = Op.getSimpleValueType();
15114
15115     bool IllegalFPCMov = false;
15116     if (VT.isFloatingPoint() && !VT.isVector() &&
15117         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15118       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15119
15120     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15121         Opc == X86ISD::BT) { // FIXME
15122       Cond = Cmp;
15123       addTest = false;
15124     }
15125   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15126              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15127              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15128               Cond.getOperand(0).getValueType() != MVT::i8)) {
15129     SDValue LHS = Cond.getOperand(0);
15130     SDValue RHS = Cond.getOperand(1);
15131     unsigned X86Opcode;
15132     unsigned X86Cond;
15133     SDVTList VTs;
15134     switch (CondOpcode) {
15135     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15136     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15137     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15138     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15139     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15140     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15141     default: llvm_unreachable("unexpected overflowing operator");
15142     }
15143     if (CondOpcode == ISD::UMULO)
15144       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15145                           MVT::i32);
15146     else
15147       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15148
15149     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15150
15151     if (CondOpcode == ISD::UMULO)
15152       Cond = X86Op.getValue(2);
15153     else
15154       Cond = X86Op.getValue(1);
15155
15156     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15157     addTest = false;
15158   }
15159
15160   if (addTest) {
15161     // Look past the truncate if the high bits are known zero.
15162     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15163       Cond = Cond.getOperand(0);
15164
15165     // We know the result of AND is compared against zero. Try to match
15166     // it to BT.
15167     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15168       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
15169         CC = NewSetCC.getOperand(0);
15170         Cond = NewSetCC.getOperand(1);
15171         addTest = false;
15172       }
15173     }
15174   }
15175
15176   if (addTest) {
15177     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
15178     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15179   }
15180
15181   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15182   // a <  b ?  0 : -1 -> RES = setcc_carry
15183   // a >= b ? -1 :  0 -> RES = setcc_carry
15184   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15185   if (Cond.getOpcode() == X86ISD::SUB) {
15186     Cond = ConvertCmpIfNecessary(Cond, DAG);
15187     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15188
15189     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15190         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15191         (isNullConstant(Op1) || isNullConstant(Op2))) {
15192       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15193                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15194                                 Cond);
15195       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15196         return DAG.getNOT(DL, Res, Res.getValueType());
15197       return Res;
15198     }
15199   }
15200
15201   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15202   // widen the cmov and push the truncate through. This avoids introducing a new
15203   // branch during isel and doesn't add any extensions.
15204   if (Op.getValueType() == MVT::i8 &&
15205       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15206     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15207     if (T1.getValueType() == T2.getValueType() &&
15208         // Blacklist CopyFromReg to avoid partial register stalls.
15209         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15210       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15211       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15212       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15213     }
15214   }
15215
15216   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15217   // condition is true.
15218   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15219   SDValue Ops[] = { Op2, Op1, CC, Cond };
15220   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15221 }
15222
15223 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15224                                        const X86Subtarget *Subtarget,
15225                                        SelectionDAG &DAG) {
15226   MVT VT = Op->getSimpleValueType(0);
15227   SDValue In = Op->getOperand(0);
15228   MVT InVT = In.getSimpleValueType();
15229   MVT VTElt = VT.getVectorElementType();
15230   MVT InVTElt = InVT.getVectorElementType();
15231   SDLoc dl(Op);
15232
15233   // SKX processor
15234   if ((InVTElt == MVT::i1) &&
15235       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15236         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15237
15238        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15239         VTElt.getSizeInBits() <= 16)) ||
15240
15241        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15242         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15243
15244        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15245         VTElt.getSizeInBits() >= 32))))
15246     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15247
15248   unsigned int NumElts = VT.getVectorNumElements();
15249
15250   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15251     return SDValue();
15252
15253   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15254     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15255       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15256     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15257   }
15258
15259   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15260   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15261   SDValue NegOne =
15262    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15263                    ExtVT);
15264   SDValue Zero =
15265    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15266
15267   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15268   if (VT.is512BitVector())
15269     return V;
15270   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15271 }
15272
15273 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15274                                              const X86Subtarget *Subtarget,
15275                                              SelectionDAG &DAG) {
15276   SDValue In = Op->getOperand(0);
15277   MVT VT = Op->getSimpleValueType(0);
15278   MVT InVT = In.getSimpleValueType();
15279   assert(VT.getSizeInBits() == InVT.getSizeInBits());
15280
15281   MVT InSVT = InVT.getVectorElementType();
15282   assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15283
15284   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15285     return SDValue();
15286   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15287     return SDValue();
15288
15289   SDLoc dl(Op);
15290
15291   // SSE41 targets can use the pmovsx* instructions directly.
15292   if (Subtarget->hasSSE41())
15293     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15294
15295   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15296   SDValue Curr = In;
15297   MVT CurrVT = InVT;
15298
15299   // As SRAI is only available on i16/i32 types, we expand only up to i32
15300   // and handle i64 separately.
15301   while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15302     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15303     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15304     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15305     Curr = DAG.getBitcast(CurrVT, Curr);
15306   }
15307
15308   SDValue SignExt = Curr;
15309   if (CurrVT != InVT) {
15310     unsigned SignExtShift =
15311         CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15312     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15313                           DAG.getConstant(SignExtShift, dl, MVT::i8));
15314   }
15315
15316   if (CurrVT == VT)
15317     return SignExt;
15318
15319   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15320     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15321                                DAG.getConstant(31, dl, MVT::i8));
15322     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15323     return DAG.getBitcast(VT, Ext);
15324   }
15325
15326   return SDValue();
15327 }
15328
15329 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15330                                 SelectionDAG &DAG) {
15331   MVT VT = Op->getSimpleValueType(0);
15332   SDValue In = Op->getOperand(0);
15333   MVT InVT = In.getSimpleValueType();
15334   SDLoc dl(Op);
15335
15336   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15337     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15338
15339   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15340       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15341       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15342     return SDValue();
15343
15344   if (Subtarget->hasInt256())
15345     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15346
15347   // Optimize vectors in AVX mode
15348   // Sign extend  v8i16 to v8i32 and
15349   //              v4i32 to v4i64
15350   //
15351   // Divide input vector into two parts
15352   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15353   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15354   // concat the vectors to original VT
15355
15356   unsigned NumElems = InVT.getVectorNumElements();
15357   SDValue Undef = DAG.getUNDEF(InVT);
15358
15359   SmallVector<int,8> ShufMask1(NumElems, -1);
15360   for (unsigned i = 0; i != NumElems/2; ++i)
15361     ShufMask1[i] = i;
15362
15363   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15364
15365   SmallVector<int,8> ShufMask2(NumElems, -1);
15366   for (unsigned i = 0; i != NumElems/2; ++i)
15367     ShufMask2[i] = i + NumElems/2;
15368
15369   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15370
15371   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15372                                 VT.getVectorNumElements()/2);
15373
15374   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15375   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15376
15377   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15378 }
15379
15380 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15381 // may emit an illegal shuffle but the expansion is still better than scalar
15382 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15383 // we'll emit a shuffle and a arithmetic shift.
15384 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15385 // TODO: It is possible to support ZExt by zeroing the undef values during
15386 // the shuffle phase or after the shuffle.
15387 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15388                                  SelectionDAG &DAG) {
15389   MVT RegVT = Op.getSimpleValueType();
15390   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15391   assert(RegVT.isInteger() &&
15392          "We only custom lower integer vector sext loads.");
15393
15394   // Nothing useful we can do without SSE2 shuffles.
15395   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15396
15397   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15398   SDLoc dl(Ld);
15399   EVT MemVT = Ld->getMemoryVT();
15400   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15401   unsigned RegSz = RegVT.getSizeInBits();
15402
15403   ISD::LoadExtType Ext = Ld->getExtensionType();
15404
15405   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15406          && "Only anyext and sext are currently implemented.");
15407   assert(MemVT != RegVT && "Cannot extend to the same type");
15408   assert(MemVT.isVector() && "Must load a vector from memory");
15409
15410   unsigned NumElems = RegVT.getVectorNumElements();
15411   unsigned MemSz = MemVT.getSizeInBits();
15412   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15413
15414   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15415     // The only way in which we have a legal 256-bit vector result but not the
15416     // integer 256-bit operations needed to directly lower a sextload is if we
15417     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15418     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15419     // correctly legalized. We do this late to allow the canonical form of
15420     // sextload to persist throughout the rest of the DAG combiner -- it wants
15421     // to fold together any extensions it can, and so will fuse a sign_extend
15422     // of an sextload into a sextload targeting a wider value.
15423     SDValue Load;
15424     if (MemSz == 128) {
15425       // Just switch this to a normal load.
15426       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15427                                        "it must be a legal 128-bit vector "
15428                                        "type!");
15429       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15430                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15431                   Ld->isInvariant(), Ld->getAlignment());
15432     } else {
15433       assert(MemSz < 128 &&
15434              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15435       // Do an sext load to a 128-bit vector type. We want to use the same
15436       // number of elements, but elements half as wide. This will end up being
15437       // recursively lowered by this routine, but will succeed as we definitely
15438       // have all the necessary features if we're using AVX1.
15439       EVT HalfEltVT =
15440           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15441       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15442       Load =
15443           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15444                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15445                          Ld->isNonTemporal(), Ld->isInvariant(),
15446                          Ld->getAlignment());
15447     }
15448
15449     // Replace chain users with the new chain.
15450     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15451     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15452
15453     // Finally, do a normal sign-extend to the desired register.
15454     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15455   }
15456
15457   // All sizes must be a power of two.
15458   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15459          "Non-power-of-two elements are not custom lowered!");
15460
15461   // Attempt to load the original value using scalar loads.
15462   // Find the largest scalar type that divides the total loaded size.
15463   MVT SclrLoadTy = MVT::i8;
15464   for (MVT Tp : MVT::integer_valuetypes()) {
15465     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15466       SclrLoadTy = Tp;
15467     }
15468   }
15469
15470   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15471   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15472       (64 <= MemSz))
15473     SclrLoadTy = MVT::f64;
15474
15475   // Calculate the number of scalar loads that we need to perform
15476   // in order to load our vector from memory.
15477   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15478
15479   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15480          "Can only lower sext loads with a single scalar load!");
15481
15482   unsigned loadRegZize = RegSz;
15483   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15484     loadRegZize = 128;
15485
15486   // Represent our vector as a sequence of elements which are the
15487   // largest scalar that we can load.
15488   EVT LoadUnitVecVT = EVT::getVectorVT(
15489       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15490
15491   // Represent the data using the same element type that is stored in
15492   // memory. In practice, we ''widen'' MemVT.
15493   EVT WideVecVT =
15494       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15495                        loadRegZize / MemVT.getScalarSizeInBits());
15496
15497   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15498          "Invalid vector type");
15499
15500   // We can't shuffle using an illegal type.
15501   assert(TLI.isTypeLegal(WideVecVT) &&
15502          "We only lower types that form legal widened vector types");
15503
15504   SmallVector<SDValue, 8> Chains;
15505   SDValue Ptr = Ld->getBasePtr();
15506   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15507                                       TLI.getPointerTy(DAG.getDataLayout()));
15508   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15509
15510   for (unsigned i = 0; i < NumLoads; ++i) {
15511     // Perform a single load.
15512     SDValue ScalarLoad =
15513         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15514                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15515                     Ld->getAlignment());
15516     Chains.push_back(ScalarLoad.getValue(1));
15517     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15518     // another round of DAGCombining.
15519     if (i == 0)
15520       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15521     else
15522       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15523                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15524
15525     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15526   }
15527
15528   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15529
15530   // Bitcast the loaded value to a vector of the original element type, in
15531   // the size of the target vector type.
15532   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15533   unsigned SizeRatio = RegSz / MemSz;
15534
15535   if (Ext == ISD::SEXTLOAD) {
15536     // If we have SSE4.1, we can directly emit a VSEXT node.
15537     if (Subtarget->hasSSE41()) {
15538       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15539       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15540       return Sext;
15541     }
15542
15543     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15544     // lanes.
15545     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15546            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15547
15548     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15549     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15550     return Shuff;
15551   }
15552
15553   // Redistribute the loaded elements into the different locations.
15554   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15555   for (unsigned i = 0; i != NumElems; ++i)
15556     ShuffleVec[i * SizeRatio] = i;
15557
15558   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15559                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15560
15561   // Bitcast to the requested type.
15562   Shuff = DAG.getBitcast(RegVT, Shuff);
15563   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15564   return Shuff;
15565 }
15566
15567 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15568 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15569 // from the AND / OR.
15570 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15571   Opc = Op.getOpcode();
15572   if (Opc != ISD::OR && Opc != ISD::AND)
15573     return false;
15574   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15575           Op.getOperand(0).hasOneUse() &&
15576           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15577           Op.getOperand(1).hasOneUse());
15578 }
15579
15580 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15581 // 1 and that the SETCC node has a single use.
15582 static bool isXor1OfSetCC(SDValue Op) {
15583   if (Op.getOpcode() != ISD::XOR)
15584     return false;
15585   if (isOneConstant(Op.getOperand(1)))
15586     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15587            Op.getOperand(0).hasOneUse();
15588   return false;
15589 }
15590
15591 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15592   bool addTest = true;
15593   SDValue Chain = Op.getOperand(0);
15594   SDValue Cond  = Op.getOperand(1);
15595   SDValue Dest  = Op.getOperand(2);
15596   SDLoc dl(Op);
15597   SDValue CC;
15598   bool Inverted = false;
15599
15600   if (Cond.getOpcode() == ISD::SETCC) {
15601     // Check for setcc([su]{add,sub,mul}o == 0).
15602     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15603         isNullConstant(Cond.getOperand(1)) &&
15604         Cond.getOperand(0).getResNo() == 1 &&
15605         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15606          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15607          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15608          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15609          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15610          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15611       Inverted = true;
15612       Cond = Cond.getOperand(0);
15613     } else {
15614       SDValue NewCond = LowerSETCC(Cond, DAG);
15615       if (NewCond.getNode())
15616         Cond = NewCond;
15617     }
15618   }
15619 #if 0
15620   // FIXME: LowerXALUO doesn't handle these!!
15621   else if (Cond.getOpcode() == X86ISD::ADD  ||
15622            Cond.getOpcode() == X86ISD::SUB  ||
15623            Cond.getOpcode() == X86ISD::SMUL ||
15624            Cond.getOpcode() == X86ISD::UMUL)
15625     Cond = LowerXALUO(Cond, DAG);
15626 #endif
15627
15628   // Look pass (and (setcc_carry (cmp ...)), 1).
15629   if (Cond.getOpcode() == ISD::AND &&
15630       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15631       isOneConstant(Cond.getOperand(1)))
15632     Cond = Cond.getOperand(0);
15633
15634   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15635   // setting operand in place of the X86ISD::SETCC.
15636   unsigned CondOpcode = Cond.getOpcode();
15637   if (CondOpcode == X86ISD::SETCC ||
15638       CondOpcode == X86ISD::SETCC_CARRY) {
15639     CC = Cond.getOperand(0);
15640
15641     SDValue Cmp = Cond.getOperand(1);
15642     unsigned Opc = Cmp.getOpcode();
15643     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15644     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15645       Cond = Cmp;
15646       addTest = false;
15647     } else {
15648       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15649       default: break;
15650       case X86::COND_O:
15651       case X86::COND_B:
15652         // These can only come from an arithmetic instruction with overflow,
15653         // e.g. SADDO, UADDO.
15654         Cond = Cond.getNode()->getOperand(1);
15655         addTest = false;
15656         break;
15657       }
15658     }
15659   }
15660   CondOpcode = Cond.getOpcode();
15661   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15662       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15663       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15664        Cond.getOperand(0).getValueType() != MVT::i8)) {
15665     SDValue LHS = Cond.getOperand(0);
15666     SDValue RHS = Cond.getOperand(1);
15667     unsigned X86Opcode;
15668     unsigned X86Cond;
15669     SDVTList VTs;
15670     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15671     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15672     // X86ISD::INC).
15673     switch (CondOpcode) {
15674     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15675     case ISD::SADDO:
15676       if (isOneConstant(RHS)) {
15677           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15678           break;
15679         }
15680       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15681     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15682     case ISD::SSUBO:
15683       if (isOneConstant(RHS)) {
15684           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15685           break;
15686         }
15687       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15688     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15689     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15690     default: llvm_unreachable("unexpected overflowing operator");
15691     }
15692     if (Inverted)
15693       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15694     if (CondOpcode == ISD::UMULO)
15695       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15696                           MVT::i32);
15697     else
15698       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15699
15700     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15701
15702     if (CondOpcode == ISD::UMULO)
15703       Cond = X86Op.getValue(2);
15704     else
15705       Cond = X86Op.getValue(1);
15706
15707     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15708     addTest = false;
15709   } else {
15710     unsigned CondOpc;
15711     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15712       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15713       if (CondOpc == ISD::OR) {
15714         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15715         // two branches instead of an explicit OR instruction with a
15716         // separate test.
15717         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15718             isX86LogicalCmp(Cmp)) {
15719           CC = Cond.getOperand(0).getOperand(0);
15720           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15721                               Chain, Dest, CC, Cmp);
15722           CC = Cond.getOperand(1).getOperand(0);
15723           Cond = Cmp;
15724           addTest = false;
15725         }
15726       } else { // ISD::AND
15727         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15728         // two branches instead of an explicit AND instruction with a
15729         // separate test. However, we only do this if this block doesn't
15730         // have a fall-through edge, because this requires an explicit
15731         // jmp when the condition is false.
15732         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15733             isX86LogicalCmp(Cmp) &&
15734             Op.getNode()->hasOneUse()) {
15735           X86::CondCode CCode =
15736             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15737           CCode = X86::GetOppositeBranchCondition(CCode);
15738           CC = DAG.getConstant(CCode, dl, MVT::i8);
15739           SDNode *User = *Op.getNode()->use_begin();
15740           // Look for an unconditional branch following this conditional branch.
15741           // We need this because we need to reverse the successors in order
15742           // to implement FCMP_OEQ.
15743           if (User->getOpcode() == ISD::BR) {
15744             SDValue FalseBB = User->getOperand(1);
15745             SDNode *NewBR =
15746               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15747             assert(NewBR == User);
15748             (void)NewBR;
15749             Dest = FalseBB;
15750
15751             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15752                                 Chain, Dest, CC, Cmp);
15753             X86::CondCode CCode =
15754               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15755             CCode = X86::GetOppositeBranchCondition(CCode);
15756             CC = DAG.getConstant(CCode, dl, MVT::i8);
15757             Cond = Cmp;
15758             addTest = false;
15759           }
15760         }
15761       }
15762     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15763       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15764       // It should be transformed during dag combiner except when the condition
15765       // is set by a arithmetics with overflow node.
15766       X86::CondCode CCode =
15767         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15768       CCode = X86::GetOppositeBranchCondition(CCode);
15769       CC = DAG.getConstant(CCode, dl, MVT::i8);
15770       Cond = Cond.getOperand(0).getOperand(1);
15771       addTest = false;
15772     } else if (Cond.getOpcode() == ISD::SETCC &&
15773                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15774       // For FCMP_OEQ, we can emit
15775       // two branches instead of an explicit AND instruction with a
15776       // separate test. However, we only do this if this block doesn't
15777       // have a fall-through edge, because this requires an explicit
15778       // jmp when the condition is false.
15779       if (Op.getNode()->hasOneUse()) {
15780         SDNode *User = *Op.getNode()->use_begin();
15781         // Look for an unconditional branch following this conditional branch.
15782         // We need this because we need to reverse the successors in order
15783         // to implement FCMP_OEQ.
15784         if (User->getOpcode() == ISD::BR) {
15785           SDValue FalseBB = User->getOperand(1);
15786           SDNode *NewBR =
15787             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15788           assert(NewBR == User);
15789           (void)NewBR;
15790           Dest = FalseBB;
15791
15792           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15793                                     Cond.getOperand(0), Cond.getOperand(1));
15794           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15795           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15796           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15797                               Chain, Dest, CC, Cmp);
15798           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15799           Cond = Cmp;
15800           addTest = false;
15801         }
15802       }
15803     } else if (Cond.getOpcode() == ISD::SETCC &&
15804                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15805       // For FCMP_UNE, we can emit
15806       // two branches instead of an explicit AND instruction with a
15807       // separate test. However, we only do this if this block doesn't
15808       // have a fall-through edge, because this requires an explicit
15809       // jmp when the condition is false.
15810       if (Op.getNode()->hasOneUse()) {
15811         SDNode *User = *Op.getNode()->use_begin();
15812         // Look for an unconditional branch following this conditional branch.
15813         // We need this because we need to reverse the successors in order
15814         // to implement FCMP_UNE.
15815         if (User->getOpcode() == ISD::BR) {
15816           SDValue FalseBB = User->getOperand(1);
15817           SDNode *NewBR =
15818             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15819           assert(NewBR == User);
15820           (void)NewBR;
15821
15822           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15823                                     Cond.getOperand(0), Cond.getOperand(1));
15824           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15825           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15826           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15827                               Chain, Dest, CC, Cmp);
15828           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15829           Cond = Cmp;
15830           addTest = false;
15831           Dest = FalseBB;
15832         }
15833       }
15834     }
15835   }
15836
15837   if (addTest) {
15838     // Look pass the truncate if the high bits are known zero.
15839     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15840         Cond = Cond.getOperand(0);
15841
15842     // We know the result of AND is compared against zero. Try to match
15843     // it to BT.
15844     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15845       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15846         CC = NewSetCC.getOperand(0);
15847         Cond = NewSetCC.getOperand(1);
15848         addTest = false;
15849       }
15850     }
15851   }
15852
15853   if (addTest) {
15854     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15855     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15856     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15857   }
15858   Cond = ConvertCmpIfNecessary(Cond, DAG);
15859   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15860                      Chain, Dest, CC, Cond);
15861 }
15862
15863 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15864 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15865 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15866 // that the guard pages used by the OS virtual memory manager are allocated in
15867 // correct sequence.
15868 SDValue
15869 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15870                                            SelectionDAG &DAG) const {
15871   MachineFunction &MF = DAG.getMachineFunction();
15872   bool SplitStack = MF.shouldSplitStack();
15873   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15874                SplitStack;
15875   SDLoc dl(Op);
15876
15877   // Get the inputs.
15878   SDNode *Node = Op.getNode();
15879   SDValue Chain = Op.getOperand(0);
15880   SDValue Size  = Op.getOperand(1);
15881   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15882   EVT VT = Node->getValueType(0);
15883
15884   // Chain the dynamic stack allocation so that it doesn't modify the stack
15885   // pointer when other instructions are using the stack.
15886   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15887
15888   bool Is64Bit = Subtarget->is64Bit();
15889   MVT SPTy = getPointerTy(DAG.getDataLayout());
15890
15891   SDValue Result;
15892   if (!Lower) {
15893     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15894     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15895     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15896                     " not tell us which reg is the stack pointer!");
15897     EVT VT = Node->getValueType(0);
15898     SDValue Tmp3 = Node->getOperand(2);
15899
15900     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15901     Chain = SP.getValue(1);
15902     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15903     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15904     unsigned StackAlign = TFI.getStackAlignment();
15905     Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15906     if (Align > StackAlign)
15907       Result = DAG.getNode(ISD::AND, dl, VT, Result,
15908                          DAG.getConstant(-(uint64_t)Align, dl, VT));
15909     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15910   } else if (SplitStack) {
15911     MachineRegisterInfo &MRI = MF.getRegInfo();
15912
15913     if (Is64Bit) {
15914       // The 64 bit implementation of segmented stacks needs to clobber both r10
15915       // r11. This makes it impossible to use it along with nested parameters.
15916       const Function *F = MF.getFunction();
15917
15918       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15919            I != E; ++I)
15920         if (I->hasNestAttr())
15921           report_fatal_error("Cannot use segmented stacks with functions that "
15922                              "have nested arguments.");
15923     }
15924
15925     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15926     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15927     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15928     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15929                                 DAG.getRegister(Vreg, SPTy));
15930   } else {
15931     SDValue Flag;
15932     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15933
15934     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15935     Flag = Chain.getValue(1);
15936     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15937
15938     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15939
15940     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15941     unsigned SPReg = RegInfo->getStackRegister();
15942     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15943     Chain = SP.getValue(1);
15944
15945     if (Align) {
15946       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15947                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15948       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15949     }
15950
15951     Result = SP;
15952   }
15953
15954   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15955                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
15956
15957   SDValue Ops[2] = {Result, Chain};
15958   return DAG.getMergeValues(Ops, dl);
15959 }
15960
15961 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15962   MachineFunction &MF = DAG.getMachineFunction();
15963   auto PtrVT = getPointerTy(MF.getDataLayout());
15964   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15965
15966   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15967   SDLoc DL(Op);
15968
15969   if (!Subtarget->is64Bit() ||
15970       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15971     // vastart just stores the address of the VarArgsFrameIndex slot into the
15972     // memory location argument.
15973     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15974     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15975                         MachinePointerInfo(SV), false, false, 0);
15976   }
15977
15978   // __va_list_tag:
15979   //   gp_offset         (0 - 6 * 8)
15980   //   fp_offset         (48 - 48 + 8 * 16)
15981   //   overflow_arg_area (point to parameters coming in memory).
15982   //   reg_save_area
15983   SmallVector<SDValue, 8> MemOps;
15984   SDValue FIN = Op.getOperand(1);
15985   // Store gp_offset
15986   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15987                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15988                                                DL, MVT::i32),
15989                                FIN, MachinePointerInfo(SV), false, false, 0);
15990   MemOps.push_back(Store);
15991
15992   // Store fp_offset
15993   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15994   Store = DAG.getStore(Op.getOperand(0), DL,
15995                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15996                                        MVT::i32),
15997                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15998   MemOps.push_back(Store);
15999
16000   // Store ptr to overflow_arg_area
16001   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16002   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16003   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16004                        MachinePointerInfo(SV, 8),
16005                        false, false, 0);
16006   MemOps.push_back(Store);
16007
16008   // Store ptr to reg_save_area.
16009   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
16010       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
16011   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
16012   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
16013       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
16014   MemOps.push_back(Store);
16015   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16016 }
16017
16018 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16019   assert(Subtarget->is64Bit() &&
16020          "LowerVAARG only handles 64-bit va_arg!");
16021   assert(Op.getNode()->getNumOperands() == 4);
16022
16023   MachineFunction &MF = DAG.getMachineFunction();
16024   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
16025     // The Win64 ABI uses char* instead of a structure.
16026     return DAG.expandVAArg(Op.getNode());
16027
16028   SDValue Chain = Op.getOperand(0);
16029   SDValue SrcPtr = Op.getOperand(1);
16030   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16031   unsigned Align = Op.getConstantOperandVal(3);
16032   SDLoc dl(Op);
16033
16034   EVT ArgVT = Op.getNode()->getValueType(0);
16035   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16036   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
16037   uint8_t ArgMode;
16038
16039   // Decide which area this value should be read from.
16040   // TODO: Implement the AMD64 ABI in its entirety. This simple
16041   // selection mechanism works only for the basic types.
16042   if (ArgVT == MVT::f80) {
16043     llvm_unreachable("va_arg for f80 not yet implemented");
16044   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16045     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16046   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16047     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16048   } else {
16049     llvm_unreachable("Unhandled argument type in LowerVAARG");
16050   }
16051
16052   if (ArgMode == 2) {
16053     // Sanity Check: Make sure using fp_offset makes sense.
16054     assert(!Subtarget->useSoftFloat() &&
16055            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
16056            Subtarget->hasSSE1());
16057   }
16058
16059   // Insert VAARG_64 node into the DAG
16060   // VAARG_64 returns two values: Variable Argument Address, Chain
16061   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
16062                        DAG.getConstant(ArgMode, dl, MVT::i8),
16063                        DAG.getConstant(Align, dl, MVT::i32)};
16064   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
16065   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16066                                           VTs, InstOps, MVT::i64,
16067                                           MachinePointerInfo(SV),
16068                                           /*Align=*/0,
16069                                           /*Volatile=*/false,
16070                                           /*ReadMem=*/true,
16071                                           /*WriteMem=*/true);
16072   Chain = VAARG.getValue(1);
16073
16074   // Load the next argument and return it
16075   return DAG.getLoad(ArgVT, dl,
16076                      Chain,
16077                      VAARG,
16078                      MachinePointerInfo(),
16079                      false, false, false, 0);
16080 }
16081
16082 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16083                            SelectionDAG &DAG) {
16084   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
16085   // where a va_list is still an i8*.
16086   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16087   if (Subtarget->isCallingConvWin64(
16088         DAG.getMachineFunction().getFunction()->getCallingConv()))
16089     // Probably a Win64 va_copy.
16090     return DAG.expandVACopy(Op.getNode());
16091
16092   SDValue Chain = Op.getOperand(0);
16093   SDValue DstPtr = Op.getOperand(1);
16094   SDValue SrcPtr = Op.getOperand(2);
16095   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16096   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16097   SDLoc DL(Op);
16098
16099   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16100                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
16101                        false, false,
16102                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16103 }
16104
16105 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16106 // amount is a constant. Takes immediate version of shift as input.
16107 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16108                                           SDValue SrcOp, uint64_t ShiftAmt,
16109                                           SelectionDAG &DAG) {
16110   MVT ElementType = VT.getVectorElementType();
16111
16112   // Fold this packed shift into its first operand if ShiftAmt is 0.
16113   if (ShiftAmt == 0)
16114     return SrcOp;
16115
16116   // Check for ShiftAmt >= element width
16117   if (ShiftAmt >= ElementType.getSizeInBits()) {
16118     if (Opc == X86ISD::VSRAI)
16119       ShiftAmt = ElementType.getSizeInBits() - 1;
16120     else
16121       return DAG.getConstant(0, dl, VT);
16122   }
16123
16124   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16125          && "Unknown target vector shift-by-constant node");
16126
16127   // Fold this packed vector shift into a build vector if SrcOp is a
16128   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16129   if (VT == SrcOp.getSimpleValueType() &&
16130       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16131     SmallVector<SDValue, 8> Elts;
16132     unsigned NumElts = SrcOp->getNumOperands();
16133     ConstantSDNode *ND;
16134
16135     switch(Opc) {
16136     default: llvm_unreachable(nullptr);
16137     case X86ISD::VSHLI:
16138       for (unsigned i=0; i!=NumElts; ++i) {
16139         SDValue CurrentOp = SrcOp->getOperand(i);
16140         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16141           Elts.push_back(CurrentOp);
16142           continue;
16143         }
16144         ND = cast<ConstantSDNode>(CurrentOp);
16145         const APInt &C = ND->getAPIntValue();
16146         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
16147       }
16148       break;
16149     case X86ISD::VSRLI:
16150       for (unsigned i=0; i!=NumElts; ++i) {
16151         SDValue CurrentOp = SrcOp->getOperand(i);
16152         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16153           Elts.push_back(CurrentOp);
16154           continue;
16155         }
16156         ND = cast<ConstantSDNode>(CurrentOp);
16157         const APInt &C = ND->getAPIntValue();
16158         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
16159       }
16160       break;
16161     case X86ISD::VSRAI:
16162       for (unsigned i=0; i!=NumElts; ++i) {
16163         SDValue CurrentOp = SrcOp->getOperand(i);
16164         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16165           Elts.push_back(CurrentOp);
16166           continue;
16167         }
16168         ND = cast<ConstantSDNode>(CurrentOp);
16169         const APInt &C = ND->getAPIntValue();
16170         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
16171       }
16172       break;
16173     }
16174
16175     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16176   }
16177
16178   return DAG.getNode(Opc, dl, VT, SrcOp,
16179                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
16180 }
16181
16182 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16183 // may or may not be a constant. Takes immediate version of shift as input.
16184 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16185                                    SDValue SrcOp, SDValue ShAmt,
16186                                    SelectionDAG &DAG) {
16187   MVT SVT = ShAmt.getSimpleValueType();
16188   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16189
16190   // Catch shift-by-constant.
16191   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16192     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16193                                       CShAmt->getZExtValue(), DAG);
16194
16195   // Change opcode to non-immediate version
16196   switch (Opc) {
16197     default: llvm_unreachable("Unknown target vector shift node");
16198     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16199     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16200     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16201   }
16202
16203   const X86Subtarget &Subtarget =
16204       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16205   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16206       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16207     // Let the shuffle legalizer expand this shift amount node.
16208     SDValue Op0 = ShAmt.getOperand(0);
16209     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16210     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16211   } else {
16212     // Need to build a vector containing shift amount.
16213     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16214     SmallVector<SDValue, 4> ShOps;
16215     ShOps.push_back(ShAmt);
16216     if (SVT == MVT::i32) {
16217       ShOps.push_back(DAG.getConstant(0, dl, SVT));
16218       ShOps.push_back(DAG.getUNDEF(SVT));
16219     }
16220     ShOps.push_back(DAG.getUNDEF(SVT));
16221
16222     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16223     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16224   }
16225
16226   // The return type has to be a 128-bit type with the same element
16227   // type as the input type.
16228   MVT EltVT = VT.getVectorElementType();
16229   MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16230
16231   ShAmt = DAG.getBitcast(ShVT, ShAmt);
16232   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16233 }
16234
16235 /// \brief Return Mask with the necessary casting or extending
16236 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16237 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16238                            const X86Subtarget *Subtarget,
16239                            SelectionDAG &DAG, SDLoc dl) {
16240
16241   if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16242     // Mask should be extended
16243     Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16244                        MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16245   }
16246
16247   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16248     if (MaskVT == MVT::v64i1) {
16249       assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16250       // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16251       SDValue Lo, Hi;
16252       Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16253                           DAG.getConstant(0, dl, MVT::i32));
16254       Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16255                           DAG.getConstant(1, dl, MVT::i32));
16256
16257       Lo = DAG.getBitcast(MVT::v32i1, Lo);
16258       Hi = DAG.getBitcast(MVT::v32i1, Hi);
16259
16260       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16261     } else {
16262       // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16263       // and bitcast.
16264       MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16265       return DAG.getBitcast(MaskVT,
16266                             DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16267     }
16268
16269   } else {
16270     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16271                                      Mask.getSimpleValueType().getSizeInBits());
16272     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16273     // are extracted by EXTRACT_SUBVECTOR.
16274     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16275                        DAG.getBitcast(BitcastVT, Mask),
16276                        DAG.getIntPtrConstant(0, dl));
16277   }
16278 }
16279
16280 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16281 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16282 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16283 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16284                   SDValue PreservedSrc,
16285                   const X86Subtarget *Subtarget,
16286                   SelectionDAG &DAG) {
16287   MVT VT = Op.getSimpleValueType();
16288   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16289   unsigned OpcodeSelect = ISD::VSELECT;
16290   SDLoc dl(Op);
16291
16292   if (isAllOnesConstant(Mask))
16293     return Op;
16294
16295   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16296
16297   switch (Op.getOpcode()) {
16298   default: break;
16299   case X86ISD::PCMPEQM:
16300   case X86ISD::PCMPGTM:
16301   case X86ISD::CMPM:
16302   case X86ISD::CMPMU:
16303     return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16304   case X86ISD::VFPCLASS:
16305     case X86ISD::VFPCLASSS:
16306     return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16307   case X86ISD::VTRUNC:
16308   case X86ISD::VTRUNCS:
16309   case X86ISD::VTRUNCUS:
16310     // We can't use ISD::VSELECT here because it is not always "Legal"
16311     // for the destination type. For example vpmovqb require only AVX512
16312     // and vselect that can operate on byte element type require BWI
16313     OpcodeSelect = X86ISD::SELECT;
16314     break;
16315   }
16316   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16317     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16318   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16319 }
16320
16321 /// \brief Creates an SDNode for a predicated scalar operation.
16322 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16323 /// The mask is coming as MVT::i8 and it should be truncated
16324 /// to MVT::i1 while lowering masking intrinsics.
16325 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16326 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16327 /// for a scalar instruction.
16328 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16329                                     SDValue PreservedSrc,
16330                                     const X86Subtarget *Subtarget,
16331                                     SelectionDAG &DAG) {
16332   if (isAllOnesConstant(Mask))
16333     return Op;
16334
16335   MVT VT = Op.getSimpleValueType();
16336   SDLoc dl(Op);
16337   // The mask should be of type MVT::i1
16338   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16339
16340   if (Op.getOpcode() == X86ISD::FSETCC)
16341     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16342   if (Op.getOpcode() == X86ISD::VFPCLASS ||
16343       Op.getOpcode() == X86ISD::VFPCLASSS)
16344     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16345
16346   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16347     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16348   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16349 }
16350
16351 static int getSEHRegistrationNodeSize(const Function *Fn) {
16352   if (!Fn->hasPersonalityFn())
16353     report_fatal_error(
16354         "querying registration node size for function without personality");
16355   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16356   // WinEHStatePass for the full struct definition.
16357   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16358   case EHPersonality::MSVC_X86SEH: return 24;
16359   case EHPersonality::MSVC_CXX: return 16;
16360   default: break;
16361   }
16362   report_fatal_error(
16363       "can only recover FP for 32-bit MSVC EH personality functions");
16364 }
16365
16366 /// When the MSVC runtime transfers control to us, either to an outlined
16367 /// function or when returning to a parent frame after catching an exception, we
16368 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16369 /// Here's the math:
16370 ///   RegNodeBase = EntryEBP - RegNodeSize
16371 ///   ParentFP = RegNodeBase - ParentFrameOffset
16372 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16373 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16374 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16375                                    SDValue EntryEBP) {
16376   MachineFunction &MF = DAG.getMachineFunction();
16377   SDLoc dl;
16378
16379   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16380   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16381
16382   // It's possible that the parent function no longer has a personality function
16383   // if the exceptional code was optimized away, in which case we just return
16384   // the incoming EBP.
16385   if (!Fn->hasPersonalityFn())
16386     return EntryEBP;
16387
16388   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16389   // registration, or the .set_setframe offset.
16390   MCSymbol *OffsetSym =
16391       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16392           GlobalValue::getRealLinkageName(Fn->getName()));
16393   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16394   SDValue ParentFrameOffset =
16395       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16396
16397   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
16398   // prologue to RBP in the parent function.
16399   const X86Subtarget &Subtarget =
16400       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16401   if (Subtarget.is64Bit())
16402     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
16403
16404   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16405   // RegNodeBase = EntryEBP - RegNodeSize
16406   // ParentFP = RegNodeBase - ParentFrameOffset
16407   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16408                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16409   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
16410 }
16411
16412 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16413                                        SelectionDAG &DAG) {
16414   SDLoc dl(Op);
16415   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16416   MVT VT = Op.getSimpleValueType();
16417   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16418   if (IntrData) {
16419     switch(IntrData->Type) {
16420     case INTR_TYPE_1OP:
16421       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16422     case INTR_TYPE_2OP:
16423       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16424         Op.getOperand(2));
16425     case INTR_TYPE_2OP_IMM8:
16426       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16427                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16428     case INTR_TYPE_3OP:
16429       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16430         Op.getOperand(2), Op.getOperand(3));
16431     case INTR_TYPE_4OP:
16432       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16433         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16434     case INTR_TYPE_1OP_MASK_RM: {
16435       SDValue Src = Op.getOperand(1);
16436       SDValue PassThru = Op.getOperand(2);
16437       SDValue Mask = Op.getOperand(3);
16438       SDValue RoundingMode;
16439       // We allways add rounding mode to the Node.
16440       // If the rounding mode is not specified, we add the
16441       // "current direction" mode.
16442       if (Op.getNumOperands() == 4)
16443         RoundingMode =
16444           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16445       else
16446         RoundingMode = Op.getOperand(4);
16447       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16448       if (IntrWithRoundingModeOpcode != 0)
16449         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16450             X86::STATIC_ROUNDING::CUR_DIRECTION)
16451           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16452                                       dl, Op.getValueType(), Src, RoundingMode),
16453                                       Mask, PassThru, Subtarget, DAG);
16454       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16455                                               RoundingMode),
16456                                   Mask, PassThru, Subtarget, DAG);
16457     }
16458     case INTR_TYPE_1OP_MASK: {
16459       SDValue Src = Op.getOperand(1);
16460       SDValue PassThru = Op.getOperand(2);
16461       SDValue Mask = Op.getOperand(3);
16462       // We add rounding mode to the Node when
16463       //   - RM Opcode is specified and
16464       //   - RM is not "current direction".
16465       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16466       if (IntrWithRoundingModeOpcode != 0) {
16467         SDValue Rnd = Op.getOperand(4);
16468         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16469         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16470           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16471                                       dl, Op.getValueType(),
16472                                       Src, Rnd),
16473                                       Mask, PassThru, Subtarget, DAG);
16474         }
16475       }
16476       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16477                                   Mask, PassThru, Subtarget, DAG);
16478     }
16479     case INTR_TYPE_SCALAR_MASK: {
16480       SDValue Src1 = Op.getOperand(1);
16481       SDValue Src2 = Op.getOperand(2);
16482       SDValue passThru = Op.getOperand(3);
16483       SDValue Mask = Op.getOperand(4);
16484       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16485                                   Mask, passThru, Subtarget, DAG);
16486     }
16487     case INTR_TYPE_SCALAR_MASK_RM: {
16488       SDValue Src1 = Op.getOperand(1);
16489       SDValue Src2 = Op.getOperand(2);
16490       SDValue Src0 = Op.getOperand(3);
16491       SDValue Mask = Op.getOperand(4);
16492       // There are 2 kinds of intrinsics in this group:
16493       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16494       // (2) With rounding mode and sae - 7 operands.
16495       if (Op.getNumOperands() == 6) {
16496         SDValue Sae  = Op.getOperand(5);
16497         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16498         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16499                                                 Sae),
16500                                     Mask, Src0, Subtarget, DAG);
16501       }
16502       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16503       SDValue RoundingMode  = Op.getOperand(5);
16504       SDValue Sae  = Op.getOperand(6);
16505       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16506                                               RoundingMode, Sae),
16507                                   Mask, Src0, Subtarget, DAG);
16508     }
16509     case INTR_TYPE_2OP_MASK:
16510     case INTR_TYPE_2OP_IMM8_MASK: {
16511       SDValue Src1 = Op.getOperand(1);
16512       SDValue Src2 = Op.getOperand(2);
16513       SDValue PassThru = Op.getOperand(3);
16514       SDValue Mask = Op.getOperand(4);
16515
16516       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16517         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16518
16519       // We specify 2 possible opcodes for intrinsics with rounding modes.
16520       // First, we check if the intrinsic may have non-default rounding mode,
16521       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16522       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16523       if (IntrWithRoundingModeOpcode != 0) {
16524         SDValue Rnd = Op.getOperand(5);
16525         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16526         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16527           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16528                                       dl, Op.getValueType(),
16529                                       Src1, Src2, Rnd),
16530                                       Mask, PassThru, Subtarget, DAG);
16531         }
16532       }
16533       // TODO: Intrinsics should have fast-math-flags to propagate.
16534       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16535                                   Mask, PassThru, Subtarget, DAG);
16536     }
16537     case INTR_TYPE_2OP_MASK_RM: {
16538       SDValue Src1 = Op.getOperand(1);
16539       SDValue Src2 = Op.getOperand(2);
16540       SDValue PassThru = Op.getOperand(3);
16541       SDValue Mask = Op.getOperand(4);
16542       // We specify 2 possible modes for intrinsics, with/without rounding
16543       // modes.
16544       // First, we check if the intrinsic have rounding mode (6 operands),
16545       // if not, we set rounding mode to "current".
16546       SDValue Rnd;
16547       if (Op.getNumOperands() == 6)
16548         Rnd = Op.getOperand(5);
16549       else
16550         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16551       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16552                                               Src1, Src2, Rnd),
16553                                   Mask, PassThru, Subtarget, DAG);
16554     }
16555     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16556       SDValue Src1 = Op.getOperand(1);
16557       SDValue Src2 = Op.getOperand(2);
16558       SDValue Src3 = Op.getOperand(3);
16559       SDValue PassThru = Op.getOperand(4);
16560       SDValue Mask = Op.getOperand(5);
16561       SDValue Sae  = Op.getOperand(6);
16562
16563       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16564                                               Src2, Src3, Sae),
16565                                   Mask, PassThru, Subtarget, DAG);
16566     }
16567     case INTR_TYPE_3OP_MASK_RM: {
16568       SDValue Src1 = Op.getOperand(1);
16569       SDValue Src2 = Op.getOperand(2);
16570       SDValue Imm = Op.getOperand(3);
16571       SDValue PassThru = Op.getOperand(4);
16572       SDValue Mask = Op.getOperand(5);
16573       // We specify 2 possible modes for intrinsics, with/without rounding
16574       // modes.
16575       // First, we check if the intrinsic have rounding mode (7 operands),
16576       // if not, we set rounding mode to "current".
16577       SDValue Rnd;
16578       if (Op.getNumOperands() == 7)
16579         Rnd = Op.getOperand(6);
16580       else
16581         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16582       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16583         Src1, Src2, Imm, Rnd),
16584         Mask, PassThru, Subtarget, DAG);
16585     }
16586     case INTR_TYPE_3OP_IMM8_MASK:
16587     case INTR_TYPE_3OP_MASK:
16588     case INSERT_SUBVEC: {
16589       SDValue Src1 = Op.getOperand(1);
16590       SDValue Src2 = Op.getOperand(2);
16591       SDValue Src3 = Op.getOperand(3);
16592       SDValue PassThru = Op.getOperand(4);
16593       SDValue Mask = Op.getOperand(5);
16594
16595       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16596         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16597       else if (IntrData->Type == INSERT_SUBVEC) {
16598         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16599         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16600         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16601         Imm *= Src2.getSimpleValueType().getVectorNumElements();
16602         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16603       }
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(6);
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, Src3, Rnd),
16616                                       Mask, PassThru, Subtarget, DAG);
16617         }
16618       }
16619       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16620                                               Src1, Src2, Src3),
16621                                   Mask, PassThru, Subtarget, DAG);
16622     }
16623     case VPERM_3OP_MASKZ:
16624     case VPERM_3OP_MASK:{
16625       // Src2 is the PassThru
16626       SDValue Src1 = Op.getOperand(1);
16627       SDValue Src2 = Op.getOperand(2);
16628       SDValue Src3 = Op.getOperand(3);
16629       SDValue Mask = Op.getOperand(4);
16630       MVT VT = Op.getSimpleValueType();
16631       SDValue PassThru = SDValue();
16632
16633       // set PassThru element
16634       if (IntrData->Type == VPERM_3OP_MASKZ)
16635         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16636       else
16637         PassThru = DAG.getBitcast(VT, Src2);
16638
16639       // Swap Src1 and Src2 in the node creation
16640       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16641                                               dl, Op.getValueType(),
16642                                               Src2, Src1, Src3),
16643                                   Mask, PassThru, Subtarget, DAG);
16644     }
16645     case FMA_OP_MASK3:
16646     case FMA_OP_MASKZ:
16647     case FMA_OP_MASK: {
16648       SDValue Src1 = Op.getOperand(1);
16649       SDValue Src2 = Op.getOperand(2);
16650       SDValue Src3 = Op.getOperand(3);
16651       SDValue Mask = Op.getOperand(4);
16652       MVT VT = Op.getSimpleValueType();
16653       SDValue PassThru = SDValue();
16654
16655       // set PassThru element
16656       if (IntrData->Type == FMA_OP_MASKZ)
16657         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16658       else if (IntrData->Type == FMA_OP_MASK3)
16659         PassThru = Src3;
16660       else
16661         PassThru = Src1;
16662
16663       // We specify 2 possible opcodes for intrinsics with rounding modes.
16664       // First, we check if the intrinsic may have non-default rounding mode,
16665       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16666       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16667       if (IntrWithRoundingModeOpcode != 0) {
16668         SDValue Rnd = Op.getOperand(5);
16669         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16670             X86::STATIC_ROUNDING::CUR_DIRECTION)
16671           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16672                                                   dl, Op.getValueType(),
16673                                                   Src1, Src2, Src3, Rnd),
16674                                       Mask, PassThru, Subtarget, DAG);
16675       }
16676       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16677                                               dl, Op.getValueType(),
16678                                               Src1, Src2, Src3),
16679                                   Mask, PassThru, Subtarget, DAG);
16680     }
16681     case TERLOG_OP_MASK:
16682     case TERLOG_OP_MASKZ: {
16683       SDValue Src1 = Op.getOperand(1);
16684       SDValue Src2 = Op.getOperand(2);
16685       SDValue Src3 = Op.getOperand(3);
16686       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16687       SDValue Mask = Op.getOperand(5);
16688       MVT VT = Op.getSimpleValueType();
16689       SDValue PassThru = Src1;
16690       // Set PassThru element.
16691       if (IntrData->Type == TERLOG_OP_MASKZ)
16692         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16693
16694       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16695                                               Src1, Src2, Src3, Src4),
16696                                   Mask, PassThru, Subtarget, DAG);
16697     }
16698     case FPCLASS: {
16699       // FPclass intrinsics with mask
16700        SDValue Src1 = Op.getOperand(1);
16701        MVT VT = Src1.getSimpleValueType();
16702        MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16703        SDValue Imm = Op.getOperand(2);
16704        SDValue Mask = Op.getOperand(3);
16705        MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16706                                      Mask.getSimpleValueType().getSizeInBits());
16707        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16708        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16709                                                  DAG.getTargetConstant(0, dl, MaskVT),
16710                                                  Subtarget, DAG);
16711        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16712                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16713                                  DAG.getIntPtrConstant(0, dl));
16714        return DAG.getBitcast(Op.getValueType(), Res);
16715     }
16716     case FPCLASSS: {
16717       SDValue Src1 = Op.getOperand(1);
16718       SDValue Imm = Op.getOperand(2);
16719       SDValue Mask = Op.getOperand(3);
16720       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16721       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16722         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16723       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16724     }
16725     case CMP_MASK:
16726     case CMP_MASK_CC: {
16727       // Comparison intrinsics with masks.
16728       // Example of transformation:
16729       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16730       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16731       // (i8 (bitcast
16732       //   (v8i1 (insert_subvector undef,
16733       //           (v2i1 (and (PCMPEQM %a, %b),
16734       //                      (extract_subvector
16735       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16736       MVT VT = Op.getOperand(1).getSimpleValueType();
16737       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16738       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16739       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16740                                        Mask.getSimpleValueType().getSizeInBits());
16741       SDValue Cmp;
16742       if (IntrData->Type == CMP_MASK_CC) {
16743         SDValue CC = Op.getOperand(3);
16744         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16745         // We specify 2 possible opcodes for intrinsics with rounding modes.
16746         // First, we check if the intrinsic may have non-default rounding mode,
16747         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16748         if (IntrData->Opc1 != 0) {
16749           SDValue Rnd = Op.getOperand(5);
16750           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16751               X86::STATIC_ROUNDING::CUR_DIRECTION)
16752             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16753                               Op.getOperand(2), CC, Rnd);
16754         }
16755         //default rounding mode
16756         if(!Cmp.getNode())
16757             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16758                               Op.getOperand(2), CC);
16759
16760       } else {
16761         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16762         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16763                           Op.getOperand(2));
16764       }
16765       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16766                                              DAG.getTargetConstant(0, dl,
16767                                                                    MaskVT),
16768                                              Subtarget, DAG);
16769       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16770                                 DAG.getUNDEF(BitcastVT), CmpMask,
16771                                 DAG.getIntPtrConstant(0, dl));
16772       return DAG.getBitcast(Op.getValueType(), Res);
16773     }
16774     case CMP_MASK_SCALAR_CC: {
16775       SDValue Src1 = Op.getOperand(1);
16776       SDValue Src2 = Op.getOperand(2);
16777       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16778       SDValue Mask = Op.getOperand(4);
16779
16780       SDValue Cmp;
16781       if (IntrData->Opc1 != 0) {
16782         SDValue Rnd = Op.getOperand(5);
16783         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16784             X86::STATIC_ROUNDING::CUR_DIRECTION)
16785           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16786       }
16787       //default rounding mode
16788       if(!Cmp.getNode())
16789         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16790
16791       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16792                                              DAG.getTargetConstant(0, dl,
16793                                                                    MVT::i1),
16794                                              Subtarget, DAG);
16795
16796       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16797                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16798                          DAG.getValueType(MVT::i1));
16799     }
16800     case COMI: { // Comparison intrinsics
16801       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16802       SDValue LHS = Op.getOperand(1);
16803       SDValue RHS = Op.getOperand(2);
16804       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16805       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16806       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16807       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16808                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16809       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16810     }
16811     case COMI_RM: { // Comparison intrinsics with Sae
16812       SDValue LHS = Op.getOperand(1);
16813       SDValue RHS = Op.getOperand(2);
16814       SDValue CC = Op.getOperand(3);
16815       SDValue Sae = Op.getOperand(4);
16816       auto ComiType = TranslateX86ConstCondToX86CC(CC);
16817       // choose between ordered and unordered (comi/ucomi)
16818       unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16819       SDValue Cond;
16820       if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16821                                            X86::STATIC_ROUNDING::CUR_DIRECTION)
16822         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16823       else
16824         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16825       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16826         DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16827       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16828     }
16829     case VSHIFT:
16830       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16831                                  Op.getOperand(1), Op.getOperand(2), DAG);
16832     case VSHIFT_MASK:
16833       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16834                                                       Op.getSimpleValueType(),
16835                                                       Op.getOperand(1),
16836                                                       Op.getOperand(2), DAG),
16837                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16838                                   DAG);
16839     case COMPRESS_EXPAND_IN_REG: {
16840       SDValue Mask = Op.getOperand(3);
16841       SDValue DataToCompress = Op.getOperand(1);
16842       SDValue PassThru = Op.getOperand(2);
16843       if (isAllOnesConstant(Mask)) // return data as is
16844         return Op.getOperand(1);
16845
16846       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16847                                               DataToCompress),
16848                                   Mask, PassThru, Subtarget, DAG);
16849     }
16850     case BROADCASTM: {
16851       SDValue Mask = Op.getOperand(1);
16852       MVT MaskVT = MVT::getVectorVT(MVT::i1,
16853                                     Mask.getSimpleValueType().getSizeInBits());
16854       Mask = DAG.getBitcast(MaskVT, Mask);
16855       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16856     }
16857     case BLEND: {
16858       SDValue Mask = Op.getOperand(3);
16859       MVT VT = Op.getSimpleValueType();
16860       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16861       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16862       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16863                          Op.getOperand(2));
16864     }
16865     case KUNPCK: {
16866       MVT VT = Op.getSimpleValueType();
16867       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16868
16869       SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16870       SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16871       // Arguments should be swapped.
16872       SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16873                                 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16874                                 Src2, Src1);
16875       return DAG.getBitcast(VT, Res);
16876     }
16877     case CONVERT_TO_MASK: {
16878       MVT SrcVT = Op.getOperand(1).getSimpleValueType();
16879       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
16880       MVT BitcastVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits());
16881
16882       SDValue CvtMask = DAG.getNode(IntrData->Opc0, dl, MaskVT,
16883                                     Op.getOperand(1));
16884       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16885                                 DAG.getUNDEF(BitcastVT), CvtMask,
16886                                 DAG.getIntPtrConstant(0, dl));
16887       return DAG.getBitcast(Op.getValueType(), Res);
16888     }
16889     case CONVERT_MASK_TO_VEC: {
16890       SDValue Mask = Op.getOperand(1);
16891       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16892       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16893       return DAG.getNode(IntrData->Opc0, dl, VT, VMask);
16894     }
16895     case BRCST_SUBVEC_TO_VEC: {
16896       SDValue Src = Op.getOperand(1);
16897       SDValue Passthru = Op.getOperand(2);
16898       SDValue Mask = Op.getOperand(3);
16899       EVT resVT = Passthru.getValueType();
16900       SDValue subVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, resVT,
16901                                        DAG.getUNDEF(resVT), Src,
16902                                        DAG.getIntPtrConstant(0, dl));
16903       SDValue immVal;
16904       if (Src.getSimpleValueType().is256BitVector() && resVT.is512BitVector())
16905         immVal = DAG.getConstant(0x44, dl, MVT::i8);
16906       else
16907         immVal = DAG.getConstant(0, dl, MVT::i8);
16908       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16909                                               subVec, subVec, immVal),
16910                                   Mask, Passthru, Subtarget, DAG);
16911     }
16912     default:
16913       break;
16914     }
16915   }
16916
16917   switch (IntNo) {
16918   default: return SDValue();    // Don't custom lower most intrinsics.
16919
16920   case Intrinsic::x86_avx2_permd:
16921   case Intrinsic::x86_avx2_permps:
16922     // Operands intentionally swapped. Mask is last operand to intrinsic,
16923     // but second operand for node/instruction.
16924     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16925                        Op.getOperand(2), Op.getOperand(1));
16926
16927   // ptest and testp intrinsics. The intrinsic these come from are designed to
16928   // return an integer value, not just an instruction so lower it to the ptest
16929   // or testp pattern and a setcc for the result.
16930   case Intrinsic::x86_sse41_ptestz:
16931   case Intrinsic::x86_sse41_ptestc:
16932   case Intrinsic::x86_sse41_ptestnzc:
16933   case Intrinsic::x86_avx_ptestz_256:
16934   case Intrinsic::x86_avx_ptestc_256:
16935   case Intrinsic::x86_avx_ptestnzc_256:
16936   case Intrinsic::x86_avx_vtestz_ps:
16937   case Intrinsic::x86_avx_vtestc_ps:
16938   case Intrinsic::x86_avx_vtestnzc_ps:
16939   case Intrinsic::x86_avx_vtestz_pd:
16940   case Intrinsic::x86_avx_vtestc_pd:
16941   case Intrinsic::x86_avx_vtestnzc_pd:
16942   case Intrinsic::x86_avx_vtestz_ps_256:
16943   case Intrinsic::x86_avx_vtestc_ps_256:
16944   case Intrinsic::x86_avx_vtestnzc_ps_256:
16945   case Intrinsic::x86_avx_vtestz_pd_256:
16946   case Intrinsic::x86_avx_vtestc_pd_256:
16947   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16948     bool IsTestPacked = false;
16949     unsigned X86CC;
16950     switch (IntNo) {
16951     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16952     case Intrinsic::x86_avx_vtestz_ps:
16953     case Intrinsic::x86_avx_vtestz_pd:
16954     case Intrinsic::x86_avx_vtestz_ps_256:
16955     case Intrinsic::x86_avx_vtestz_pd_256:
16956       IsTestPacked = true; // Fallthrough
16957     case Intrinsic::x86_sse41_ptestz:
16958     case Intrinsic::x86_avx_ptestz_256:
16959       // ZF = 1
16960       X86CC = X86::COND_E;
16961       break;
16962     case Intrinsic::x86_avx_vtestc_ps:
16963     case Intrinsic::x86_avx_vtestc_pd:
16964     case Intrinsic::x86_avx_vtestc_ps_256:
16965     case Intrinsic::x86_avx_vtestc_pd_256:
16966       IsTestPacked = true; // Fallthrough
16967     case Intrinsic::x86_sse41_ptestc:
16968     case Intrinsic::x86_avx_ptestc_256:
16969       // CF = 1
16970       X86CC = X86::COND_B;
16971       break;
16972     case Intrinsic::x86_avx_vtestnzc_ps:
16973     case Intrinsic::x86_avx_vtestnzc_pd:
16974     case Intrinsic::x86_avx_vtestnzc_ps_256:
16975     case Intrinsic::x86_avx_vtestnzc_pd_256:
16976       IsTestPacked = true; // Fallthrough
16977     case Intrinsic::x86_sse41_ptestnzc:
16978     case Intrinsic::x86_avx_ptestnzc_256:
16979       // ZF and CF = 0
16980       X86CC = X86::COND_A;
16981       break;
16982     }
16983
16984     SDValue LHS = Op.getOperand(1);
16985     SDValue RHS = Op.getOperand(2);
16986     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16987     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16988     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16989     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16990     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16991   }
16992   case Intrinsic::x86_avx512_kortestz_w:
16993   case Intrinsic::x86_avx512_kortestc_w: {
16994     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16995     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16996     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16997     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16998     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16999     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17000     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17001   }
17002
17003   case Intrinsic::x86_sse42_pcmpistria128:
17004   case Intrinsic::x86_sse42_pcmpestria128:
17005   case Intrinsic::x86_sse42_pcmpistric128:
17006   case Intrinsic::x86_sse42_pcmpestric128:
17007   case Intrinsic::x86_sse42_pcmpistrio128:
17008   case Intrinsic::x86_sse42_pcmpestrio128:
17009   case Intrinsic::x86_sse42_pcmpistris128:
17010   case Intrinsic::x86_sse42_pcmpestris128:
17011   case Intrinsic::x86_sse42_pcmpistriz128:
17012   case Intrinsic::x86_sse42_pcmpestriz128: {
17013     unsigned Opcode;
17014     unsigned X86CC;
17015     switch (IntNo) {
17016     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17017     case Intrinsic::x86_sse42_pcmpistria128:
17018       Opcode = X86ISD::PCMPISTRI;
17019       X86CC = X86::COND_A;
17020       break;
17021     case Intrinsic::x86_sse42_pcmpestria128:
17022       Opcode = X86ISD::PCMPESTRI;
17023       X86CC = X86::COND_A;
17024       break;
17025     case Intrinsic::x86_sse42_pcmpistric128:
17026       Opcode = X86ISD::PCMPISTRI;
17027       X86CC = X86::COND_B;
17028       break;
17029     case Intrinsic::x86_sse42_pcmpestric128:
17030       Opcode = X86ISD::PCMPESTRI;
17031       X86CC = X86::COND_B;
17032       break;
17033     case Intrinsic::x86_sse42_pcmpistrio128:
17034       Opcode = X86ISD::PCMPISTRI;
17035       X86CC = X86::COND_O;
17036       break;
17037     case Intrinsic::x86_sse42_pcmpestrio128:
17038       Opcode = X86ISD::PCMPESTRI;
17039       X86CC = X86::COND_O;
17040       break;
17041     case Intrinsic::x86_sse42_pcmpistris128:
17042       Opcode = X86ISD::PCMPISTRI;
17043       X86CC = X86::COND_S;
17044       break;
17045     case Intrinsic::x86_sse42_pcmpestris128:
17046       Opcode = X86ISD::PCMPESTRI;
17047       X86CC = X86::COND_S;
17048       break;
17049     case Intrinsic::x86_sse42_pcmpistriz128:
17050       Opcode = X86ISD::PCMPISTRI;
17051       X86CC = X86::COND_E;
17052       break;
17053     case Intrinsic::x86_sse42_pcmpestriz128:
17054       Opcode = X86ISD::PCMPESTRI;
17055       X86CC = X86::COND_E;
17056       break;
17057     }
17058     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17059     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17060     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17061     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17062                                 DAG.getConstant(X86CC, dl, MVT::i8),
17063                                 SDValue(PCMP.getNode(), 1));
17064     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17065   }
17066
17067   case Intrinsic::x86_sse42_pcmpistri128:
17068   case Intrinsic::x86_sse42_pcmpestri128: {
17069     unsigned Opcode;
17070     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17071       Opcode = X86ISD::PCMPISTRI;
17072     else
17073       Opcode = X86ISD::PCMPESTRI;
17074
17075     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17076     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17077     return DAG.getNode(Opcode, dl, VTs, NewOps);
17078   }
17079
17080   case Intrinsic::x86_seh_lsda: {
17081     // Compute the symbol for the LSDA. We know it'll get emitted later.
17082     MachineFunction &MF = DAG.getMachineFunction();
17083     SDValue Op1 = Op.getOperand(1);
17084     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
17085     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
17086         GlobalValue::getRealLinkageName(Fn->getName()));
17087
17088     // Generate a simple absolute symbol reference. This intrinsic is only
17089     // supported on 32-bit Windows, which isn't PIC.
17090     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
17091     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
17092   }
17093
17094   case Intrinsic::x86_seh_recoverfp: {
17095     SDValue FnOp = Op.getOperand(1);
17096     SDValue IncomingFPOp = Op.getOperand(2);
17097     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
17098     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
17099     if (!Fn)
17100       report_fatal_error(
17101           "llvm.x86.seh.recoverfp must take a function as the first argument");
17102     return recoverFramePointer(DAG, Fn, IncomingFPOp);
17103   }
17104
17105   case Intrinsic::localaddress: {
17106     // Returns one of the stack, base, or frame pointer registers, depending on
17107     // which is used to reference local variables.
17108     MachineFunction &MF = DAG.getMachineFunction();
17109     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17110     unsigned Reg;
17111     if (RegInfo->hasBasePointer(MF))
17112       Reg = RegInfo->getBaseRegister();
17113     else // This function handles the SP or FP case.
17114       Reg = RegInfo->getPtrSizedFrameRegister(MF);
17115     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
17116   }
17117   }
17118 }
17119
17120 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17121                               SDValue Src, SDValue Mask, SDValue Base,
17122                               SDValue Index, SDValue ScaleOp, SDValue Chain,
17123                               const X86Subtarget * Subtarget) {
17124   SDLoc dl(Op);
17125   auto *C = cast<ConstantSDNode>(ScaleOp);
17126   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17127   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17128                              Index.getSimpleValueType().getVectorNumElements());
17129   SDValue MaskInReg;
17130   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17131   if (MaskC)
17132     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17133   else {
17134     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17135                                      Mask.getSimpleValueType().getSizeInBits());
17136
17137     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17138     // are extracted by EXTRACT_SUBVECTOR.
17139     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17140                             DAG.getBitcast(BitcastVT, Mask),
17141                             DAG.getIntPtrConstant(0, dl));
17142   }
17143   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17144   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17145   SDValue Segment = DAG.getRegister(0, MVT::i32);
17146   if (Src.getOpcode() == ISD::UNDEF)
17147     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
17148   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17149   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17150   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17151   return DAG.getMergeValues(RetOps, dl);
17152 }
17153
17154 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17155                                SDValue Src, SDValue Mask, SDValue Base,
17156                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
17157   SDLoc dl(Op);
17158   auto *C = cast<ConstantSDNode>(ScaleOp);
17159   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17160   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17161   SDValue Segment = DAG.getRegister(0, MVT::i32);
17162   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17163                              Index.getSimpleValueType().getVectorNumElements());
17164   SDValue MaskInReg;
17165   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17166   if (MaskC)
17167     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17168   else {
17169     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17170                                      Mask.getSimpleValueType().getSizeInBits());
17171
17172     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17173     // are extracted by EXTRACT_SUBVECTOR.
17174     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17175                             DAG.getBitcast(BitcastVT, Mask),
17176                             DAG.getIntPtrConstant(0, dl));
17177   }
17178   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17179   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17180   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17181   return SDValue(Res, 1);
17182 }
17183
17184 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17185                                SDValue Mask, SDValue Base, SDValue Index,
17186                                SDValue ScaleOp, SDValue Chain) {
17187   SDLoc dl(Op);
17188   auto *C = cast<ConstantSDNode>(ScaleOp);
17189   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17190   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17191   SDValue Segment = DAG.getRegister(0, MVT::i32);
17192   MVT MaskVT =
17193     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17194   SDValue MaskInReg;
17195   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17196   if (MaskC)
17197     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17198   else
17199     MaskInReg = DAG.getBitcast(MaskVT, Mask);
17200   //SDVTList VTs = DAG.getVTList(MVT::Other);
17201   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17202   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17203   return SDValue(Res, 0);
17204 }
17205
17206 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17207 // read performance monitor counters (x86_rdpmc).
17208 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17209                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17210                               SmallVectorImpl<SDValue> &Results) {
17211   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17212   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17213   SDValue LO, HI;
17214
17215   // The ECX register is used to select the index of the performance counter
17216   // to read.
17217   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17218                                    N->getOperand(2));
17219   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17220
17221   // Reads the content of a 64-bit performance counter and returns it in the
17222   // registers EDX:EAX.
17223   if (Subtarget->is64Bit()) {
17224     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17225     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17226                             LO.getValue(2));
17227   } else {
17228     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17229     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17230                             LO.getValue(2));
17231   }
17232   Chain = HI.getValue(1);
17233
17234   if (Subtarget->is64Bit()) {
17235     // The EAX register is loaded with the low-order 32 bits. The EDX register
17236     // is loaded with the supported high-order bits of the counter.
17237     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17238                               DAG.getConstant(32, DL, MVT::i8));
17239     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17240     Results.push_back(Chain);
17241     return;
17242   }
17243
17244   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17245   SDValue Ops[] = { LO, HI };
17246   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17247   Results.push_back(Pair);
17248   Results.push_back(Chain);
17249 }
17250
17251 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17252 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17253 // also used to custom lower READCYCLECOUNTER nodes.
17254 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17255                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17256                               SmallVectorImpl<SDValue> &Results) {
17257   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17258   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17259   SDValue LO, HI;
17260
17261   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17262   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17263   // and the EAX register is loaded with the low-order 32 bits.
17264   if (Subtarget->is64Bit()) {
17265     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17266     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17267                             LO.getValue(2));
17268   } else {
17269     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17270     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17271                             LO.getValue(2));
17272   }
17273   SDValue Chain = HI.getValue(1);
17274
17275   if (Opcode == X86ISD::RDTSCP_DAG) {
17276     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17277
17278     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17279     // the ECX register. Add 'ecx' explicitly to the chain.
17280     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17281                                      HI.getValue(2));
17282     // Explicitly store the content of ECX at the location passed in input
17283     // to the 'rdtscp' intrinsic.
17284     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17285                          MachinePointerInfo(), false, false, 0);
17286   }
17287
17288   if (Subtarget->is64Bit()) {
17289     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17290     // the EAX register is loaded with the low-order 32 bits.
17291     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17292                               DAG.getConstant(32, DL, MVT::i8));
17293     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17294     Results.push_back(Chain);
17295     return;
17296   }
17297
17298   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17299   SDValue Ops[] = { LO, HI };
17300   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17301   Results.push_back(Pair);
17302   Results.push_back(Chain);
17303 }
17304
17305 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17306                                      SelectionDAG &DAG) {
17307   SmallVector<SDValue, 2> Results;
17308   SDLoc DL(Op);
17309   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17310                           Results);
17311   return DAG.getMergeValues(Results, DL);
17312 }
17313
17314 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17315   MachineFunction &MF = DAG.getMachineFunction();
17316   SDValue Chain = Op.getOperand(0);
17317   SDValue RegNode = Op.getOperand(2);
17318   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17319   if (!EHInfo)
17320     report_fatal_error("EH registrations only live in functions using WinEH");
17321
17322   // Cast the operand to an alloca, and remember the frame index.
17323   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17324   if (!FINode)
17325     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17326   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17327
17328   // Return the chain operand without making any DAG nodes.
17329   return Chain;
17330 }
17331
17332 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17333 /// return truncate Store/MaskedStore Node
17334 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17335                                                SelectionDAG &DAG,
17336                                                MVT ElementType) {
17337   SDLoc dl(Op);
17338   SDValue Mask = Op.getOperand(4);
17339   SDValue DataToTruncate = Op.getOperand(3);
17340   SDValue Addr = Op.getOperand(2);
17341   SDValue Chain = Op.getOperand(0);
17342
17343   MVT VT  = DataToTruncate.getSimpleValueType();
17344   MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17345
17346   if (isAllOnesConstant(Mask)) // return just a truncate store
17347     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17348                              MachinePointerInfo(), SVT, false, false,
17349                              SVT.getScalarSizeInBits()/8);
17350
17351   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17352   MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17353                                    Mask.getSimpleValueType().getSizeInBits());
17354   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17355   // are extracted by EXTRACT_SUBVECTOR.
17356   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17357                               DAG.getBitcast(BitcastVT, Mask),
17358                               DAG.getIntPtrConstant(0, dl));
17359
17360   MachineMemOperand *MMO = DAG.getMachineFunction().
17361     getMachineMemOperand(MachinePointerInfo(),
17362                          MachineMemOperand::MOStore, SVT.getStoreSize(),
17363                          SVT.getScalarSizeInBits()/8);
17364
17365   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17366                             VMask, SVT, MMO, true);
17367 }
17368
17369 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17370                                       SelectionDAG &DAG) {
17371   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17372
17373   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17374   if (!IntrData) {
17375     if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17376       return MarkEHRegistrationNode(Op, DAG);
17377     if (IntNo == llvm::Intrinsic::x86_flags_read_u32 ||
17378         IntNo == llvm::Intrinsic::x86_flags_read_u64 ||
17379         IntNo == llvm::Intrinsic::x86_flags_write_u32 ||
17380         IntNo == llvm::Intrinsic::x86_flags_write_u64) {
17381       // We need a frame pointer because this will get lowered to a PUSH/POP
17382       // sequence.
17383       MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17384       MFI->setHasOpaqueSPAdjustment(true);
17385       // Don't do anything here, we will expand these intrinsics out later
17386       // during ExpandISelPseudos in EmitInstrWithCustomInserter.
17387       return SDValue();
17388     }
17389     return SDValue();
17390   }
17391
17392   SDLoc dl(Op);
17393   switch(IntrData->Type) {
17394   default: llvm_unreachable("Unknown Intrinsic Type");
17395   case RDSEED:
17396   case RDRAND: {
17397     // Emit the node with the right value type.
17398     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17399     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17400
17401     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17402     // Otherwise return the value from Rand, which is always 0, casted to i32.
17403     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17404                       DAG.getConstant(1, dl, Op->getValueType(1)),
17405                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
17406                       SDValue(Result.getNode(), 1) };
17407     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17408                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17409                                   Ops);
17410
17411     // Return { result, isValid, chain }.
17412     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17413                        SDValue(Result.getNode(), 2));
17414   }
17415   case GATHER: {
17416   //gather(v1, mask, index, base, scale);
17417     SDValue Chain = Op.getOperand(0);
17418     SDValue Src   = Op.getOperand(2);
17419     SDValue Base  = Op.getOperand(3);
17420     SDValue Index = Op.getOperand(4);
17421     SDValue Mask  = Op.getOperand(5);
17422     SDValue Scale = Op.getOperand(6);
17423     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17424                          Chain, Subtarget);
17425   }
17426   case SCATTER: {
17427   //scatter(base, mask, index, v1, scale);
17428     SDValue Chain = Op.getOperand(0);
17429     SDValue Base  = Op.getOperand(2);
17430     SDValue Mask  = Op.getOperand(3);
17431     SDValue Index = Op.getOperand(4);
17432     SDValue Src   = Op.getOperand(5);
17433     SDValue Scale = Op.getOperand(6);
17434     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17435                           Scale, Chain);
17436   }
17437   case PREFETCH: {
17438     SDValue Hint = Op.getOperand(6);
17439     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17440     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17441     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17442     SDValue Chain = Op.getOperand(0);
17443     SDValue Mask  = Op.getOperand(2);
17444     SDValue Index = Op.getOperand(3);
17445     SDValue Base  = Op.getOperand(4);
17446     SDValue Scale = Op.getOperand(5);
17447     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17448   }
17449   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17450   case RDTSC: {
17451     SmallVector<SDValue, 2> Results;
17452     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17453                             Results);
17454     return DAG.getMergeValues(Results, dl);
17455   }
17456   // Read Performance Monitoring Counters.
17457   case RDPMC: {
17458     SmallVector<SDValue, 2> Results;
17459     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17460     return DAG.getMergeValues(Results, dl);
17461   }
17462   // XTEST intrinsics.
17463   case XTEST: {
17464     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17465     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17466     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17467                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17468                                 InTrans);
17469     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17470     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17471                        Ret, SDValue(InTrans.getNode(), 1));
17472   }
17473   // ADC/ADCX/SBB
17474   case ADX: {
17475     SmallVector<SDValue, 2> Results;
17476     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17477     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17478     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17479                                 DAG.getConstant(-1, dl, MVT::i8));
17480     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17481                               Op.getOperand(4), GenCF.getValue(1));
17482     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17483                                  Op.getOperand(5), MachinePointerInfo(),
17484                                  false, false, 0);
17485     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17486                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17487                                 Res.getValue(1));
17488     Results.push_back(SetCC);
17489     Results.push_back(Store);
17490     return DAG.getMergeValues(Results, dl);
17491   }
17492   case COMPRESS_TO_MEM: {
17493     SDLoc dl(Op);
17494     SDValue Mask = Op.getOperand(4);
17495     SDValue DataToCompress = Op.getOperand(3);
17496     SDValue Addr = Op.getOperand(2);
17497     SDValue Chain = Op.getOperand(0);
17498
17499     MVT VT = DataToCompress.getSimpleValueType();
17500     if (isAllOnesConstant(Mask)) // return just a store
17501       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17502                           MachinePointerInfo(), false, false,
17503                           VT.getScalarSizeInBits()/8);
17504
17505     SDValue Compressed =
17506       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17507                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17508     return DAG.getStore(Chain, dl, Compressed, Addr,
17509                         MachinePointerInfo(), false, false,
17510                         VT.getScalarSizeInBits()/8);
17511   }
17512   case TRUNCATE_TO_MEM_VI8:
17513     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17514   case TRUNCATE_TO_MEM_VI16:
17515     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17516   case TRUNCATE_TO_MEM_VI32:
17517     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17518   case EXPAND_FROM_MEM: {
17519     SDLoc dl(Op);
17520     SDValue Mask = Op.getOperand(4);
17521     SDValue PassThru = Op.getOperand(3);
17522     SDValue Addr = Op.getOperand(2);
17523     SDValue Chain = Op.getOperand(0);
17524     MVT VT = Op.getSimpleValueType();
17525
17526     if (isAllOnesConstant(Mask)) // return just a load
17527       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17528                          false, VT.getScalarSizeInBits()/8);
17529
17530     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17531                                        false, false, false,
17532                                        VT.getScalarSizeInBits()/8);
17533
17534     SDValue Results[] = {
17535       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17536                            Mask, PassThru, Subtarget, DAG), Chain};
17537     return DAG.getMergeValues(Results, dl);
17538   }
17539   }
17540 }
17541
17542 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17543                                            SelectionDAG &DAG) const {
17544   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17545   MFI->setReturnAddressIsTaken(true);
17546
17547   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17548     return SDValue();
17549
17550   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17551   SDLoc dl(Op);
17552   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17553
17554   if (Depth > 0) {
17555     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17556     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17557     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17558     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17559                        DAG.getNode(ISD::ADD, dl, PtrVT,
17560                                    FrameAddr, Offset),
17561                        MachinePointerInfo(), false, false, false, 0);
17562   }
17563
17564   // Just load the return address.
17565   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17566   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17567                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17568 }
17569
17570 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17571   MachineFunction &MF = DAG.getMachineFunction();
17572   MachineFrameInfo *MFI = MF.getFrameInfo();
17573   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17574   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17575   EVT VT = Op.getValueType();
17576
17577   MFI->setFrameAddressIsTaken(true);
17578
17579   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17580     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17581     // is not possible to crawl up the stack without looking at the unwind codes
17582     // simultaneously.
17583     int FrameAddrIndex = FuncInfo->getFAIndex();
17584     if (!FrameAddrIndex) {
17585       // Set up a frame object for the return address.
17586       unsigned SlotSize = RegInfo->getSlotSize();
17587       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17588           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17589       FuncInfo->setFAIndex(FrameAddrIndex);
17590     }
17591     return DAG.getFrameIndex(FrameAddrIndex, VT);
17592   }
17593
17594   unsigned FrameReg =
17595       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17596   SDLoc dl(Op);  // FIXME probably not meaningful
17597   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17598   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17599           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17600          "Invalid Frame Register!");
17601   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17602   while (Depth--)
17603     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17604                             MachinePointerInfo(),
17605                             false, false, false, 0);
17606   return FrameAddr;
17607 }
17608
17609 // FIXME? Maybe this could be a TableGen attribute on some registers and
17610 // this table could be generated automatically from RegInfo.
17611 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17612                                               SelectionDAG &DAG) const {
17613   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17614   const MachineFunction &MF = DAG.getMachineFunction();
17615
17616   unsigned Reg = StringSwitch<unsigned>(RegName)
17617                        .Case("esp", X86::ESP)
17618                        .Case("rsp", X86::RSP)
17619                        .Case("ebp", X86::EBP)
17620                        .Case("rbp", X86::RBP)
17621                        .Default(0);
17622
17623   if (Reg == X86::EBP || Reg == X86::RBP) {
17624     if (!TFI.hasFP(MF))
17625       report_fatal_error("register " + StringRef(RegName) +
17626                          " is allocatable: function has no frame pointer");
17627 #ifndef NDEBUG
17628     else {
17629       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17630       unsigned FrameReg =
17631           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17632       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17633              "Invalid Frame Register!");
17634     }
17635 #endif
17636   }
17637
17638   if (Reg)
17639     return Reg;
17640
17641   report_fatal_error("Invalid register name global variable");
17642 }
17643
17644 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17645                                                      SelectionDAG &DAG) const {
17646   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17647   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17648 }
17649
17650 unsigned X86TargetLowering::getExceptionPointerRegister(
17651     const Constant *PersonalityFn) const {
17652   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17653     return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17654
17655   return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17656 }
17657
17658 unsigned X86TargetLowering::getExceptionSelectorRegister(
17659     const Constant *PersonalityFn) const {
17660   // Funclet personalities don't use selectors (the runtime does the selection).
17661   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17662   return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17663 }
17664
17665 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17666   SDValue Chain     = Op.getOperand(0);
17667   SDValue Offset    = Op.getOperand(1);
17668   SDValue Handler   = Op.getOperand(2);
17669   SDLoc dl      (Op);
17670
17671   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17672   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17673   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17674   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17675           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17676          "Invalid Frame Register!");
17677   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17678   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17679
17680   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17681                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17682                                                        dl));
17683   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17684   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17685                        false, false, 0);
17686   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17687
17688   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17689                      DAG.getRegister(StoreAddrReg, PtrVT));
17690 }
17691
17692 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17693                                                SelectionDAG &DAG) const {
17694   SDLoc DL(Op);
17695   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17696                      DAG.getVTList(MVT::i32, MVT::Other),
17697                      Op.getOperand(0), Op.getOperand(1));
17698 }
17699
17700 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17701                                                 SelectionDAG &DAG) const {
17702   SDLoc DL(Op);
17703   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17704                      Op.getOperand(0), Op.getOperand(1));
17705 }
17706
17707 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17708   return Op.getOperand(0);
17709 }
17710
17711 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17712                                                 SelectionDAG &DAG) const {
17713   SDValue Root = Op.getOperand(0);
17714   SDValue Trmp = Op.getOperand(1); // trampoline
17715   SDValue FPtr = Op.getOperand(2); // nested function
17716   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17717   SDLoc dl (Op);
17718
17719   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17720   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17721
17722   if (Subtarget->is64Bit()) {
17723     SDValue OutChains[6];
17724
17725     // Large code-model.
17726     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17727     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17728
17729     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17730     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17731
17732     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17733
17734     // Load the pointer to the nested function into R11.
17735     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17736     SDValue Addr = Trmp;
17737     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17738                                 Addr, MachinePointerInfo(TrmpAddr),
17739                                 false, false, 0);
17740
17741     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17742                        DAG.getConstant(2, dl, MVT::i64));
17743     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17744                                 MachinePointerInfo(TrmpAddr, 2),
17745                                 false, false, 2);
17746
17747     // Load the 'nest' parameter value into R10.
17748     // R10 is specified in X86CallingConv.td
17749     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17750     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17751                        DAG.getConstant(10, dl, MVT::i64));
17752     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17753                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17754                                 false, false, 0);
17755
17756     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17757                        DAG.getConstant(12, dl, MVT::i64));
17758     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17759                                 MachinePointerInfo(TrmpAddr, 12),
17760                                 false, false, 2);
17761
17762     // Jump to the nested function.
17763     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17764     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17765                        DAG.getConstant(20, dl, MVT::i64));
17766     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17767                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17768                                 false, false, 0);
17769
17770     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17771     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17772                        DAG.getConstant(22, dl, MVT::i64));
17773     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17774                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17775                                 false, false, 0);
17776
17777     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17778   } else {
17779     const Function *Func =
17780       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17781     CallingConv::ID CC = Func->getCallingConv();
17782     unsigned NestReg;
17783
17784     switch (CC) {
17785     default:
17786       llvm_unreachable("Unsupported calling convention");
17787     case CallingConv::C:
17788     case CallingConv::X86_StdCall: {
17789       // Pass 'nest' parameter in ECX.
17790       // Must be kept in sync with X86CallingConv.td
17791       NestReg = X86::ECX;
17792
17793       // Check that ECX wasn't needed by an 'inreg' parameter.
17794       FunctionType *FTy = Func->getFunctionType();
17795       const AttributeSet &Attrs = Func->getAttributes();
17796
17797       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17798         unsigned InRegCount = 0;
17799         unsigned Idx = 1;
17800
17801         for (FunctionType::param_iterator I = FTy->param_begin(),
17802              E = FTy->param_end(); I != E; ++I, ++Idx)
17803           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17804             auto &DL = DAG.getDataLayout();
17805             // FIXME: should only count parameters that are lowered to integers.
17806             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17807           }
17808
17809         if (InRegCount > 2) {
17810           report_fatal_error("Nest register in use - reduce number of inreg"
17811                              " parameters!");
17812         }
17813       }
17814       break;
17815     }
17816     case CallingConv::X86_FastCall:
17817     case CallingConv::X86_ThisCall:
17818     case CallingConv::Fast:
17819       // Pass 'nest' parameter in EAX.
17820       // Must be kept in sync with X86CallingConv.td
17821       NestReg = X86::EAX;
17822       break;
17823     }
17824
17825     SDValue OutChains[4];
17826     SDValue Addr, Disp;
17827
17828     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17829                        DAG.getConstant(10, dl, MVT::i32));
17830     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17831
17832     // This is storing the opcode for MOV32ri.
17833     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17834     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17835     OutChains[0] = DAG.getStore(Root, dl,
17836                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17837                                 Trmp, MachinePointerInfo(TrmpAddr),
17838                                 false, false, 0);
17839
17840     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17841                        DAG.getConstant(1, dl, MVT::i32));
17842     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17843                                 MachinePointerInfo(TrmpAddr, 1),
17844                                 false, false, 1);
17845
17846     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17847     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17848                        DAG.getConstant(5, dl, MVT::i32));
17849     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17850                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17851                                 false, false, 1);
17852
17853     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17854                        DAG.getConstant(6, dl, MVT::i32));
17855     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17856                                 MachinePointerInfo(TrmpAddr, 6),
17857                                 false, false, 1);
17858
17859     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17860   }
17861 }
17862
17863 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17864                                             SelectionDAG &DAG) const {
17865   /*
17866    The rounding mode is in bits 11:10 of FPSR, and has the following
17867    settings:
17868      00 Round to nearest
17869      01 Round to -inf
17870      10 Round to +inf
17871      11 Round to 0
17872
17873   FLT_ROUNDS, on the other hand, expects the following:
17874     -1 Undefined
17875      0 Round to 0
17876      1 Round to nearest
17877      2 Round to +inf
17878      3 Round to -inf
17879
17880   To perform the conversion, we do:
17881     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17882   */
17883
17884   MachineFunction &MF = DAG.getMachineFunction();
17885   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17886   unsigned StackAlignment = TFI.getStackAlignment();
17887   MVT VT = Op.getSimpleValueType();
17888   SDLoc DL(Op);
17889
17890   // Save FP Control Word to stack slot
17891   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17892   SDValue StackSlot =
17893       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17894
17895   MachineMemOperand *MMO =
17896       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17897                               MachineMemOperand::MOStore, 2, 2);
17898
17899   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17900   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17901                                           DAG.getVTList(MVT::Other),
17902                                           Ops, MVT::i16, MMO);
17903
17904   // Load FP Control Word from stack slot
17905   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17906                             MachinePointerInfo(), false, false, false, 0);
17907
17908   // Transform as necessary
17909   SDValue CWD1 =
17910     DAG.getNode(ISD::SRL, DL, MVT::i16,
17911                 DAG.getNode(ISD::AND, DL, MVT::i16,
17912                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17913                 DAG.getConstant(11, DL, MVT::i8));
17914   SDValue CWD2 =
17915     DAG.getNode(ISD::SRL, DL, MVT::i16,
17916                 DAG.getNode(ISD::AND, DL, MVT::i16,
17917                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17918                 DAG.getConstant(9, DL, MVT::i8));
17919
17920   SDValue RetVal =
17921     DAG.getNode(ISD::AND, DL, MVT::i16,
17922                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17923                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17924                             DAG.getConstant(1, DL, MVT::i16)),
17925                 DAG.getConstant(3, DL, MVT::i16));
17926
17927   return DAG.getNode((VT.getSizeInBits() < 16 ?
17928                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17929 }
17930
17931 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17932 //
17933 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17934 //    to 512-bit vector.
17935 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17936 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17937 //    split the vector, perform operation on it's Lo a Hi part and
17938 //    concatenate the results.
17939 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17940   SDLoc dl(Op);
17941   MVT VT = Op.getSimpleValueType();
17942   MVT EltVT = VT.getVectorElementType();
17943   unsigned NumElems = VT.getVectorNumElements();
17944
17945   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17946     // Extend to 512 bit vector.
17947     assert((VT.is256BitVector() || VT.is128BitVector()) &&
17948               "Unsupported value type for operation");
17949
17950     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17951     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17952                                  DAG.getUNDEF(NewVT),
17953                                  Op.getOperand(0),
17954                                  DAG.getIntPtrConstant(0, dl));
17955     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17956
17957     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17958                        DAG.getIntPtrConstant(0, dl));
17959   }
17960
17961   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17962           "Unsupported element type");
17963
17964   if (16 < NumElems) {
17965     // Split vector, it's Lo and Hi parts will be handled in next iteration.
17966     SDValue Lo, Hi;
17967     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17968     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17969
17970     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17971     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17972
17973     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17974   }
17975
17976   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17977
17978   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17979           "Unsupported value type for operation");
17980
17981   // Use native supported vector instruction vplzcntd.
17982   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17983   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17984   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17985   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17986
17987   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17988 }
17989
17990 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
17991                          SelectionDAG &DAG) {
17992   MVT VT = Op.getSimpleValueType();
17993   MVT OpVT = VT;
17994   unsigned NumBits = VT.getSizeInBits();
17995   SDLoc dl(Op);
17996
17997   if (VT.isVector() && Subtarget->hasAVX512())
17998     return LowerVectorCTLZ_AVX512(Op, DAG);
17999
18000   Op = Op.getOperand(0);
18001   if (VT == MVT::i8) {
18002     // Zero extend to i32 since there is not an i8 bsr.
18003     OpVT = MVT::i32;
18004     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18005   }
18006
18007   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
18008   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18009   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18010
18011   // If src is zero (i.e. bsr sets ZF), returns NumBits.
18012   SDValue Ops[] = {
18013     Op,
18014     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
18015     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18016     Op.getValue(1)
18017   };
18018   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
18019
18020   // Finally xor with NumBits-1.
18021   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18022                    DAG.getConstant(NumBits - 1, dl, OpVT));
18023
18024   if (VT == MVT::i8)
18025     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18026   return Op;
18027 }
18028
18029 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
18030                                     SelectionDAG &DAG) {
18031   MVT VT = Op.getSimpleValueType();
18032   EVT OpVT = VT;
18033   unsigned NumBits = VT.getSizeInBits();
18034   SDLoc dl(Op);
18035
18036   Op = Op.getOperand(0);
18037   if (VT == MVT::i8) {
18038     // Zero extend to i32 since there is not an i8 bsr.
18039     OpVT = MVT::i32;
18040     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18041   }
18042
18043   // Issue a bsr (scan bits in reverse).
18044   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18045   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18046
18047   // And xor with NumBits-1.
18048   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18049                    DAG.getConstant(NumBits - 1, dl, OpVT));
18050
18051   if (VT == MVT::i8)
18052     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18053   return Op;
18054 }
18055
18056 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18057   MVT VT = Op.getSimpleValueType();
18058   unsigned NumBits = VT.getScalarSizeInBits();
18059   SDLoc dl(Op);
18060
18061   if (VT.isVector()) {
18062     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18063
18064     SDValue N0 = Op.getOperand(0);
18065     SDValue Zero = DAG.getConstant(0, dl, VT);
18066
18067     // lsb(x) = (x & -x)
18068     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
18069                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
18070
18071     // cttz_undef(x) = (width - 1) - ctlz(lsb)
18072     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
18073         TLI.isOperationLegal(ISD::CTLZ, VT)) {
18074       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
18075       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
18076                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
18077     }
18078
18079     // cttz(x) = ctpop(lsb - 1)
18080     SDValue One = DAG.getConstant(1, dl, VT);
18081     return DAG.getNode(ISD::CTPOP, dl, VT,
18082                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
18083   }
18084
18085   assert(Op.getOpcode() == ISD::CTTZ &&
18086          "Only scalar CTTZ requires custom lowering");
18087
18088   // Issue a bsf (scan bits forward) which also sets EFLAGS.
18089   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18090   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
18091
18092   // If src is zero (i.e. bsf sets ZF), returns NumBits.
18093   SDValue Ops[] = {
18094     Op,
18095     DAG.getConstant(NumBits, dl, VT),
18096     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18097     Op.getValue(1)
18098   };
18099   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18100 }
18101
18102 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18103 // ones, and then concatenate the result back.
18104 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18105   MVT VT = Op.getSimpleValueType();
18106
18107   assert(VT.is256BitVector() && VT.isInteger() &&
18108          "Unsupported value type for operation");
18109
18110   unsigned NumElems = VT.getVectorNumElements();
18111   SDLoc dl(Op);
18112
18113   // Extract the LHS vectors
18114   SDValue LHS = Op.getOperand(0);
18115   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18116   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18117
18118   // Extract the RHS vectors
18119   SDValue RHS = Op.getOperand(1);
18120   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18121   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18122
18123   MVT EltVT = VT.getVectorElementType();
18124   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18125
18126   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18127                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18128                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18129 }
18130
18131 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18132   if (Op.getValueType() == MVT::i1)
18133     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18134                        Op.getOperand(0), Op.getOperand(1));
18135   assert(Op.getSimpleValueType().is256BitVector() &&
18136          Op.getSimpleValueType().isInteger() &&
18137          "Only handle AVX 256-bit vector integer operation");
18138   return Lower256IntArith(Op, DAG);
18139 }
18140
18141 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18142   if (Op.getValueType() == MVT::i1)
18143     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18144                        Op.getOperand(0), Op.getOperand(1));
18145   assert(Op.getSimpleValueType().is256BitVector() &&
18146          Op.getSimpleValueType().isInteger() &&
18147          "Only handle AVX 256-bit vector integer operation");
18148   return Lower256IntArith(Op, DAG);
18149 }
18150
18151 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
18152   assert(Op.getSimpleValueType().is256BitVector() &&
18153          Op.getSimpleValueType().isInteger() &&
18154          "Only handle AVX 256-bit vector integer operation");
18155   return Lower256IntArith(Op, DAG);
18156 }
18157
18158 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18159                         SelectionDAG &DAG) {
18160   SDLoc dl(Op);
18161   MVT VT = Op.getSimpleValueType();
18162
18163   if (VT == MVT::i1)
18164     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
18165
18166   // Decompose 256-bit ops into smaller 128-bit ops.
18167   if (VT.is256BitVector() && !Subtarget->hasInt256())
18168     return Lower256IntArith(Op, DAG);
18169
18170   SDValue A = Op.getOperand(0);
18171   SDValue B = Op.getOperand(1);
18172
18173   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
18174   // pairs, multiply and truncate.
18175   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
18176     if (Subtarget->hasInt256()) {
18177       if (VT == MVT::v32i8) {
18178         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
18179         SDValue Lo = DAG.getIntPtrConstant(0, dl);
18180         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
18181         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
18182         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
18183         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
18184         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18185         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18186                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18187                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18188       }
18189
18190       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18191       return DAG.getNode(
18192           ISD::TRUNCATE, dl, VT,
18193           DAG.getNode(ISD::MUL, dl, ExVT,
18194                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18195                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18196     }
18197
18198     assert(VT == MVT::v16i8 &&
18199            "Pre-AVX2 support only supports v16i8 multiplication");
18200     MVT ExVT = MVT::v8i16;
18201
18202     // Extract the lo parts and sign extend to i16
18203     SDValue ALo, BLo;
18204     if (Subtarget->hasSSE41()) {
18205       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18206       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18207     } else {
18208       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18209                               -1, 4, -1, 5, -1, 6, -1, 7};
18210       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18211       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18212       ALo = DAG.getBitcast(ExVT, ALo);
18213       BLo = DAG.getBitcast(ExVT, BLo);
18214       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18215       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18216     }
18217
18218     // Extract the hi parts and sign extend to i16
18219     SDValue AHi, BHi;
18220     if (Subtarget->hasSSE41()) {
18221       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
18222                               -1, -1, -1, -1, -1, -1, -1, -1};
18223       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18224       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18225       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18226       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18227     } else {
18228       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
18229                               -1, 12, -1, 13, -1, 14, -1, 15};
18230       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18231       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18232       AHi = DAG.getBitcast(ExVT, AHi);
18233       BHi = DAG.getBitcast(ExVT, BHi);
18234       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18235       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18236     }
18237
18238     // Multiply, mask the lower 8bits of the lo/hi results and pack
18239     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18240     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18241     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18242     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18243     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18244   }
18245
18246   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18247   if (VT == MVT::v4i32) {
18248     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18249            "Should not custom lower when pmuldq is available!");
18250
18251     // Extract the odd parts.
18252     static const int UnpackMask[] = { 1, -1, 3, -1 };
18253     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18254     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18255
18256     // Multiply the even parts.
18257     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18258     // Now multiply odd parts.
18259     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18260
18261     Evens = DAG.getBitcast(VT, Evens);
18262     Odds = DAG.getBitcast(VT, Odds);
18263
18264     // Merge the two vectors back together with a shuffle. This expands into 2
18265     // shuffles.
18266     static const int ShufMask[] = { 0, 4, 2, 6 };
18267     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18268   }
18269
18270   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18271          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18272
18273   //  Ahi = psrlqi(a, 32);
18274   //  Bhi = psrlqi(b, 32);
18275   //
18276   //  AloBlo = pmuludq(a, b);
18277   //  AloBhi = pmuludq(a, Bhi);
18278   //  AhiBlo = pmuludq(Ahi, b);
18279
18280   //  AloBhi = psllqi(AloBhi, 32);
18281   //  AhiBlo = psllqi(AhiBlo, 32);
18282   //  return AloBlo + AloBhi + AhiBlo;
18283
18284   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18285   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18286
18287   SDValue AhiBlo = Ahi;
18288   SDValue AloBhi = Bhi;
18289   // Bit cast to 32-bit vectors for MULUDQ
18290   MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18291                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18292   A = DAG.getBitcast(MulVT, A);
18293   B = DAG.getBitcast(MulVT, B);
18294   Ahi = DAG.getBitcast(MulVT, Ahi);
18295   Bhi = DAG.getBitcast(MulVT, Bhi);
18296
18297   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18298   // After shifting right const values the result may be all-zero.
18299   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18300     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18301     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18302   }
18303   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18304     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18305     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18306   }
18307
18308   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18309   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18310 }
18311
18312 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18313   assert(Subtarget->isTargetWin64() && "Unexpected target");
18314   EVT VT = Op.getValueType();
18315   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18316          "Unexpected return type for lowering");
18317
18318   RTLIB::Libcall LC;
18319   bool isSigned;
18320   switch (Op->getOpcode()) {
18321   default: llvm_unreachable("Unexpected request for libcall!");
18322   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18323   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18324   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18325   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18326   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18327   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18328   }
18329
18330   SDLoc dl(Op);
18331   SDValue InChain = DAG.getEntryNode();
18332
18333   TargetLowering::ArgListTy Args;
18334   TargetLowering::ArgListEntry Entry;
18335   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18336     EVT ArgVT = Op->getOperand(i).getValueType();
18337     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18338            "Unexpected argument type for lowering");
18339     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18340     Entry.Node = StackPtr;
18341     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18342                            false, false, 16);
18343     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18344     Entry.Ty = PointerType::get(ArgTy,0);
18345     Entry.isSExt = false;
18346     Entry.isZExt = false;
18347     Args.push_back(Entry);
18348   }
18349
18350   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18351                                          getPointerTy(DAG.getDataLayout()));
18352
18353   TargetLowering::CallLoweringInfo CLI(DAG);
18354   CLI.setDebugLoc(dl).setChain(InChain)
18355     .setCallee(getLibcallCallingConv(LC),
18356                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18357                Callee, std::move(Args), 0)
18358     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18359
18360   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18361   return DAG.getBitcast(VT, CallInfo.first);
18362 }
18363
18364 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18365                              SelectionDAG &DAG) {
18366   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18367   MVT VT = Op0.getSimpleValueType();
18368   SDLoc dl(Op);
18369
18370   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18371          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18372
18373   // PMULxD operations multiply each even value (starting at 0) of LHS with
18374   // the related value of RHS and produce a widen result.
18375   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18376   // => <2 x i64> <ae|cg>
18377   //
18378   // In other word, to have all the results, we need to perform two PMULxD:
18379   // 1. one with the even values.
18380   // 2. one with the odd values.
18381   // To achieve #2, with need to place the odd values at an even position.
18382   //
18383   // Place the odd value at an even position (basically, shift all values 1
18384   // step to the left):
18385   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18386   // <a|b|c|d> => <b|undef|d|undef>
18387   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18388   // <e|f|g|h> => <f|undef|h|undef>
18389   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18390
18391   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18392   // ints.
18393   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18394   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18395   unsigned Opcode =
18396       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18397   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18398   // => <2 x i64> <ae|cg>
18399   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18400   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18401   // => <2 x i64> <bf|dh>
18402   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18403
18404   // Shuffle it back into the right order.
18405   SDValue Highs, Lows;
18406   if (VT == MVT::v8i32) {
18407     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18408     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18409     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18410     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18411   } else {
18412     const int HighMask[] = {1, 5, 3, 7};
18413     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18414     const int LowMask[] = {0, 4, 2, 6};
18415     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18416   }
18417
18418   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18419   // unsigned multiply.
18420   if (IsSigned && !Subtarget->hasSSE41()) {
18421     SDValue ShAmt = DAG.getConstant(
18422         31, dl,
18423         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18424     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18425                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18426     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18427                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18428
18429     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18430     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18431   }
18432
18433   // The first result of MUL_LOHI is actually the low value, followed by the
18434   // high value.
18435   SDValue Ops[] = {Lows, Highs};
18436   return DAG.getMergeValues(Ops, dl);
18437 }
18438
18439 // Return true if the required (according to Opcode) shift-imm form is natively
18440 // supported by the Subtarget
18441 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18442                                         unsigned Opcode) {
18443   if (VT.getScalarSizeInBits() < 16)
18444     return false;
18445
18446   if (VT.is512BitVector() &&
18447       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18448     return true;
18449
18450   bool LShift = VT.is128BitVector() ||
18451     (VT.is256BitVector() && Subtarget->hasInt256());
18452
18453   bool AShift = LShift && (Subtarget->hasVLX() ||
18454     (VT != MVT::v2i64 && VT != MVT::v4i64));
18455   return (Opcode == ISD::SRA) ? AShift : LShift;
18456 }
18457
18458 // The shift amount is a variable, but it is the same for all vector lanes.
18459 // These instructions are defined together with shift-immediate.
18460 static
18461 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18462                                       unsigned Opcode) {
18463   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18464 }
18465
18466 // Return true if the required (according to Opcode) variable-shift form is
18467 // natively supported by the Subtarget
18468 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18469                                     unsigned Opcode) {
18470
18471   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18472     return false;
18473
18474   // vXi16 supported only on AVX-512, BWI
18475   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18476     return false;
18477
18478   if (VT.is512BitVector() || Subtarget->hasVLX())
18479     return true;
18480
18481   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18482   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18483   return (Opcode == ISD::SRA) ? AShift : LShift;
18484 }
18485
18486 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18487                                          const X86Subtarget *Subtarget) {
18488   MVT VT = Op.getSimpleValueType();
18489   SDLoc dl(Op);
18490   SDValue R = Op.getOperand(0);
18491   SDValue Amt = Op.getOperand(1);
18492
18493   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18494     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18495
18496   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18497     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18498     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18499     SDValue Ex = DAG.getBitcast(ExVT, R);
18500
18501     if (ShiftAmt >= 32) {
18502       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18503       SDValue Upper =
18504           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18505       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18506                                                  ShiftAmt - 32, DAG);
18507       if (VT == MVT::v2i64)
18508         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18509       if (VT == MVT::v4i64)
18510         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18511                                   {9, 1, 11, 3, 13, 5, 15, 7});
18512     } else {
18513       // SRA upper i32, SHL whole i64 and select lower i32.
18514       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18515                                                  ShiftAmt, DAG);
18516       SDValue Lower =
18517           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18518       Lower = DAG.getBitcast(ExVT, Lower);
18519       if (VT == MVT::v2i64)
18520         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18521       if (VT == MVT::v4i64)
18522         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18523                                   {8, 1, 10, 3, 12, 5, 14, 7});
18524     }
18525     return DAG.getBitcast(VT, Ex);
18526   };
18527
18528   // Optimize shl/srl/sra with constant shift amount.
18529   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18530     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18531       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18532
18533       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18534         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18535
18536       // i64 SRA needs to be performed as partial shifts.
18537       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18538           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18539         return ArithmeticShiftRight64(ShiftAmt);
18540
18541       if (VT == MVT::v16i8 ||
18542           (Subtarget->hasInt256() && VT == MVT::v32i8) ||
18543           VT == MVT::v64i8) {
18544         unsigned NumElts = VT.getVectorNumElements();
18545         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18546
18547         // Simple i8 add case
18548         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18549           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18550
18551         // ashr(R, 7)  === cmp_slt(R, 0)
18552         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18553           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18554           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18555         }
18556
18557         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18558         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18559           return SDValue();
18560
18561         if (Op.getOpcode() == ISD::SHL) {
18562           // Make a large shift.
18563           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18564                                                    R, ShiftAmt, DAG);
18565           SHL = DAG.getBitcast(VT, SHL);
18566           // Zero out the rightmost bits.
18567           return DAG.getNode(ISD::AND, dl, VT, SHL,
18568                              DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
18569         }
18570         if (Op.getOpcode() == ISD::SRL) {
18571           // Make a large shift.
18572           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18573                                                    R, ShiftAmt, DAG);
18574           SRL = DAG.getBitcast(VT, SRL);
18575           // Zero out the leftmost bits.
18576           return DAG.getNode(ISD::AND, dl, VT, SRL,
18577                              DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
18578         }
18579         if (Op.getOpcode() == ISD::SRA) {
18580           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18581           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18582
18583           SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
18584           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18585           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18586           return Res;
18587         }
18588         llvm_unreachable("Unknown shift opcode.");
18589       }
18590     }
18591   }
18592
18593   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18594   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18595       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18596
18597     // Peek through any splat that was introduced for i64 shift vectorization.
18598     int SplatIndex = -1;
18599     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18600       if (SVN->isSplat()) {
18601         SplatIndex = SVN->getSplatIndex();
18602         Amt = Amt.getOperand(0);
18603         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18604                "Splat shuffle referencing second operand");
18605       }
18606
18607     if (Amt.getOpcode() != ISD::BITCAST ||
18608         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18609       return SDValue();
18610
18611     Amt = Amt.getOperand(0);
18612     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18613                      VT.getVectorNumElements();
18614     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18615     uint64_t ShiftAmt = 0;
18616     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18617     for (unsigned i = 0; i != Ratio; ++i) {
18618       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18619       if (!C)
18620         return SDValue();
18621       // 6 == Log2(64)
18622       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18623     }
18624
18625     // Check remaining shift amounts (if not a splat).
18626     if (SplatIndex < 0) {
18627       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18628         uint64_t ShAmt = 0;
18629         for (unsigned j = 0; j != Ratio; ++j) {
18630           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18631           if (!C)
18632             return SDValue();
18633           // 6 == Log2(64)
18634           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18635         }
18636         if (ShAmt != ShiftAmt)
18637           return SDValue();
18638       }
18639     }
18640
18641     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18642       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18643
18644     if (Op.getOpcode() == ISD::SRA)
18645       return ArithmeticShiftRight64(ShiftAmt);
18646   }
18647
18648   return SDValue();
18649 }
18650
18651 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18652                                         const X86Subtarget* Subtarget) {
18653   MVT VT = Op.getSimpleValueType();
18654   SDLoc dl(Op);
18655   SDValue R = Op.getOperand(0);
18656   SDValue Amt = Op.getOperand(1);
18657
18658   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18659     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18660
18661   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18662     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18663
18664   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18665     SDValue BaseShAmt;
18666     MVT EltVT = VT.getVectorElementType();
18667
18668     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18669       // Check if this build_vector node is doing a splat.
18670       // If so, then set BaseShAmt equal to the splat value.
18671       BaseShAmt = BV->getSplatValue();
18672       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18673         BaseShAmt = SDValue();
18674     } else {
18675       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18676         Amt = Amt.getOperand(0);
18677
18678       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18679       if (SVN && SVN->isSplat()) {
18680         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18681         SDValue InVec = Amt.getOperand(0);
18682         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18683           assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18684                  "Unexpected shuffle index found!");
18685           BaseShAmt = InVec.getOperand(SplatIdx);
18686         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18687            if (ConstantSDNode *C =
18688                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18689              if (C->getZExtValue() == SplatIdx)
18690                BaseShAmt = InVec.getOperand(1);
18691            }
18692         }
18693
18694         if (!BaseShAmt)
18695           // Avoid introducing an extract element from a shuffle.
18696           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18697                                   DAG.getIntPtrConstant(SplatIdx, dl));
18698       }
18699     }
18700
18701     if (BaseShAmt.getNode()) {
18702       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18703       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18704         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18705       else if (EltVT.bitsLT(MVT::i32))
18706         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18707
18708       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18709     }
18710   }
18711
18712   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18713   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18714       Amt.getOpcode() == ISD::BITCAST &&
18715       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18716     Amt = Amt.getOperand(0);
18717     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18718                      VT.getVectorNumElements();
18719     std::vector<SDValue> Vals(Ratio);
18720     for (unsigned i = 0; i != Ratio; ++i)
18721       Vals[i] = Amt.getOperand(i);
18722     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18723       for (unsigned j = 0; j != Ratio; ++j)
18724         if (Vals[j] != Amt.getOperand(i + j))
18725           return SDValue();
18726     }
18727
18728     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18729       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18730   }
18731   return SDValue();
18732 }
18733
18734 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18735                           SelectionDAG &DAG) {
18736   MVT VT = Op.getSimpleValueType();
18737   SDLoc dl(Op);
18738   SDValue R = Op.getOperand(0);
18739   SDValue Amt = Op.getOperand(1);
18740
18741   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18742   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18743
18744   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18745     return V;
18746
18747   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18748     return V;
18749
18750   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18751     return Op;
18752
18753   // XOP has 128-bit variable logical/arithmetic shifts.
18754   // +ve/-ve Amt = shift left/right.
18755   if (Subtarget->hasXOP() &&
18756       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18757        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18758     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18759       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18760       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18761     }
18762     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18763       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18764     if (Op.getOpcode() == ISD::SRA)
18765       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18766   }
18767
18768   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18769   // shifts per-lane and then shuffle the partial results back together.
18770   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18771     // Splat the shift amounts so the scalar shifts above will catch it.
18772     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18773     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18774     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18775     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18776     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18777   }
18778
18779   // i64 vector arithmetic shift can be emulated with the transform:
18780   // M = lshr(SIGN_BIT, Amt)
18781   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18782   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18783       Op.getOpcode() == ISD::SRA) {
18784     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18785     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18786     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18787     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18788     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18789     return R;
18790   }
18791
18792   // If possible, lower this packed shift into a vector multiply instead of
18793   // expanding it into a sequence of scalar shifts.
18794   // Do this only if the vector shift count is a constant build_vector.
18795   if (Op.getOpcode() == ISD::SHL &&
18796       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18797        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18798       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18799     SmallVector<SDValue, 8> Elts;
18800     MVT SVT = VT.getVectorElementType();
18801     unsigned SVTBits = SVT.getSizeInBits();
18802     APInt One(SVTBits, 1);
18803     unsigned NumElems = VT.getVectorNumElements();
18804
18805     for (unsigned i=0; i !=NumElems; ++i) {
18806       SDValue Op = Amt->getOperand(i);
18807       if (Op->getOpcode() == ISD::UNDEF) {
18808         Elts.push_back(Op);
18809         continue;
18810       }
18811
18812       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18813       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18814       uint64_t ShAmt = C.getZExtValue();
18815       if (ShAmt >= SVTBits) {
18816         Elts.push_back(DAG.getUNDEF(SVT));
18817         continue;
18818       }
18819       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18820     }
18821     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18822     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18823   }
18824
18825   // Lower SHL with variable shift amount.
18826   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18827     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18828
18829     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18830                      DAG.getConstant(0x3f800000U, dl, VT));
18831     Op = DAG.getBitcast(MVT::v4f32, Op);
18832     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18833     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18834   }
18835
18836   // If possible, lower this shift as a sequence of two shifts by
18837   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18838   // Example:
18839   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18840   //
18841   // Could be rewritten as:
18842   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18843   //
18844   // The advantage is that the two shifts from the example would be
18845   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18846   // the vector shift into four scalar shifts plus four pairs of vector
18847   // insert/extract.
18848   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18849       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18850     unsigned TargetOpcode = X86ISD::MOVSS;
18851     bool CanBeSimplified;
18852     // The splat value for the first packed shift (the 'X' from the example).
18853     SDValue Amt1 = Amt->getOperand(0);
18854     // The splat value for the second packed shift (the 'Y' from the example).
18855     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18856                                         Amt->getOperand(2);
18857
18858     // See if it is possible to replace this node with a sequence of
18859     // two shifts followed by a MOVSS/MOVSD
18860     if (VT == MVT::v4i32) {
18861       // Check if it is legal to use a MOVSS.
18862       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18863                         Amt2 == Amt->getOperand(3);
18864       if (!CanBeSimplified) {
18865         // Otherwise, check if we can still simplify this node using a MOVSD.
18866         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18867                           Amt->getOperand(2) == Amt->getOperand(3);
18868         TargetOpcode = X86ISD::MOVSD;
18869         Amt2 = Amt->getOperand(2);
18870       }
18871     } else {
18872       // Do similar checks for the case where the machine value type
18873       // is MVT::v8i16.
18874       CanBeSimplified = Amt1 == Amt->getOperand(1);
18875       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18876         CanBeSimplified = Amt2 == Amt->getOperand(i);
18877
18878       if (!CanBeSimplified) {
18879         TargetOpcode = X86ISD::MOVSD;
18880         CanBeSimplified = true;
18881         Amt2 = Amt->getOperand(4);
18882         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18883           CanBeSimplified = Amt1 == Amt->getOperand(i);
18884         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18885           CanBeSimplified = Amt2 == Amt->getOperand(j);
18886       }
18887     }
18888
18889     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18890         isa<ConstantSDNode>(Amt2)) {
18891       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18892       MVT CastVT = MVT::v4i32;
18893       SDValue Splat1 =
18894         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18895       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18896       SDValue Splat2 =
18897         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18898       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18899       if (TargetOpcode == X86ISD::MOVSD)
18900         CastVT = MVT::v2i64;
18901       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18902       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18903       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18904                                             BitCast1, DAG);
18905       return DAG.getBitcast(VT, Result);
18906     }
18907   }
18908
18909   // v4i32 Non Uniform Shifts.
18910   // If the shift amount is constant we can shift each lane using the SSE2
18911   // immediate shifts, else we need to zero-extend each lane to the lower i64
18912   // and shift using the SSE2 variable shifts.
18913   // The separate results can then be blended together.
18914   if (VT == MVT::v4i32) {
18915     unsigned Opc = Op.getOpcode();
18916     SDValue Amt0, Amt1, Amt2, Amt3;
18917     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18918       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18919       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18920       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18921       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18922     } else {
18923       // ISD::SHL is handled above but we include it here for completeness.
18924       switch (Opc) {
18925       default:
18926         llvm_unreachable("Unknown target vector shift node");
18927       case ISD::SHL:
18928         Opc = X86ISD::VSHL;
18929         break;
18930       case ISD::SRL:
18931         Opc = X86ISD::VSRL;
18932         break;
18933       case ISD::SRA:
18934         Opc = X86ISD::VSRA;
18935         break;
18936       }
18937       // The SSE2 shifts use the lower i64 as the same shift amount for
18938       // all lanes and the upper i64 is ignored. These shuffle masks
18939       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18940       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18941       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18942       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18943       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18944       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18945     }
18946
18947     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18948     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18949     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18950     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18951     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18952     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18953     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18954   }
18955
18956   if (VT == MVT::v16i8 ||
18957       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18958     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18959     unsigned ShiftOpcode = Op->getOpcode();
18960
18961     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18962       // On SSE41 targets we make use of the fact that VSELECT lowers
18963       // to PBLENDVB which selects bytes based just on the sign bit.
18964       if (Subtarget->hasSSE41()) {
18965         V0 = DAG.getBitcast(VT, V0);
18966         V1 = DAG.getBitcast(VT, V1);
18967         Sel = DAG.getBitcast(VT, Sel);
18968         return DAG.getBitcast(SelVT,
18969                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18970       }
18971       // On pre-SSE41 targets we test for the sign bit by comparing to
18972       // zero - a negative value will set all bits of the lanes to true
18973       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18974       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18975       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18976       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18977     };
18978
18979     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18980     // We can safely do this using i16 shifts as we're only interested in
18981     // the 3 lower bits of each byte.
18982     Amt = DAG.getBitcast(ExtVT, Amt);
18983     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18984     Amt = DAG.getBitcast(VT, Amt);
18985
18986     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18987       // r = VSELECT(r, shift(r, 4), a);
18988       SDValue M =
18989           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18990       R = SignBitSelect(VT, Amt, M, R);
18991
18992       // a += a
18993       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18994
18995       // r = VSELECT(r, shift(r, 2), a);
18996       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18997       R = SignBitSelect(VT, Amt, M, R);
18998
18999       // a += a
19000       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19001
19002       // return VSELECT(r, shift(r, 1), a);
19003       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19004       R = SignBitSelect(VT, Amt, M, R);
19005       return R;
19006     }
19007
19008     if (Op->getOpcode() == ISD::SRA) {
19009       // For SRA we need to unpack each byte to the higher byte of a i16 vector
19010       // so we can correctly sign extend. We don't care what happens to the
19011       // lower byte.
19012       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
19013       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
19014       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
19015       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
19016       ALo = DAG.getBitcast(ExtVT, ALo);
19017       AHi = DAG.getBitcast(ExtVT, AHi);
19018       RLo = DAG.getBitcast(ExtVT, RLo);
19019       RHi = DAG.getBitcast(ExtVT, RHi);
19020
19021       // r = VSELECT(r, shift(r, 4), a);
19022       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19023                                 DAG.getConstant(4, dl, ExtVT));
19024       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19025                                 DAG.getConstant(4, dl, ExtVT));
19026       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19027       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19028
19029       // a += a
19030       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19031       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19032
19033       // r = VSELECT(r, shift(r, 2), a);
19034       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19035                         DAG.getConstant(2, dl, ExtVT));
19036       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19037                         DAG.getConstant(2, dl, ExtVT));
19038       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19039       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19040
19041       // a += a
19042       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19043       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19044
19045       // r = VSELECT(r, shift(r, 1), a);
19046       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19047                         DAG.getConstant(1, dl, ExtVT));
19048       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19049                         DAG.getConstant(1, dl, ExtVT));
19050       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19051       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19052
19053       // Logical shift the result back to the lower byte, leaving a zero upper
19054       // byte
19055       // meaning that we can safely pack with PACKUSWB.
19056       RLo =
19057           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
19058       RHi =
19059           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
19060       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
19061     }
19062   }
19063
19064   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
19065   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
19066   // solution better.
19067   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
19068     MVT ExtVT = MVT::v8i32;
19069     unsigned ExtOpc =
19070         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19071     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
19072     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
19073     return DAG.getNode(ISD::TRUNCATE, dl, VT,
19074                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
19075   }
19076
19077   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
19078     MVT ExtVT = MVT::v8i32;
19079     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19080     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
19081     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
19082     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
19083     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
19084     ALo = DAG.getBitcast(ExtVT, ALo);
19085     AHi = DAG.getBitcast(ExtVT, AHi);
19086     RLo = DAG.getBitcast(ExtVT, RLo);
19087     RHi = DAG.getBitcast(ExtVT, RHi);
19088     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
19089     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
19090     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
19091     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
19092     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
19093   }
19094
19095   if (VT == MVT::v8i16) {
19096     unsigned ShiftOpcode = Op->getOpcode();
19097
19098     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
19099       // On SSE41 targets we make use of the fact that VSELECT lowers
19100       // to PBLENDVB which selects bytes based just on the sign bit.
19101       if (Subtarget->hasSSE41()) {
19102         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
19103         V0 = DAG.getBitcast(ExtVT, V0);
19104         V1 = DAG.getBitcast(ExtVT, V1);
19105         Sel = DAG.getBitcast(ExtVT, Sel);
19106         return DAG.getBitcast(
19107             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
19108       }
19109       // On pre-SSE41 targets we splat the sign bit - a negative value will
19110       // set all bits of the lanes to true and VSELECT uses that in
19111       // its OR(AND(V0,C),AND(V1,~C)) lowering.
19112       SDValue C =
19113           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
19114       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
19115     };
19116
19117     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
19118     if (Subtarget->hasSSE41()) {
19119       // On SSE41 targets we need to replicate the shift mask in both
19120       // bytes for PBLENDVB.
19121       Amt = DAG.getNode(
19122           ISD::OR, dl, VT,
19123           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
19124           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
19125     } else {
19126       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
19127     }
19128
19129     // r = VSELECT(r, shift(r, 8), a);
19130     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
19131     R = SignBitSelect(Amt, M, R);
19132
19133     // a += a
19134     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19135
19136     // r = VSELECT(r, shift(r, 4), a);
19137     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19138     R = SignBitSelect(Amt, M, R);
19139
19140     // a += a
19141     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19142
19143     // r = VSELECT(r, shift(r, 2), a);
19144     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19145     R = SignBitSelect(Amt, M, R);
19146
19147     // a += a
19148     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19149
19150     // return VSELECT(r, shift(r, 1), a);
19151     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19152     R = SignBitSelect(Amt, M, R);
19153     return R;
19154   }
19155
19156   // Decompose 256-bit shifts into smaller 128-bit shifts.
19157   if (VT.is256BitVector()) {
19158     unsigned NumElems = VT.getVectorNumElements();
19159     MVT EltVT = VT.getVectorElementType();
19160     MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19161
19162     // Extract the two vectors
19163     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
19164     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
19165
19166     // Recreate the shift amount vectors
19167     SDValue Amt1, Amt2;
19168     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
19169       // Constant shift amount
19170       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
19171       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
19172       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
19173
19174       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
19175       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
19176     } else {
19177       // Variable shift amount
19178       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19179       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19180     }
19181
19182     // Issue new vector shifts for the smaller types
19183     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19184     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19185
19186     // Concatenate the result back
19187     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19188   }
19189
19190   return SDValue();
19191 }
19192
19193 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19194                            SelectionDAG &DAG) {
19195   MVT VT = Op.getSimpleValueType();
19196   SDLoc DL(Op);
19197   SDValue R = Op.getOperand(0);
19198   SDValue Amt = Op.getOperand(1);
19199
19200   assert(VT.isVector() && "Custom lowering only for vector rotates!");
19201   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19202   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19203
19204   // XOP has 128-bit vector variable + immediate rotates.
19205   // +ve/-ve Amt = rotate left/right.
19206
19207   // Split 256-bit integers.
19208   if (VT.is256BitVector())
19209     return Lower256IntArith(Op, DAG);
19210
19211   assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19212
19213   // Attempt to rotate by immediate.
19214   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19215     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19216       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19217       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19218       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19219                          DAG.getConstant(RotateAmt, DL, MVT::i8));
19220     }
19221   }
19222
19223   // Use general rotate by variable (per-element).
19224   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19225 }
19226
19227 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19228   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19229   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19230   // looks for this combo and may remove the "setcc" instruction if the "setcc"
19231   // has only one use.
19232   SDNode *N = Op.getNode();
19233   SDValue LHS = N->getOperand(0);
19234   SDValue RHS = N->getOperand(1);
19235   unsigned BaseOp = 0;
19236   unsigned Cond = 0;
19237   SDLoc DL(Op);
19238   switch (Op.getOpcode()) {
19239   default: llvm_unreachable("Unknown ovf instruction!");
19240   case ISD::SADDO:
19241     // A subtract of one will be selected as a INC. Note that INC doesn't
19242     // set CF, so we can't do this for UADDO.
19243     if (isOneConstant(RHS)) {
19244         BaseOp = X86ISD::INC;
19245         Cond = X86::COND_O;
19246         break;
19247       }
19248     BaseOp = X86ISD::ADD;
19249     Cond = X86::COND_O;
19250     break;
19251   case ISD::UADDO:
19252     BaseOp = X86ISD::ADD;
19253     Cond = X86::COND_B;
19254     break;
19255   case ISD::SSUBO:
19256     // A subtract of one will be selected as a DEC. Note that DEC doesn't
19257     // set CF, so we can't do this for USUBO.
19258     if (isOneConstant(RHS)) {
19259         BaseOp = X86ISD::DEC;
19260         Cond = X86::COND_O;
19261         break;
19262       }
19263     BaseOp = X86ISD::SUB;
19264     Cond = X86::COND_O;
19265     break;
19266   case ISD::USUBO:
19267     BaseOp = X86ISD::SUB;
19268     Cond = X86::COND_B;
19269     break;
19270   case ISD::SMULO:
19271     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19272     Cond = X86::COND_O;
19273     break;
19274   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19275     if (N->getValueType(0) == MVT::i8) {
19276       BaseOp = X86ISD::UMUL8;
19277       Cond = X86::COND_O;
19278       break;
19279     }
19280     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19281                                  MVT::i32);
19282     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19283
19284     SDValue SetCC =
19285       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19286                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
19287                   SDValue(Sum.getNode(), 2));
19288
19289     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19290   }
19291   }
19292
19293   // Also sets EFLAGS.
19294   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19295   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19296
19297   SDValue SetCC =
19298     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19299                 DAG.getConstant(Cond, DL, MVT::i32),
19300                 SDValue(Sum.getNode(), 1));
19301
19302   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19303 }
19304
19305 /// Returns true if the operand type is exactly twice the native width, and
19306 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19307 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19308 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19309 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19310   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19311
19312   if (OpWidth == 64)
19313     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19314   else if (OpWidth == 128)
19315     return Subtarget->hasCmpxchg16b();
19316   else
19317     return false;
19318 }
19319
19320 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19321   return needsCmpXchgNb(SI->getValueOperand()->getType());
19322 }
19323
19324 // Note: this turns large loads into lock cmpxchg8b/16b.
19325 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19326 TargetLowering::AtomicExpansionKind
19327 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19328   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19329   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19330                                                : AtomicExpansionKind::None;
19331 }
19332
19333 TargetLowering::AtomicExpansionKind
19334 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19335   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19336   Type *MemType = AI->getType();
19337
19338   // If the operand is too big, we must see if cmpxchg8/16b is available
19339   // and default to library calls otherwise.
19340   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19341     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19342                                    : AtomicExpansionKind::None;
19343   }
19344
19345   AtomicRMWInst::BinOp Op = AI->getOperation();
19346   switch (Op) {
19347   default:
19348     llvm_unreachable("Unknown atomic operation");
19349   case AtomicRMWInst::Xchg:
19350   case AtomicRMWInst::Add:
19351   case AtomicRMWInst::Sub:
19352     // It's better to use xadd, xsub or xchg for these in all cases.
19353     return AtomicExpansionKind::None;
19354   case AtomicRMWInst::Or:
19355   case AtomicRMWInst::And:
19356   case AtomicRMWInst::Xor:
19357     // If the atomicrmw's result isn't actually used, we can just add a "lock"
19358     // prefix to a normal instruction for these operations.
19359     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19360                             : AtomicExpansionKind::None;
19361   case AtomicRMWInst::Nand:
19362   case AtomicRMWInst::Max:
19363   case AtomicRMWInst::Min:
19364   case AtomicRMWInst::UMax:
19365   case AtomicRMWInst::UMin:
19366     // These always require a non-trivial set of data operations on x86. We must
19367     // use a cmpxchg loop.
19368     return AtomicExpansionKind::CmpXChg;
19369   }
19370 }
19371
19372 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19373   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19374   // no-sse2). There isn't any reason to disable it if the target processor
19375   // supports it.
19376   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19377 }
19378
19379 LoadInst *
19380 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19381   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19382   Type *MemType = AI->getType();
19383   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19384   // there is no benefit in turning such RMWs into loads, and it is actually
19385   // harmful as it introduces a mfence.
19386   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19387     return nullptr;
19388
19389   auto Builder = IRBuilder<>(AI);
19390   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19391   auto SynchScope = AI->getSynchScope();
19392   // We must restrict the ordering to avoid generating loads with Release or
19393   // ReleaseAcquire orderings.
19394   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19395   auto Ptr = AI->getPointerOperand();
19396
19397   // Before the load we need a fence. Here is an example lifted from
19398   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19399   // is required:
19400   // Thread 0:
19401   //   x.store(1, relaxed);
19402   //   r1 = y.fetch_add(0, release);
19403   // Thread 1:
19404   //   y.fetch_add(42, acquire);
19405   //   r2 = x.load(relaxed);
19406   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19407   // lowered to just a load without a fence. A mfence flushes the store buffer,
19408   // making the optimization clearly correct.
19409   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19410   // otherwise, we might be able to be more aggressive on relaxed idempotent
19411   // rmw. In practice, they do not look useful, so we don't try to be
19412   // especially clever.
19413   if (SynchScope == SingleThread)
19414     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19415     // the IR level, so we must wrap it in an intrinsic.
19416     return nullptr;
19417
19418   if (!hasMFENCE(*Subtarget))
19419     // FIXME: it might make sense to use a locked operation here but on a
19420     // different cache-line to prevent cache-line bouncing. In practice it
19421     // is probably a small win, and x86 processors without mfence are rare
19422     // enough that we do not bother.
19423     return nullptr;
19424
19425   Function *MFence =
19426       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19427   Builder.CreateCall(MFence, {});
19428
19429   // Finally we can emit the atomic load.
19430   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19431           AI->getType()->getPrimitiveSizeInBits());
19432   Loaded->setAtomic(Order, SynchScope);
19433   AI->replaceAllUsesWith(Loaded);
19434   AI->eraseFromParent();
19435   return Loaded;
19436 }
19437
19438 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19439                                  SelectionDAG &DAG) {
19440   SDLoc dl(Op);
19441   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19442     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19443   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19444     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19445
19446   // The only fence that needs an instruction is a sequentially-consistent
19447   // cross-thread fence.
19448   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19449     if (hasMFENCE(*Subtarget))
19450       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19451
19452     SDValue Chain = Op.getOperand(0);
19453     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19454     SDValue Ops[] = {
19455       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19456       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19457       DAG.getRegister(0, MVT::i32),            // Index
19458       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19459       DAG.getRegister(0, MVT::i32),            // Segment.
19460       Zero,
19461       Chain
19462     };
19463     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19464     return SDValue(Res, 0);
19465   }
19466
19467   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19468   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19469 }
19470
19471 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19472                              SelectionDAG &DAG) {
19473   MVT T = Op.getSimpleValueType();
19474   SDLoc DL(Op);
19475   unsigned Reg = 0;
19476   unsigned size = 0;
19477   switch(T.SimpleTy) {
19478   default: llvm_unreachable("Invalid value type!");
19479   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19480   case MVT::i16: Reg = X86::AX;  size = 2; break;
19481   case MVT::i32: Reg = X86::EAX; size = 4; break;
19482   case MVT::i64:
19483     assert(Subtarget->is64Bit() && "Node not type legal!");
19484     Reg = X86::RAX; size = 8;
19485     break;
19486   }
19487   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19488                                   Op.getOperand(2), SDValue());
19489   SDValue Ops[] = { cpIn.getValue(0),
19490                     Op.getOperand(1),
19491                     Op.getOperand(3),
19492                     DAG.getTargetConstant(size, DL, MVT::i8),
19493                     cpIn.getValue(1) };
19494   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19495   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19496   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19497                                            Ops, T, MMO);
19498
19499   SDValue cpOut =
19500     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19501   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19502                                       MVT::i32, cpOut.getValue(2));
19503   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19504                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19505                                 EFLAGS);
19506
19507   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19508   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19509   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19510   return SDValue();
19511 }
19512
19513 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19514                             SelectionDAG &DAG) {
19515   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19516   MVT DstVT = Op.getSimpleValueType();
19517
19518   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19519     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19520     if (DstVT != MVT::f64)
19521       // This conversion needs to be expanded.
19522       return SDValue();
19523
19524     SDValue InVec = Op->getOperand(0);
19525     SDLoc dl(Op);
19526     unsigned NumElts = SrcVT.getVectorNumElements();
19527     MVT SVT = SrcVT.getVectorElementType();
19528
19529     // Widen the vector in input in the case of MVT::v2i32.
19530     // Example: from MVT::v2i32 to MVT::v4i32.
19531     SmallVector<SDValue, 16> Elts;
19532     for (unsigned i = 0, e = NumElts; i != e; ++i)
19533       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19534                                  DAG.getIntPtrConstant(i, dl)));
19535
19536     // Explicitly mark the extra elements as Undef.
19537     Elts.append(NumElts, DAG.getUNDEF(SVT));
19538
19539     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19540     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19541     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19542     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19543                        DAG.getIntPtrConstant(0, dl));
19544   }
19545
19546   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19547          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19548   assert((DstVT == MVT::i64 ||
19549           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19550          "Unexpected custom BITCAST");
19551   // i64 <=> MMX conversions are Legal.
19552   if (SrcVT==MVT::i64 && DstVT.isVector())
19553     return Op;
19554   if (DstVT==MVT::i64 && SrcVT.isVector())
19555     return Op;
19556   // MMX <=> MMX conversions are Legal.
19557   if (SrcVT.isVector() && DstVT.isVector())
19558     return Op;
19559   // All other conversions need to be expanded.
19560   return SDValue();
19561 }
19562
19563 /// Compute the horizontal sum of bytes in V for the elements of VT.
19564 ///
19565 /// Requires V to be a byte vector and VT to be an integer vector type with
19566 /// wider elements than V's type. The width of the elements of VT determines
19567 /// how many bytes of V are summed horizontally to produce each element of the
19568 /// result.
19569 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19570                                       const X86Subtarget *Subtarget,
19571                                       SelectionDAG &DAG) {
19572   SDLoc DL(V);
19573   MVT ByteVecVT = V.getSimpleValueType();
19574   MVT EltVT = VT.getVectorElementType();
19575   int NumElts = VT.getVectorNumElements();
19576   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19577          "Expected value to have byte element type.");
19578   assert(EltVT != MVT::i8 &&
19579          "Horizontal byte sum only makes sense for wider elements!");
19580   unsigned VecSize = VT.getSizeInBits();
19581   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19582
19583   // PSADBW instruction horizontally add all bytes and leave the result in i64
19584   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19585   if (EltVT == MVT::i64) {
19586     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19587     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19588     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19589     return DAG.getBitcast(VT, V);
19590   }
19591
19592   if (EltVT == MVT::i32) {
19593     // We unpack the low half and high half into i32s interleaved with zeros so
19594     // that we can use PSADBW to horizontally sum them. The most useful part of
19595     // this is that it lines up the results of two PSADBW instructions to be
19596     // two v2i64 vectors which concatenated are the 4 population counts. We can
19597     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19598     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19599     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19600     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19601
19602     // Do the horizontal sums into two v2i64s.
19603     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19604     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19605     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19606                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19607     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19608                        DAG.getBitcast(ByteVecVT, High), Zeros);
19609
19610     // Merge them together.
19611     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19612     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19613                     DAG.getBitcast(ShortVecVT, Low),
19614                     DAG.getBitcast(ShortVecVT, High));
19615
19616     return DAG.getBitcast(VT, V);
19617   }
19618
19619   // The only element type left is i16.
19620   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19621
19622   // To obtain pop count for each i16 element starting from the pop count for
19623   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19624   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19625   // directly supported.
19626   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19627   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19628   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19629   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19630                   DAG.getBitcast(ByteVecVT, V));
19631   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19632 }
19633
19634 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19635                                         const X86Subtarget *Subtarget,
19636                                         SelectionDAG &DAG) {
19637   MVT VT = Op.getSimpleValueType();
19638   MVT EltVT = VT.getVectorElementType();
19639   unsigned VecSize = VT.getSizeInBits();
19640
19641   // Implement a lookup table in register by using an algorithm based on:
19642   // http://wm.ite.pl/articles/sse-popcount.html
19643   //
19644   // The general idea is that every lower byte nibble in the input vector is an
19645   // index into a in-register pre-computed pop count table. We then split up the
19646   // input vector in two new ones: (1) a vector with only the shifted-right
19647   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19648   // masked out higher ones) for each byte. PSHUB is used separately with both
19649   // to index the in-register table. Next, both are added and the result is a
19650   // i8 vector where each element contains the pop count for input byte.
19651   //
19652   // To obtain the pop count for elements != i8, we follow up with the same
19653   // approach and use additional tricks as described below.
19654   //
19655   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19656                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19657                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19658                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19659
19660   int NumByteElts = VecSize / 8;
19661   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19662   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19663   SmallVector<SDValue, 16> LUTVec;
19664   for (int i = 0; i < NumByteElts; ++i)
19665     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19666   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19667   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19668                                   DAG.getConstant(0x0F, DL, MVT::i8));
19669   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19670
19671   // High nibbles
19672   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19673   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19674   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19675
19676   // Low nibbles
19677   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19678
19679   // The input vector is used as the shuffle mask that index elements into the
19680   // LUT. After counting low and high nibbles, add the vector to obtain the
19681   // final pop count per i8 element.
19682   SDValue HighPopCnt =
19683       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19684   SDValue LowPopCnt =
19685       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19686   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19687
19688   if (EltVT == MVT::i8)
19689     return PopCnt;
19690
19691   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19692 }
19693
19694 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19695                                        const X86Subtarget *Subtarget,
19696                                        SelectionDAG &DAG) {
19697   MVT VT = Op.getSimpleValueType();
19698   assert(VT.is128BitVector() &&
19699          "Only 128-bit vector bitmath lowering supported.");
19700
19701   int VecSize = VT.getSizeInBits();
19702   MVT EltVT = VT.getVectorElementType();
19703   int Len = EltVT.getSizeInBits();
19704
19705   // This is the vectorized version of the "best" algorithm from
19706   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19707   // with a minor tweak to use a series of adds + shifts instead of vector
19708   // multiplications. Implemented for all integer vector types. We only use
19709   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19710   // much faster, even faster than using native popcnt instructions.
19711
19712   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19713     MVT VT = V.getSimpleValueType();
19714     SmallVector<SDValue, 32> Shifters(
19715         VT.getVectorNumElements(),
19716         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19717     return DAG.getNode(OpCode, DL, VT, V,
19718                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19719   };
19720   auto GetMask = [&](SDValue V, APInt Mask) {
19721     MVT VT = V.getSimpleValueType();
19722     SmallVector<SDValue, 32> Masks(
19723         VT.getVectorNumElements(),
19724         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19725     return DAG.getNode(ISD::AND, DL, VT, V,
19726                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19727   };
19728
19729   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19730   // x86, so set the SRL type to have elements at least i16 wide. This is
19731   // correct because all of our SRLs are followed immediately by a mask anyways
19732   // that handles any bits that sneak into the high bits of the byte elements.
19733   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19734
19735   SDValue V = Op;
19736
19737   // v = v - ((v >> 1) & 0x55555555...)
19738   SDValue Srl =
19739       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19740   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19741   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19742
19743   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19744   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19745   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19746   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19747   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19748
19749   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19750   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19751   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19752   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19753
19754   // At this point, V contains the byte-wise population count, and we are
19755   // merely doing a horizontal sum if necessary to get the wider element
19756   // counts.
19757   if (EltVT == MVT::i8)
19758     return V;
19759
19760   return LowerHorizontalByteSum(
19761       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19762       DAG);
19763 }
19764
19765 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19766                                 SelectionDAG &DAG) {
19767   MVT VT = Op.getSimpleValueType();
19768   // FIXME: Need to add AVX-512 support here!
19769   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19770          "Unknown CTPOP type to handle");
19771   SDLoc DL(Op.getNode());
19772   SDValue Op0 = Op.getOperand(0);
19773
19774   if (!Subtarget->hasSSSE3()) {
19775     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19776     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19777     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19778   }
19779
19780   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19781     unsigned NumElems = VT.getVectorNumElements();
19782
19783     // Extract each 128-bit vector, compute pop count and concat the result.
19784     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19785     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19786
19787     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19788                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19789                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19790   }
19791
19792   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19793 }
19794
19795 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19796                           SelectionDAG &DAG) {
19797   assert(Op.getSimpleValueType().isVector() &&
19798          "We only do custom lowering for vector population count.");
19799   return LowerVectorCTPOP(Op, Subtarget, DAG);
19800 }
19801
19802 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19803   SDNode *Node = Op.getNode();
19804   SDLoc dl(Node);
19805   EVT T = Node->getValueType(0);
19806   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19807                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19808   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19809                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19810                        Node->getOperand(0),
19811                        Node->getOperand(1), negOp,
19812                        cast<AtomicSDNode>(Node)->getMemOperand(),
19813                        cast<AtomicSDNode>(Node)->getOrdering(),
19814                        cast<AtomicSDNode>(Node)->getSynchScope());
19815 }
19816
19817 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19818   SDNode *Node = Op.getNode();
19819   SDLoc dl(Node);
19820   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19821
19822   // Convert seq_cst store -> xchg
19823   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19824   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19825   //        (The only way to get a 16-byte store is cmpxchg16b)
19826   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19827   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19828       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19829     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19830                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19831                                  Node->getOperand(0),
19832                                  Node->getOperand(1), Node->getOperand(2),
19833                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19834                                  cast<AtomicSDNode>(Node)->getOrdering(),
19835                                  cast<AtomicSDNode>(Node)->getSynchScope());
19836     return Swap.getValue(1);
19837   }
19838   // Other atomic stores have a simple pattern.
19839   return Op;
19840 }
19841
19842 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19843   MVT VT = Op.getNode()->getSimpleValueType(0);
19844
19845   // Let legalize expand this if it isn't a legal type yet.
19846   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19847     return SDValue();
19848
19849   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19850
19851   unsigned Opc;
19852   bool ExtraOp = false;
19853   switch (Op.getOpcode()) {
19854   default: llvm_unreachable("Invalid code");
19855   case ISD::ADDC: Opc = X86ISD::ADD; break;
19856   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19857   case ISD::SUBC: Opc = X86ISD::SUB; break;
19858   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19859   }
19860
19861   if (!ExtraOp)
19862     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19863                        Op.getOperand(1));
19864   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19865                      Op.getOperand(1), Op.getOperand(2));
19866 }
19867
19868 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19869                             SelectionDAG &DAG) {
19870   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19871
19872   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19873   // which returns the values as { float, float } (in XMM0) or
19874   // { double, double } (which is returned in XMM0, XMM1).
19875   SDLoc dl(Op);
19876   SDValue Arg = Op.getOperand(0);
19877   EVT ArgVT = Arg.getValueType();
19878   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19879
19880   TargetLowering::ArgListTy Args;
19881   TargetLowering::ArgListEntry Entry;
19882
19883   Entry.Node = Arg;
19884   Entry.Ty = ArgTy;
19885   Entry.isSExt = false;
19886   Entry.isZExt = false;
19887   Args.push_back(Entry);
19888
19889   bool isF64 = ArgVT == MVT::f64;
19890   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19891   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19892   // the results are returned via SRet in memory.
19893   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19894   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19895   SDValue Callee =
19896       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19897
19898   Type *RetTy = isF64
19899     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19900     : (Type*)VectorType::get(ArgTy, 4);
19901
19902   TargetLowering::CallLoweringInfo CLI(DAG);
19903   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19904     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19905
19906   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19907
19908   if (isF64)
19909     // Returned in xmm0 and xmm1.
19910     return CallResult.first;
19911
19912   // Returned in bits 0:31 and 32:64 xmm0.
19913   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19914                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19915   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19916                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19917   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19918   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19919 }
19920
19921 /// Widen a vector input to a vector of NVT.  The
19922 /// input vector must have the same element type as NVT.
19923 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
19924                             bool FillWithZeroes = false) {
19925   // Check if InOp already has the right width.
19926   MVT InVT = InOp.getSimpleValueType();
19927   if (InVT == NVT)
19928     return InOp;
19929
19930   if (InOp.isUndef())
19931     return DAG.getUNDEF(NVT);
19932
19933   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
19934          "input and widen element type must match");
19935
19936   unsigned InNumElts = InVT.getVectorNumElements();
19937   unsigned WidenNumElts = NVT.getVectorNumElements();
19938   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
19939          "Unexpected request for vector widening");
19940
19941   EVT EltVT = NVT.getVectorElementType();
19942
19943   SDLoc dl(InOp);
19944   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
19945       InOp.getNumOperands() == 2) {
19946     SDValue N1 = InOp.getOperand(1);
19947     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
19948         N1.isUndef()) {
19949       InOp = InOp.getOperand(0);
19950       InVT = InOp.getSimpleValueType();
19951       InNumElts = InVT.getVectorNumElements();
19952     }
19953   }
19954   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
19955       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
19956     SmallVector<SDValue, 16> Ops;
19957     for (unsigned i = 0; i < InNumElts; ++i)
19958       Ops.push_back(InOp.getOperand(i));
19959
19960     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
19961       DAG.getUNDEF(EltVT);
19962     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
19963       Ops.push_back(FillVal);
19964     return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
19965   }
19966   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
19967     DAG.getUNDEF(NVT);
19968   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
19969                      InOp, DAG.getIntPtrConstant(0, dl));
19970 }
19971
19972 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19973                              SelectionDAG &DAG) {
19974   assert(Subtarget->hasAVX512() &&
19975          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19976
19977   // X86 scatter kills mask register, so its type should be added to
19978   // the list of return values.
19979   // If the "scatter" has 2 return values, it is already handled.
19980   if (Op.getNode()->getNumValues() == 2)
19981     return Op;
19982
19983   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19984   SDValue Src = N->getValue();
19985   MVT VT = Src.getSimpleValueType();
19986   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19987   SDLoc dl(Op);
19988
19989   SDValue NewScatter;
19990   SDValue Index = N->getIndex();
19991   SDValue Mask = N->getMask();
19992   SDValue Chain = N->getChain();
19993   SDValue BasePtr = N->getBasePtr();
19994   MVT MemVT = N->getMemoryVT().getSimpleVT();
19995   MVT IndexVT = Index.getSimpleValueType();
19996   MVT MaskVT = Mask.getSimpleValueType();
19997
19998   if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
19999     // The v2i32 value was promoted to v2i64.
20000     // Now we "redo" the type legalizer's work and widen the original
20001     // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
20002     // with a shuffle.
20003     assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
20004            "Unexpected memory type");
20005     int ShuffleMask[] = {0, 2, -1, -1};
20006     Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
20007                                DAG.getUNDEF(MVT::v4i32), ShuffleMask);
20008     // Now we have 4 elements instead of 2.
20009     // Expand the index.
20010     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
20011     Index = ExtendToType(Index, NewIndexVT, DAG);
20012
20013     // Expand the mask with zeroes
20014     // Mask may be <2 x i64> or <2 x i1> at this moment
20015     assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
20016            "Unexpected mask type");
20017     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
20018     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20019     VT = MVT::v4i32;
20020   }
20021
20022   unsigned NumElts = VT.getVectorNumElements();
20023   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20024       !Index.getSimpleValueType().is512BitVector()) {
20025     // AVX512F supports only 512-bit vectors. Or data or index should
20026     // be 512 bit wide. If now the both index and data are 256-bit, but
20027     // the vector contains 8 elements, we just sign-extend the index
20028     if (IndexVT == MVT::v8i32)
20029       // Just extend index
20030       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20031     else {
20032       // The minimal number of elts in scatter is 8
20033       NumElts = 8;
20034       // Index
20035       MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20036       // Use original index here, do not modify the index twice
20037       Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
20038       if (IndexVT.getScalarType() == MVT::i32)
20039         Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20040
20041       // Mask
20042       // At this point we have promoted mask operand
20043       assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20044       MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20045       // Use the original mask here, do not modify the mask twice
20046       Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true);
20047
20048       // The value that should be stored
20049       MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20050       Src = ExtendToType(Src, NewVT, DAG);
20051     }
20052   }
20053   // If the mask is "wide" at this point - truncate it to i1 vector
20054   MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
20055   Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
20056
20057   // The mask is killed by scatter, add it to the values
20058   SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
20059   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
20060   NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
20061                                     N->getMemOperand());
20062   DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
20063   return SDValue(NewScatter.getNode(), 0);
20064 }
20065
20066 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
20067                           SelectionDAG &DAG) {
20068
20069   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
20070   MVT VT = Op.getSimpleValueType();
20071   SDValue Mask = N->getMask();
20072   SDLoc dl(Op);
20073
20074   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20075       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20076     // This operation is legal for targets with VLX, but without
20077     // VLX the vector should be widened to 512 bit
20078     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20079     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20080     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20081     SDValue Src0 = N->getSrc0();
20082     Src0 = ExtendToType(Src0, WideDataVT, DAG);
20083     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20084     SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
20085                                         N->getBasePtr(), Mask, Src0,
20086                                         N->getMemoryVT(), N->getMemOperand(),
20087                                         N->getExtensionType());
20088
20089     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20090                                  NewLoad.getValue(0),
20091                                  DAG.getIntPtrConstant(0, dl));
20092     SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
20093     return DAG.getMergeValues(RetOps, dl);
20094   }
20095   return Op;
20096 }
20097
20098 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
20099                            SelectionDAG &DAG) {
20100   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
20101   SDValue DataToStore = N->getValue();
20102   MVT VT = DataToStore.getSimpleValueType();
20103   SDValue Mask = N->getMask();
20104   SDLoc dl(Op);
20105
20106   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20107       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20108     // This operation is legal for targets with VLX, but without
20109     // VLX the vector should be widened to 512 bit
20110     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20111     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20112     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20113     DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
20114     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20115     return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
20116                               Mask, N->getMemoryVT(), N->getMemOperand(),
20117                               N->isTruncatingStore());
20118   }
20119   return Op;
20120 }
20121
20122 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
20123                             SelectionDAG &DAG) {
20124   assert(Subtarget->hasAVX512() &&
20125          "MGATHER/MSCATTER are supported on AVX-512 arch only");
20126
20127   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
20128   SDLoc dl(Op);
20129   MVT VT = Op.getSimpleValueType();
20130   SDValue Index = N->getIndex();
20131   SDValue Mask = N->getMask();
20132   SDValue Src0 = N->getValue();
20133   MVT IndexVT = Index.getSimpleValueType();
20134   MVT MaskVT = Mask.getSimpleValueType();
20135
20136   unsigned NumElts = VT.getVectorNumElements();
20137   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
20138
20139   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20140       !Index.getSimpleValueType().is512BitVector()) {
20141     // AVX512F supports only 512-bit vectors. Or data or index should
20142     // be 512 bit wide. If now the both index and data are 256-bit, but
20143     // the vector contains 8 elements, we just sign-extend the index
20144     if (NumElts == 8) {
20145       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20146       SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
20147                         N->getOperand(3), Index };
20148       DAG.UpdateNodeOperands(N, Ops);
20149       return Op;
20150     }
20151
20152     // Minimal number of elements in Gather
20153     NumElts = 8;
20154     // Index
20155     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20156     Index = ExtendToType(Index, NewIndexVT, DAG);
20157     if (IndexVT.getScalarType() == MVT::i32)
20158       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20159
20160     // Mask
20161     MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
20162     // At this point we have promoted mask operand
20163     assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20164     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20165     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20166     Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
20167
20168     // The pass-thru value
20169     MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20170     Src0 = ExtendToType(Src0, NewVT, DAG);
20171
20172     SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
20173     SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
20174                                             N->getMemoryVT(), dl, Ops,
20175                                             N->getMemOperand());
20176     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20177                                  NewGather.getValue(0),
20178                                  DAG.getIntPtrConstant(0, dl));
20179     SDValue RetOps[] = {Exract, NewGather.getValue(1)};
20180     return DAG.getMergeValues(RetOps, dl);
20181   }
20182   return Op;
20183 }
20184
20185 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
20186                                                     SelectionDAG &DAG) const {
20187   // TODO: Eventually, the lowering of these nodes should be informed by or
20188   // deferred to the GC strategy for the function in which they appear. For
20189   // now, however, they must be lowered to something. Since they are logically
20190   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20191   // require special handling for these nodes), lower them as literal NOOPs for
20192   // the time being.
20193   SmallVector<SDValue, 2> Ops;
20194
20195   Ops.push_back(Op.getOperand(0));
20196   if (Op->getGluedNode())
20197     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20198
20199   SDLoc OpDL(Op);
20200   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20201   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20202
20203   return NOOP;
20204 }
20205
20206 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
20207                                                   SelectionDAG &DAG) const {
20208   // TODO: Eventually, the lowering of these nodes should be informed by or
20209   // deferred to the GC strategy for the function in which they appear. For
20210   // now, however, they must be lowered to something. Since they are logically
20211   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20212   // require special handling for these nodes), lower them as literal NOOPs for
20213   // the time being.
20214   SmallVector<SDValue, 2> Ops;
20215
20216   Ops.push_back(Op.getOperand(0));
20217   if (Op->getGluedNode())
20218     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20219
20220   SDLoc OpDL(Op);
20221   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20222   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20223
20224   return NOOP;
20225 }
20226
20227 /// LowerOperation - Provide custom lowering hooks for some operations.
20228 ///
20229 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
20230   switch (Op.getOpcode()) {
20231   default: llvm_unreachable("Should not custom lower this!");
20232   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
20233   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
20234     return LowerCMP_SWAP(Op, Subtarget, DAG);
20235   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
20236   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
20237   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
20238   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
20239   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
20240   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
20241   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
20242   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
20243   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
20244   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
20245   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
20246   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
20247   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
20248   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
20249   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
20250   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
20251   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
20252   case ISD::SHL_PARTS:
20253   case ISD::SRA_PARTS:
20254   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
20255   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
20256   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
20257   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
20258   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
20259   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
20260   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
20261   case ISD::SIGN_EXTEND_VECTOR_INREG:
20262     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
20263   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
20264   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
20265   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
20266   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
20267   case ISD::FABS:
20268   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
20269   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
20270   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
20271   case ISD::SETCC:              return LowerSETCC(Op, DAG);
20272   case ISD::SETCCE:             return LowerSETCCE(Op, DAG);
20273   case ISD::SELECT:             return LowerSELECT(Op, DAG);
20274   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
20275   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
20276   case ISD::VASTART:            return LowerVASTART(Op, DAG);
20277   case ISD::VAARG:              return LowerVAARG(Op, DAG);
20278   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
20279   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
20280   case ISD::INTRINSIC_VOID:
20281   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
20282   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
20283   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
20284   case ISD::FRAME_TO_ARGS_OFFSET:
20285                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
20286   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
20287   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
20288   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
20289   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
20290   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
20291   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
20292   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
20293   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
20294   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
20295   case ISD::CTTZ:
20296   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
20297   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
20298   case ISD::UMUL_LOHI:
20299   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
20300   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
20301   case ISD::SRA:
20302   case ISD::SRL:
20303   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
20304   case ISD::SADDO:
20305   case ISD::UADDO:
20306   case ISD::SSUBO:
20307   case ISD::USUBO:
20308   case ISD::SMULO:
20309   case ISD::UMULO:              return LowerXALUO(Op, DAG);
20310   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20311   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
20312   case ISD::ADDC:
20313   case ISD::ADDE:
20314   case ISD::SUBC:
20315   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20316   case ISD::ADD:                return LowerADD(Op, DAG);
20317   case ISD::SUB:                return LowerSUB(Op, DAG);
20318   case ISD::SMAX:
20319   case ISD::SMIN:
20320   case ISD::UMAX:
20321   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
20322   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
20323   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
20324   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
20325   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
20326   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
20327   case ISD::GC_TRANSITION_START:
20328                                 return LowerGC_TRANSITION_START(Op, DAG);
20329   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
20330   }
20331 }
20332
20333 /// ReplaceNodeResults - Replace a node with an illegal result type
20334 /// with a new node built out of custom code.
20335 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20336                                            SmallVectorImpl<SDValue>&Results,
20337                                            SelectionDAG &DAG) const {
20338   SDLoc dl(N);
20339   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20340   switch (N->getOpcode()) {
20341   default:
20342     llvm_unreachable("Do not know how to custom type legalize this operation!");
20343   case X86ISD::AVG: {
20344     // Legalize types for X86ISD::AVG by expanding vectors.
20345     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20346
20347     auto InVT = N->getValueType(0);
20348     auto InVTSize = InVT.getSizeInBits();
20349     const unsigned RegSize =
20350         (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20351     assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20352            "512-bit vector requires AVX512");
20353     assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20354            "256-bit vector requires AVX2");
20355
20356     auto ElemVT = InVT.getVectorElementType();
20357     auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20358                                   RegSize / ElemVT.getSizeInBits());
20359     assert(RegSize % InVT.getSizeInBits() == 0);
20360     unsigned NumConcat = RegSize / InVT.getSizeInBits();
20361
20362     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20363     Ops[0] = N->getOperand(0);
20364     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20365     Ops[0] = N->getOperand(1);
20366     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20367
20368     SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20369     Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20370                                   DAG.getIntPtrConstant(0, dl)));
20371     return;
20372   }
20373   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20374   case X86ISD::FMINC:
20375   case X86ISD::FMIN:
20376   case X86ISD::FMAXC:
20377   case X86ISD::FMAX: {
20378     EVT VT = N->getValueType(0);
20379     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20380     SDValue UNDEF = DAG.getUNDEF(VT);
20381     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20382                               N->getOperand(0), UNDEF);
20383     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20384                               N->getOperand(1), UNDEF);
20385     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20386     return;
20387   }
20388   case ISD::SIGN_EXTEND_INREG:
20389   case ISD::ADDC:
20390   case ISD::ADDE:
20391   case ISD::SUBC:
20392   case ISD::SUBE:
20393     // We don't want to expand or promote these.
20394     return;
20395   case ISD::SDIV:
20396   case ISD::UDIV:
20397   case ISD::SREM:
20398   case ISD::UREM:
20399   case ISD::SDIVREM:
20400   case ISD::UDIVREM: {
20401     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20402     Results.push_back(V);
20403     return;
20404   }
20405   case ISD::FP_TO_SINT:
20406   case ISD::FP_TO_UINT: {
20407     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20408
20409     std::pair<SDValue,SDValue> Vals =
20410         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20411     SDValue FIST = Vals.first, StackSlot = Vals.second;
20412     if (FIST.getNode()) {
20413       EVT VT = N->getValueType(0);
20414       // Return a load from the stack slot.
20415       if (StackSlot.getNode())
20416         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20417                                       MachinePointerInfo(),
20418                                       false, false, false, 0));
20419       else
20420         Results.push_back(FIST);
20421     }
20422     return;
20423   }
20424   case ISD::UINT_TO_FP: {
20425     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20426     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20427         N->getValueType(0) != MVT::v2f32)
20428       return;
20429     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20430                                  N->getOperand(0));
20431     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20432                                      MVT::f64);
20433     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20434     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20435                              DAG.getBitcast(MVT::v2i64, VBias));
20436     Or = DAG.getBitcast(MVT::v2f64, Or);
20437     // TODO: Are there any fast-math-flags to propagate here?
20438     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20439     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20440     return;
20441   }
20442   case ISD::FP_ROUND: {
20443     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20444         return;
20445     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20446     Results.push_back(V);
20447     return;
20448   }
20449   case ISD::FP_EXTEND: {
20450     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20451     // No other ValueType for FP_EXTEND should reach this point.
20452     assert(N->getValueType(0) == MVT::v2f32 &&
20453            "Do not know how to legalize this Node");
20454     return;
20455   }
20456   case ISD::INTRINSIC_W_CHAIN: {
20457     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20458     switch (IntNo) {
20459     default : llvm_unreachable("Do not know how to custom type "
20460                                "legalize this intrinsic operation!");
20461     case Intrinsic::x86_rdtsc:
20462       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20463                                      Results);
20464     case Intrinsic::x86_rdtscp:
20465       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20466                                      Results);
20467     case Intrinsic::x86_rdpmc:
20468       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20469     }
20470   }
20471   case ISD::INTRINSIC_WO_CHAIN: {
20472     if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20473       Results.push_back(V);
20474     return;
20475   }
20476   case ISD::READCYCLECOUNTER: {
20477     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20478                                    Results);
20479   }
20480   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20481     EVT T = N->getValueType(0);
20482     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20483     bool Regs64bit = T == MVT::i128;
20484     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20485     SDValue cpInL, cpInH;
20486     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20487                         DAG.getConstant(0, dl, HalfT));
20488     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20489                         DAG.getConstant(1, dl, HalfT));
20490     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20491                              Regs64bit ? X86::RAX : X86::EAX,
20492                              cpInL, SDValue());
20493     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20494                              Regs64bit ? X86::RDX : X86::EDX,
20495                              cpInH, cpInL.getValue(1));
20496     SDValue swapInL, swapInH;
20497     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20498                           DAG.getConstant(0, dl, HalfT));
20499     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20500                           DAG.getConstant(1, dl, HalfT));
20501     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20502                                Regs64bit ? X86::RBX : X86::EBX,
20503                                swapInL, cpInH.getValue(1));
20504     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20505                                Regs64bit ? X86::RCX : X86::ECX,
20506                                swapInH, swapInL.getValue(1));
20507     SDValue Ops[] = { swapInH.getValue(0),
20508                       N->getOperand(1),
20509                       swapInH.getValue(1) };
20510     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20511     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20512     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20513                                   X86ISD::LCMPXCHG8_DAG;
20514     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20515     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20516                                         Regs64bit ? X86::RAX : X86::EAX,
20517                                         HalfT, Result.getValue(1));
20518     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20519                                         Regs64bit ? X86::RDX : X86::EDX,
20520                                         HalfT, cpOutL.getValue(2));
20521     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20522
20523     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20524                                         MVT::i32, cpOutH.getValue(2));
20525     SDValue Success =
20526         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20527                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20528     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20529
20530     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20531     Results.push_back(Success);
20532     Results.push_back(EFLAGS.getValue(1));
20533     return;
20534   }
20535   case ISD::ATOMIC_SWAP:
20536   case ISD::ATOMIC_LOAD_ADD:
20537   case ISD::ATOMIC_LOAD_SUB:
20538   case ISD::ATOMIC_LOAD_AND:
20539   case ISD::ATOMIC_LOAD_OR:
20540   case ISD::ATOMIC_LOAD_XOR:
20541   case ISD::ATOMIC_LOAD_NAND:
20542   case ISD::ATOMIC_LOAD_MIN:
20543   case ISD::ATOMIC_LOAD_MAX:
20544   case ISD::ATOMIC_LOAD_UMIN:
20545   case ISD::ATOMIC_LOAD_UMAX:
20546   case ISD::ATOMIC_LOAD: {
20547     // Delegate to generic TypeLegalization. Situations we can really handle
20548     // should have already been dealt with by AtomicExpandPass.cpp.
20549     break;
20550   }
20551   case ISD::BITCAST: {
20552     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20553     EVT DstVT = N->getValueType(0);
20554     EVT SrcVT = N->getOperand(0)->getValueType(0);
20555
20556     if (SrcVT != MVT::f64 ||
20557         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20558       return;
20559
20560     unsigned NumElts = DstVT.getVectorNumElements();
20561     EVT SVT = DstVT.getVectorElementType();
20562     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20563     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20564                                    MVT::v2f64, N->getOperand(0));
20565     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20566
20567     if (ExperimentalVectorWideningLegalization) {
20568       // If we are legalizing vectors by widening, we already have the desired
20569       // legal vector type, just return it.
20570       Results.push_back(ToVecInt);
20571       return;
20572     }
20573
20574     SmallVector<SDValue, 8> Elts;
20575     for (unsigned i = 0, e = NumElts; i != e; ++i)
20576       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20577                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
20578
20579     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20580   }
20581   }
20582 }
20583
20584 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20585   switch ((X86ISD::NodeType)Opcode) {
20586   case X86ISD::FIRST_NUMBER:       break;
20587   case X86ISD::BSF:                return "X86ISD::BSF";
20588   case X86ISD::BSR:                return "X86ISD::BSR";
20589   case X86ISD::SHLD:               return "X86ISD::SHLD";
20590   case X86ISD::SHRD:               return "X86ISD::SHRD";
20591   case X86ISD::FAND:               return "X86ISD::FAND";
20592   case X86ISD::FANDN:              return "X86ISD::FANDN";
20593   case X86ISD::FOR:                return "X86ISD::FOR";
20594   case X86ISD::FXOR:               return "X86ISD::FXOR";
20595   case X86ISD::FILD:               return "X86ISD::FILD";
20596   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
20597   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20598   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20599   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20600   case X86ISD::FLD:                return "X86ISD::FLD";
20601   case X86ISD::FST:                return "X86ISD::FST";
20602   case X86ISD::CALL:               return "X86ISD::CALL";
20603   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
20604   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
20605   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
20606   case X86ISD::BT:                 return "X86ISD::BT";
20607   case X86ISD::CMP:                return "X86ISD::CMP";
20608   case X86ISD::COMI:               return "X86ISD::COMI";
20609   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
20610   case X86ISD::CMPM:               return "X86ISD::CMPM";
20611   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
20612   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
20613   case X86ISD::SETCC:              return "X86ISD::SETCC";
20614   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
20615   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
20616   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
20617   case X86ISD::CMOV:               return "X86ISD::CMOV";
20618   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
20619   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
20620   case X86ISD::IRET:               return "X86ISD::IRET";
20621   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
20622   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
20623   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
20624   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
20625   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
20626   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
20627   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
20628   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
20629   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
20630   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
20631   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
20632   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
20633   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
20634   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
20635   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
20636   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
20637   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
20638   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
20639   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
20640   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
20641   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
20642   case X86ISD::HADD:               return "X86ISD::HADD";
20643   case X86ISD::HSUB:               return "X86ISD::HSUB";
20644   case X86ISD::FHADD:              return "X86ISD::FHADD";
20645   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
20646   case X86ISD::ABS:                return "X86ISD::ABS";
20647   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
20648   case X86ISD::FMAX:               return "X86ISD::FMAX";
20649   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
20650   case X86ISD::FMIN:               return "X86ISD::FMIN";
20651   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
20652   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20653   case X86ISD::FMINC:              return "X86ISD::FMINC";
20654   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20655   case X86ISD::FRCP:               return "X86ISD::FRCP";
20656   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
20657   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
20658   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20659   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20660   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20661   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20662   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20663   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20664   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20665   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20666   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20667   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20668   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20669   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20670   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20671   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20672   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20673   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20674   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20675   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20676   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20677   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20678   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20679   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20680   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20681   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20682   case X86ISD::CVT2MASK:           return "X86ISD::CVT2MASK";
20683   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20684   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20685   case X86ISD::VSHL:               return "X86ISD::VSHL";
20686   case X86ISD::VSRL:               return "X86ISD::VSRL";
20687   case X86ISD::VSRA:               return "X86ISD::VSRA";
20688   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20689   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20690   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20691   case X86ISD::CMPP:               return "X86ISD::CMPP";
20692   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20693   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20694   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20695   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20696   case X86ISD::ADD:                return "X86ISD::ADD";
20697   case X86ISD::SUB:                return "X86ISD::SUB";
20698   case X86ISD::ADC:                return "X86ISD::ADC";
20699   case X86ISD::SBB:                return "X86ISD::SBB";
20700   case X86ISD::SMUL:               return "X86ISD::SMUL";
20701   case X86ISD::UMUL:               return "X86ISD::UMUL";
20702   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20703   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20704   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20705   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20706   case X86ISD::INC:                return "X86ISD::INC";
20707   case X86ISD::DEC:                return "X86ISD::DEC";
20708   case X86ISD::OR:                 return "X86ISD::OR";
20709   case X86ISD::XOR:                return "X86ISD::XOR";
20710   case X86ISD::AND:                return "X86ISD::AND";
20711   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20712   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20713   case X86ISD::PTEST:              return "X86ISD::PTEST";
20714   case X86ISD::TESTP:              return "X86ISD::TESTP";
20715   case X86ISD::TESTM:              return "X86ISD::TESTM";
20716   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20717   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20718   case X86ISD::KTEST:              return "X86ISD::KTEST";
20719   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20720   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20721   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20722   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20723   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20724   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20725   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20726   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20727   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20728   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20729   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20730   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20731   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20732   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20733   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20734   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20735   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20736   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20737   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20738   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20739   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20740   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20741   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
20742   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20743   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20744   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20745   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20746   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20747   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20748   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20749   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20750   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20751   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20752   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20753   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20754   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20755   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20756   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20757   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20758   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20759   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20760   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20761   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20762   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20763   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20764   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20765   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20766   case X86ISD::SAHF:               return "X86ISD::SAHF";
20767   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20768   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20769   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20770   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20771   case X86ISD::VPROT:              return "X86ISD::VPROT";
20772   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20773   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20774   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20775   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20776   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20777   case X86ISD::FMADD:              return "X86ISD::FMADD";
20778   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20779   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20780   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20781   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20782   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20783   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20784   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20785   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20786   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20787   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20788   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20789   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20790   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20791   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20792   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20793   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20794   case X86ISD::XTEST:              return "X86ISD::XTEST";
20795   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20796   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20797   case X86ISD::SELECT:             return "X86ISD::SELECT";
20798   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20799   case X86ISD::RCP28:              return "X86ISD::RCP28";
20800   case X86ISD::EXP2:               return "X86ISD::EXP2";
20801   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20802   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20803   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20804   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20805   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20806   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20807   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20808   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20809   case X86ISD::ADDS:               return "X86ISD::ADDS";
20810   case X86ISD::SUBS:               return "X86ISD::SUBS";
20811   case X86ISD::AVG:                return "X86ISD::AVG";
20812   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20813   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20814   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20815   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20816   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20817   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20818   case X86ISD::VFPCLASSS:          return "X86ISD::VFPCLASSS";
20819   }
20820   return nullptr;
20821 }
20822
20823 // isLegalAddressingMode - Return true if the addressing mode represented
20824 // by AM is legal for this target, for a load/store of the specified type.
20825 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20826                                               const AddrMode &AM, Type *Ty,
20827                                               unsigned AS) const {
20828   // X86 supports extremely general addressing modes.
20829   CodeModel::Model M = getTargetMachine().getCodeModel();
20830   Reloc::Model R = getTargetMachine().getRelocationModel();
20831
20832   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20833   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20834     return false;
20835
20836   if (AM.BaseGV) {
20837     unsigned GVFlags =
20838       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20839
20840     // If a reference to this global requires an extra load, we can't fold it.
20841     if (isGlobalStubReference(GVFlags))
20842       return false;
20843
20844     // If BaseGV requires a register for the PIC base, we cannot also have a
20845     // BaseReg specified.
20846     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20847       return false;
20848
20849     // If lower 4G is not available, then we must use rip-relative addressing.
20850     if ((M != CodeModel::Small || R != Reloc::Static) &&
20851         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20852       return false;
20853   }
20854
20855   switch (AM.Scale) {
20856   case 0:
20857   case 1:
20858   case 2:
20859   case 4:
20860   case 8:
20861     // These scales always work.
20862     break;
20863   case 3:
20864   case 5:
20865   case 9:
20866     // These scales are formed with basereg+scalereg.  Only accept if there is
20867     // no basereg yet.
20868     if (AM.HasBaseReg)
20869       return false;
20870     break;
20871   default:  // Other stuff never works.
20872     return false;
20873   }
20874
20875   return true;
20876 }
20877
20878 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20879   unsigned Bits = Ty->getScalarSizeInBits();
20880
20881   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20882   // particularly cheaper than those without.
20883   if (Bits == 8)
20884     return false;
20885
20886   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20887   // variable shifts just as cheap as scalar ones.
20888   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20889     return false;
20890
20891   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20892   // fully general vector.
20893   return true;
20894 }
20895
20896 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20897   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20898     return false;
20899   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20900   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20901   return NumBits1 > NumBits2;
20902 }
20903
20904 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20905   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20906     return false;
20907
20908   if (!isTypeLegal(EVT::getEVT(Ty1)))
20909     return false;
20910
20911   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20912
20913   // Assuming the caller doesn't have a zeroext or signext return parameter,
20914   // truncation all the way down to i1 is valid.
20915   return true;
20916 }
20917
20918 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20919   return isInt<32>(Imm);
20920 }
20921
20922 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20923   // Can also use sub to handle negated immediates.
20924   return isInt<32>(Imm);
20925 }
20926
20927 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20928   if (!VT1.isInteger() || !VT2.isInteger())
20929     return false;
20930   unsigned NumBits1 = VT1.getSizeInBits();
20931   unsigned NumBits2 = VT2.getSizeInBits();
20932   return NumBits1 > NumBits2;
20933 }
20934
20935 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20936   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20937   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20938 }
20939
20940 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20941   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20942   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20943 }
20944
20945 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20946   EVT VT1 = Val.getValueType();
20947   if (isZExtFree(VT1, VT2))
20948     return true;
20949
20950   if (Val.getOpcode() != ISD::LOAD)
20951     return false;
20952
20953   if (!VT1.isSimple() || !VT1.isInteger() ||
20954       !VT2.isSimple() || !VT2.isInteger())
20955     return false;
20956
20957   switch (VT1.getSimpleVT().SimpleTy) {
20958   default: break;
20959   case MVT::i8:
20960   case MVT::i16:
20961   case MVT::i32:
20962     // X86 has 8, 16, and 32-bit zero-extending loads.
20963     return true;
20964   }
20965
20966   return false;
20967 }
20968
20969 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20970
20971 bool
20972 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20973   if (!Subtarget->hasAnyFMA())
20974     return false;
20975
20976   VT = VT.getScalarType();
20977
20978   if (!VT.isSimple())
20979     return false;
20980
20981   switch (VT.getSimpleVT().SimpleTy) {
20982   case MVT::f32:
20983   case MVT::f64:
20984     return true;
20985   default:
20986     break;
20987   }
20988
20989   return false;
20990 }
20991
20992 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20993   // i16 instructions are longer (0x66 prefix) and potentially slower.
20994   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20995 }
20996
20997 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20998 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20999 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
21000 /// are assumed to be legal.
21001 bool
21002 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
21003                                       EVT VT) const {
21004   if (!VT.isSimple())
21005     return false;
21006
21007   // Not for i1 vectors
21008   if (VT.getSimpleVT().getScalarType() == MVT::i1)
21009     return false;
21010
21011   // Very little shuffling can be done for 64-bit vectors right now.
21012   if (VT.getSimpleVT().getSizeInBits() == 64)
21013     return false;
21014
21015   // We only care that the types being shuffled are legal. The lowering can
21016   // handle any possible shuffle mask that results.
21017   return isTypeLegal(VT.getSimpleVT());
21018 }
21019
21020 bool
21021 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
21022                                           EVT VT) const {
21023   // Just delegate to the generic legality, clear masks aren't special.
21024   return isShuffleMaskLegal(Mask, VT);
21025 }
21026
21027 //===----------------------------------------------------------------------===//
21028 //                           X86 Scheduler Hooks
21029 //===----------------------------------------------------------------------===//
21030
21031 /// Utility function to emit xbegin specifying the start of an RTM region.
21032 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
21033                                      const TargetInstrInfo *TII) {
21034   DebugLoc DL = MI->getDebugLoc();
21035
21036   const BasicBlock *BB = MBB->getBasicBlock();
21037   MachineFunction::iterator I = ++MBB->getIterator();
21038
21039   // For the v = xbegin(), we generate
21040   //
21041   // thisMBB:
21042   //  xbegin sinkMBB
21043   //
21044   // mainMBB:
21045   //  eax = -1
21046   //
21047   // sinkMBB:
21048   //  v = eax
21049
21050   MachineBasicBlock *thisMBB = MBB;
21051   MachineFunction *MF = MBB->getParent();
21052   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21053   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21054   MF->insert(I, mainMBB);
21055   MF->insert(I, sinkMBB);
21056
21057   // Transfer the remainder of BB and its successor edges to sinkMBB.
21058   sinkMBB->splice(sinkMBB->begin(), MBB,
21059                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21060   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21061
21062   // thisMBB:
21063   //  xbegin sinkMBB
21064   //  # fallthrough to mainMBB
21065   //  # abortion to sinkMBB
21066   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
21067   thisMBB->addSuccessor(mainMBB);
21068   thisMBB->addSuccessor(sinkMBB);
21069
21070   // mainMBB:
21071   //  EAX = -1
21072   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
21073   mainMBB->addSuccessor(sinkMBB);
21074
21075   // sinkMBB:
21076   // EAX is live into the sinkMBB
21077   sinkMBB->addLiveIn(X86::EAX);
21078   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21079           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21080     .addReg(X86::EAX);
21081
21082   MI->eraseFromParent();
21083   return sinkMBB;
21084 }
21085
21086 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
21087 // or XMM0_V32I8 in AVX all of this code can be replaced with that
21088 // in the .td file.
21089 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
21090                                        const TargetInstrInfo *TII) {
21091   unsigned Opc;
21092   switch (MI->getOpcode()) {
21093   default: llvm_unreachable("illegal opcode!");
21094   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
21095   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
21096   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
21097   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
21098   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
21099   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
21100   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
21101   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
21102   }
21103
21104   DebugLoc dl = MI->getDebugLoc();
21105   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21106
21107   unsigned NumArgs = MI->getNumOperands();
21108   for (unsigned i = 1; i < NumArgs; ++i) {
21109     MachineOperand &Op = MI->getOperand(i);
21110     if (!(Op.isReg() && Op.isImplicit()))
21111       MIB.addOperand(Op);
21112   }
21113   if (MI->hasOneMemOperand())
21114     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21115
21116   BuildMI(*BB, MI, dl,
21117     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21118     .addReg(X86::XMM0);
21119
21120   MI->eraseFromParent();
21121   return BB;
21122 }
21123
21124 // FIXME: Custom handling because TableGen doesn't support multiple implicit
21125 // defs in an instruction pattern
21126 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
21127                                        const TargetInstrInfo *TII) {
21128   unsigned Opc;
21129   switch (MI->getOpcode()) {
21130   default: llvm_unreachable("illegal opcode!");
21131   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
21132   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
21133   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
21134   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
21135   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
21136   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
21137   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
21138   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
21139   }
21140
21141   DebugLoc dl = MI->getDebugLoc();
21142   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21143
21144   unsigned NumArgs = MI->getNumOperands(); // remove the results
21145   for (unsigned i = 1; i < NumArgs; ++i) {
21146     MachineOperand &Op = MI->getOperand(i);
21147     if (!(Op.isReg() && Op.isImplicit()))
21148       MIB.addOperand(Op);
21149   }
21150   if (MI->hasOneMemOperand())
21151     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21152
21153   BuildMI(*BB, MI, dl,
21154     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21155     .addReg(X86::ECX);
21156
21157   MI->eraseFromParent();
21158   return BB;
21159 }
21160
21161 static MachineBasicBlock *EmitWRPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21162                                      const X86Subtarget *Subtarget) {
21163   DebugLoc dl = MI->getDebugLoc();
21164   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21165
21166   // insert input VAL into EAX
21167   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
21168                            .addReg(MI->getOperand(0).getReg());
21169   // insert zero to ECX
21170   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21171                            .addReg(X86::ECX)
21172                            .addReg(X86::ECX);
21173   // insert zero to EDX
21174   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::EDX)
21175                            .addReg(X86::EDX)
21176                            .addReg(X86::EDX);
21177   // insert WRPKRU instruction
21178   BuildMI(*BB, MI, dl, TII->get(X86::WRPKRUr));
21179
21180   MI->eraseFromParent(); // The pseudo is gone now.
21181   return BB;
21182 }
21183
21184 static MachineBasicBlock *EmitRDPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21185                                      const X86Subtarget *Subtarget) {
21186   DebugLoc dl = MI->getDebugLoc();
21187   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21188
21189   // insert zero to ECX
21190   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21191                            .addReg(X86::ECX)
21192                            .addReg(X86::ECX);
21193   // insert RDPKRU instruction
21194   BuildMI(*BB, MI, dl, TII->get(X86::RDPKRUr));
21195   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21196                            .addReg(X86::EAX);
21197
21198   MI->eraseFromParent(); // The pseudo is gone now.
21199   return BB;
21200 }
21201
21202 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
21203                                       const X86Subtarget *Subtarget) {
21204   DebugLoc dl = MI->getDebugLoc();
21205   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21206   // Address into RAX/EAX, other two args into ECX, EDX.
21207   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
21208   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
21209   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
21210   for (int i = 0; i < X86::AddrNumOperands; ++i)
21211     MIB.addOperand(MI->getOperand(i));
21212
21213   unsigned ValOps = X86::AddrNumOperands;
21214   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
21215     .addReg(MI->getOperand(ValOps).getReg());
21216   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
21217     .addReg(MI->getOperand(ValOps+1).getReg());
21218
21219   // The instruction doesn't actually take any operands though.
21220   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
21221
21222   MI->eraseFromParent(); // The pseudo is gone now.
21223   return BB;
21224 }
21225
21226 MachineBasicBlock *
21227 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
21228                                                  MachineBasicBlock *MBB) const {
21229   // Emit va_arg instruction on X86-64.
21230
21231   // Operands to this pseudo-instruction:
21232   // 0  ) Output        : destination address (reg)
21233   // 1-5) Input         : va_list address (addr, i64mem)
21234   // 6  ) ArgSize       : Size (in bytes) of vararg type
21235   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
21236   // 8  ) Align         : Alignment of type
21237   // 9  ) EFLAGS (implicit-def)
21238
21239   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
21240   static_assert(X86::AddrNumOperands == 5,
21241                 "VAARG_64 assumes 5 address operands");
21242
21243   unsigned DestReg = MI->getOperand(0).getReg();
21244   MachineOperand &Base = MI->getOperand(1);
21245   MachineOperand &Scale = MI->getOperand(2);
21246   MachineOperand &Index = MI->getOperand(3);
21247   MachineOperand &Disp = MI->getOperand(4);
21248   MachineOperand &Segment = MI->getOperand(5);
21249   unsigned ArgSize = MI->getOperand(6).getImm();
21250   unsigned ArgMode = MI->getOperand(7).getImm();
21251   unsigned Align = MI->getOperand(8).getImm();
21252
21253   // Memory Reference
21254   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
21255   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21256   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21257
21258   // Machine Information
21259   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21260   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
21261   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
21262   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
21263   DebugLoc DL = MI->getDebugLoc();
21264
21265   // struct va_list {
21266   //   i32   gp_offset
21267   //   i32   fp_offset
21268   //   i64   overflow_area (address)
21269   //   i64   reg_save_area (address)
21270   // }
21271   // sizeof(va_list) = 24
21272   // alignment(va_list) = 8
21273
21274   unsigned TotalNumIntRegs = 6;
21275   unsigned TotalNumXMMRegs = 8;
21276   bool UseGPOffset = (ArgMode == 1);
21277   bool UseFPOffset = (ArgMode == 2);
21278   unsigned MaxOffset = TotalNumIntRegs * 8 +
21279                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
21280
21281   /* Align ArgSize to a multiple of 8 */
21282   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
21283   bool NeedsAlign = (Align > 8);
21284
21285   MachineBasicBlock *thisMBB = MBB;
21286   MachineBasicBlock *overflowMBB;
21287   MachineBasicBlock *offsetMBB;
21288   MachineBasicBlock *endMBB;
21289
21290   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
21291   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
21292   unsigned OffsetReg = 0;
21293
21294   if (!UseGPOffset && !UseFPOffset) {
21295     // If we only pull from the overflow region, we don't create a branch.
21296     // We don't need to alter control flow.
21297     OffsetDestReg = 0; // unused
21298     OverflowDestReg = DestReg;
21299
21300     offsetMBB = nullptr;
21301     overflowMBB = thisMBB;
21302     endMBB = thisMBB;
21303   } else {
21304     // First emit code to check if gp_offset (or fp_offset) is below the bound.
21305     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
21306     // If not, pull from overflow_area. (branch to overflowMBB)
21307     //
21308     //       thisMBB
21309     //         |     .
21310     //         |        .
21311     //     offsetMBB   overflowMBB
21312     //         |        .
21313     //         |     .
21314     //        endMBB
21315
21316     // Registers for the PHI in endMBB
21317     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
21318     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
21319
21320     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21321     MachineFunction *MF = MBB->getParent();
21322     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21323     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21324     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21325
21326     MachineFunction::iterator MBBIter = ++MBB->getIterator();
21327
21328     // Insert the new basic blocks
21329     MF->insert(MBBIter, offsetMBB);
21330     MF->insert(MBBIter, overflowMBB);
21331     MF->insert(MBBIter, endMBB);
21332
21333     // Transfer the remainder of MBB and its successor edges to endMBB.
21334     endMBB->splice(endMBB->begin(), thisMBB,
21335                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
21336     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
21337
21338     // Make offsetMBB and overflowMBB successors of thisMBB
21339     thisMBB->addSuccessor(offsetMBB);
21340     thisMBB->addSuccessor(overflowMBB);
21341
21342     // endMBB is a successor of both offsetMBB and overflowMBB
21343     offsetMBB->addSuccessor(endMBB);
21344     overflowMBB->addSuccessor(endMBB);
21345
21346     // Load the offset value into a register
21347     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21348     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21349       .addOperand(Base)
21350       .addOperand(Scale)
21351       .addOperand(Index)
21352       .addDisp(Disp, UseFPOffset ? 4 : 0)
21353       .addOperand(Segment)
21354       .setMemRefs(MMOBegin, MMOEnd);
21355
21356     // Check if there is enough room left to pull this argument.
21357     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21358       .addReg(OffsetReg)
21359       .addImm(MaxOffset + 8 - ArgSizeA8);
21360
21361     // Branch to "overflowMBB" if offset >= max
21362     // Fall through to "offsetMBB" otherwise
21363     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21364       .addMBB(overflowMBB);
21365   }
21366
21367   // In offsetMBB, emit code to use the reg_save_area.
21368   if (offsetMBB) {
21369     assert(OffsetReg != 0);
21370
21371     // Read the reg_save_area address.
21372     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21373     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21374       .addOperand(Base)
21375       .addOperand(Scale)
21376       .addOperand(Index)
21377       .addDisp(Disp, 16)
21378       .addOperand(Segment)
21379       .setMemRefs(MMOBegin, MMOEnd);
21380
21381     // Zero-extend the offset
21382     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21383       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21384         .addImm(0)
21385         .addReg(OffsetReg)
21386         .addImm(X86::sub_32bit);
21387
21388     // Add the offset to the reg_save_area to get the final address.
21389     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21390       .addReg(OffsetReg64)
21391       .addReg(RegSaveReg);
21392
21393     // Compute the offset for the next argument
21394     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21395     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21396       .addReg(OffsetReg)
21397       .addImm(UseFPOffset ? 16 : 8);
21398
21399     // Store it back into the va_list.
21400     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21401       .addOperand(Base)
21402       .addOperand(Scale)
21403       .addOperand(Index)
21404       .addDisp(Disp, UseFPOffset ? 4 : 0)
21405       .addOperand(Segment)
21406       .addReg(NextOffsetReg)
21407       .setMemRefs(MMOBegin, MMOEnd);
21408
21409     // Jump to endMBB
21410     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21411       .addMBB(endMBB);
21412   }
21413
21414   //
21415   // Emit code to use overflow area
21416   //
21417
21418   // Load the overflow_area address into a register.
21419   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21420   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21421     .addOperand(Base)
21422     .addOperand(Scale)
21423     .addOperand(Index)
21424     .addDisp(Disp, 8)
21425     .addOperand(Segment)
21426     .setMemRefs(MMOBegin, MMOEnd);
21427
21428   // If we need to align it, do so. Otherwise, just copy the address
21429   // to OverflowDestReg.
21430   if (NeedsAlign) {
21431     // Align the overflow address
21432     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21433     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21434
21435     // aligned_addr = (addr + (align-1)) & ~(align-1)
21436     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21437       .addReg(OverflowAddrReg)
21438       .addImm(Align-1);
21439
21440     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21441       .addReg(TmpReg)
21442       .addImm(~(uint64_t)(Align-1));
21443   } else {
21444     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21445       .addReg(OverflowAddrReg);
21446   }
21447
21448   // Compute the next overflow address after this argument.
21449   // (the overflow address should be kept 8-byte aligned)
21450   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21451   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21452     .addReg(OverflowDestReg)
21453     .addImm(ArgSizeA8);
21454
21455   // Store the new overflow address.
21456   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21457     .addOperand(Base)
21458     .addOperand(Scale)
21459     .addOperand(Index)
21460     .addDisp(Disp, 8)
21461     .addOperand(Segment)
21462     .addReg(NextAddrReg)
21463     .setMemRefs(MMOBegin, MMOEnd);
21464
21465   // If we branched, emit the PHI to the front of endMBB.
21466   if (offsetMBB) {
21467     BuildMI(*endMBB, endMBB->begin(), DL,
21468             TII->get(X86::PHI), DestReg)
21469       .addReg(OffsetDestReg).addMBB(offsetMBB)
21470       .addReg(OverflowDestReg).addMBB(overflowMBB);
21471   }
21472
21473   // Erase the pseudo instruction
21474   MI->eraseFromParent();
21475
21476   return endMBB;
21477 }
21478
21479 MachineBasicBlock *
21480 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21481                                                  MachineInstr *MI,
21482                                                  MachineBasicBlock *MBB) const {
21483   // Emit code to save XMM registers to the stack. The ABI says that the
21484   // number of registers to save is given in %al, so it's theoretically
21485   // possible to do an indirect jump trick to avoid saving all of them,
21486   // however this code takes a simpler approach and just executes all
21487   // of the stores if %al is non-zero. It's less code, and it's probably
21488   // easier on the hardware branch predictor, and stores aren't all that
21489   // expensive anyway.
21490
21491   // Create the new basic blocks. One block contains all the XMM stores,
21492   // and one block is the final destination regardless of whether any
21493   // stores were performed.
21494   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21495   MachineFunction *F = MBB->getParent();
21496   MachineFunction::iterator MBBIter = ++MBB->getIterator();
21497   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21498   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21499   F->insert(MBBIter, XMMSaveMBB);
21500   F->insert(MBBIter, EndMBB);
21501
21502   // Transfer the remainder of MBB and its successor edges to EndMBB.
21503   EndMBB->splice(EndMBB->begin(), MBB,
21504                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21505   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21506
21507   // The original block will now fall through to the XMM save block.
21508   MBB->addSuccessor(XMMSaveMBB);
21509   // The XMMSaveMBB will fall through to the end block.
21510   XMMSaveMBB->addSuccessor(EndMBB);
21511
21512   // Now add the instructions.
21513   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21514   DebugLoc DL = MI->getDebugLoc();
21515
21516   unsigned CountReg = MI->getOperand(0).getReg();
21517   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21518   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21519
21520   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21521     // If %al is 0, branch around the XMM save block.
21522     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21523     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21524     MBB->addSuccessor(EndMBB);
21525   }
21526
21527   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21528   // that was just emitted, but clearly shouldn't be "saved".
21529   assert((MI->getNumOperands() <= 3 ||
21530           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21531           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21532          && "Expected last argument to be EFLAGS");
21533   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21534   // In the XMM save block, save all the XMM argument registers.
21535   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21536     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21537     MachineMemOperand *MMO = F->getMachineMemOperand(
21538         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21539         MachineMemOperand::MOStore,
21540         /*Size=*/16, /*Align=*/16);
21541     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21542       .addFrameIndex(RegSaveFrameIndex)
21543       .addImm(/*Scale=*/1)
21544       .addReg(/*IndexReg=*/0)
21545       .addImm(/*Disp=*/Offset)
21546       .addReg(/*Segment=*/0)
21547       .addReg(MI->getOperand(i).getReg())
21548       .addMemOperand(MMO);
21549   }
21550
21551   MI->eraseFromParent();   // The pseudo instruction is gone now.
21552
21553   return EndMBB;
21554 }
21555
21556 // The EFLAGS operand of SelectItr might be missing a kill marker
21557 // because there were multiple uses of EFLAGS, and ISel didn't know
21558 // which to mark. Figure out whether SelectItr should have had a
21559 // kill marker, and set it if it should. Returns the correct kill
21560 // marker value.
21561 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21562                                      MachineBasicBlock* BB,
21563                                      const TargetRegisterInfo* TRI) {
21564   // Scan forward through BB for a use/def of EFLAGS.
21565   MachineBasicBlock::iterator miI(std::next(SelectItr));
21566   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21567     const MachineInstr& mi = *miI;
21568     if (mi.readsRegister(X86::EFLAGS))
21569       return false;
21570     if (mi.definesRegister(X86::EFLAGS))
21571       break; // Should have kill-flag - update below.
21572   }
21573
21574   // If we hit the end of the block, check whether EFLAGS is live into a
21575   // successor.
21576   if (miI == BB->end()) {
21577     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21578                                           sEnd = BB->succ_end();
21579          sItr != sEnd; ++sItr) {
21580       MachineBasicBlock* succ = *sItr;
21581       if (succ->isLiveIn(X86::EFLAGS))
21582         return false;
21583     }
21584   }
21585
21586   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21587   // out. SelectMI should have a kill flag on EFLAGS.
21588   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21589   return true;
21590 }
21591
21592 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21593 // together with other CMOV pseudo-opcodes into a single basic-block with
21594 // conditional jump around it.
21595 static bool isCMOVPseudo(MachineInstr *MI) {
21596   switch (MI->getOpcode()) {
21597   case X86::CMOV_FR32:
21598   case X86::CMOV_FR64:
21599   case X86::CMOV_GR8:
21600   case X86::CMOV_GR16:
21601   case X86::CMOV_GR32:
21602   case X86::CMOV_RFP32:
21603   case X86::CMOV_RFP64:
21604   case X86::CMOV_RFP80:
21605   case X86::CMOV_V2F64:
21606   case X86::CMOV_V2I64:
21607   case X86::CMOV_V4F32:
21608   case X86::CMOV_V4F64:
21609   case X86::CMOV_V4I64:
21610   case X86::CMOV_V16F32:
21611   case X86::CMOV_V8F32:
21612   case X86::CMOV_V8F64:
21613   case X86::CMOV_V8I64:
21614   case X86::CMOV_V8I1:
21615   case X86::CMOV_V16I1:
21616   case X86::CMOV_V32I1:
21617   case X86::CMOV_V64I1:
21618     return true;
21619
21620   default:
21621     return false;
21622   }
21623 }
21624
21625 MachineBasicBlock *
21626 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21627                                      MachineBasicBlock *BB) const {
21628   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21629   DebugLoc DL = MI->getDebugLoc();
21630
21631   // To "insert" a SELECT_CC instruction, we actually have to insert the
21632   // diamond control-flow pattern.  The incoming instruction knows the
21633   // destination vreg to set, the condition code register to branch on, the
21634   // true/false values to select between, and a branch opcode to use.
21635   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21636   MachineFunction::iterator It = ++BB->getIterator();
21637
21638   //  thisMBB:
21639   //  ...
21640   //   TrueVal = ...
21641   //   cmpTY ccX, r1, r2
21642   //   bCC copy1MBB
21643   //   fallthrough --> copy0MBB
21644   MachineBasicBlock *thisMBB = BB;
21645   MachineFunction *F = BB->getParent();
21646
21647   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21648   // as described above, by inserting a BB, and then making a PHI at the join
21649   // point to select the true and false operands of the CMOV in the PHI.
21650   //
21651   // The code also handles two different cases of multiple CMOV opcodes
21652   // in a row.
21653   //
21654   // Case 1:
21655   // In this case, there are multiple CMOVs in a row, all which are based on
21656   // the same condition setting (or the exact opposite condition setting).
21657   // In this case we can lower all the CMOVs using a single inserted BB, and
21658   // then make a number of PHIs at the join point to model the CMOVs. The only
21659   // trickiness here, is that in a case like:
21660   //
21661   // t2 = CMOV cond1 t1, f1
21662   // t3 = CMOV cond1 t2, f2
21663   //
21664   // when rewriting this into PHIs, we have to perform some renaming on the
21665   // temps since you cannot have a PHI operand refer to a PHI result earlier
21666   // in the same block.  The "simple" but wrong lowering would be:
21667   //
21668   // t2 = PHI t1(BB1), f1(BB2)
21669   // t3 = PHI t2(BB1), f2(BB2)
21670   //
21671   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21672   // renaming is to note that on the path through BB1, t2 is really just a
21673   // copy of t1, and do that renaming, properly generating:
21674   //
21675   // t2 = PHI t1(BB1), f1(BB2)
21676   // t3 = PHI t1(BB1), f2(BB2)
21677   //
21678   // Case 2, we lower cascaded CMOVs such as
21679   //
21680   //   (CMOV (CMOV F, T, cc1), T, cc2)
21681   //
21682   // to two successives branches.  For that, we look for another CMOV as the
21683   // following instruction.
21684   //
21685   // Without this, we would add a PHI between the two jumps, which ends up
21686   // creating a few copies all around. For instance, for
21687   //
21688   //    (sitofp (zext (fcmp une)))
21689   //
21690   // we would generate:
21691   //
21692   //         ucomiss %xmm1, %xmm0
21693   //         movss  <1.0f>, %xmm0
21694   //         movaps  %xmm0, %xmm1
21695   //         jne     .LBB5_2
21696   //         xorps   %xmm1, %xmm1
21697   // .LBB5_2:
21698   //         jp      .LBB5_4
21699   //         movaps  %xmm1, %xmm0
21700   // .LBB5_4:
21701   //         retq
21702   //
21703   // because this custom-inserter would have generated:
21704   //
21705   //   A
21706   //   | \
21707   //   |  B
21708   //   | /
21709   //   C
21710   //   | \
21711   //   |  D
21712   //   | /
21713   //   E
21714   //
21715   // A: X = ...; Y = ...
21716   // B: empty
21717   // C: Z = PHI [X, A], [Y, B]
21718   // D: empty
21719   // E: PHI [X, C], [Z, D]
21720   //
21721   // If we lower both CMOVs in a single step, we can instead generate:
21722   //
21723   //   A
21724   //   | \
21725   //   |  C
21726   //   | /|
21727   //   |/ |
21728   //   |  |
21729   //   |  D
21730   //   | /
21731   //   E
21732   //
21733   // A: X = ...; Y = ...
21734   // D: empty
21735   // E: PHI [X, A], [X, C], [Y, D]
21736   //
21737   // Which, in our sitofp/fcmp example, gives us something like:
21738   //
21739   //         ucomiss %xmm1, %xmm0
21740   //         movss  <1.0f>, %xmm0
21741   //         jne     .LBB5_4
21742   //         jp      .LBB5_4
21743   //         xorps   %xmm0, %xmm0
21744   // .LBB5_4:
21745   //         retq
21746   //
21747   MachineInstr *CascadedCMOV = nullptr;
21748   MachineInstr *LastCMOV = MI;
21749   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21750   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21751   MachineBasicBlock::iterator NextMIIt =
21752       std::next(MachineBasicBlock::iterator(MI));
21753
21754   // Check for case 1, where there are multiple CMOVs with the same condition
21755   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21756   // number of jumps the most.
21757
21758   if (isCMOVPseudo(MI)) {
21759     // See if we have a string of CMOVS with the same condition.
21760     while (NextMIIt != BB->end() &&
21761            isCMOVPseudo(NextMIIt) &&
21762            (NextMIIt->getOperand(3).getImm() == CC ||
21763             NextMIIt->getOperand(3).getImm() == OppCC)) {
21764       LastCMOV = &*NextMIIt;
21765       ++NextMIIt;
21766     }
21767   }
21768
21769   // This checks for case 2, but only do this if we didn't already find
21770   // case 1, as indicated by LastCMOV == MI.
21771   if (LastCMOV == MI &&
21772       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21773       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21774       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21775     CascadedCMOV = &*NextMIIt;
21776   }
21777
21778   MachineBasicBlock *jcc1MBB = nullptr;
21779
21780   // If we have a cascaded CMOV, we lower it to two successive branches to
21781   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21782   if (CascadedCMOV) {
21783     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21784     F->insert(It, jcc1MBB);
21785     jcc1MBB->addLiveIn(X86::EFLAGS);
21786   }
21787
21788   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21789   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21790   F->insert(It, copy0MBB);
21791   F->insert(It, sinkMBB);
21792
21793   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21794   // live into the sink and copy blocks.
21795   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21796
21797   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21798   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21799       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21800     copy0MBB->addLiveIn(X86::EFLAGS);
21801     sinkMBB->addLiveIn(X86::EFLAGS);
21802   }
21803
21804   // Transfer the remainder of BB and its successor edges to sinkMBB.
21805   sinkMBB->splice(sinkMBB->begin(), BB,
21806                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21807   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21808
21809   // Add the true and fallthrough blocks as its successors.
21810   if (CascadedCMOV) {
21811     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21812     BB->addSuccessor(jcc1MBB);
21813
21814     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21815     // jump to the sinkMBB.
21816     jcc1MBB->addSuccessor(copy0MBB);
21817     jcc1MBB->addSuccessor(sinkMBB);
21818   } else {
21819     BB->addSuccessor(copy0MBB);
21820   }
21821
21822   // The true block target of the first (or only) branch is always sinkMBB.
21823   BB->addSuccessor(sinkMBB);
21824
21825   // Create the conditional branch instruction.
21826   unsigned Opc = X86::GetCondBranchFromCond(CC);
21827   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21828
21829   if (CascadedCMOV) {
21830     unsigned Opc2 = X86::GetCondBranchFromCond(
21831         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21832     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21833   }
21834
21835   //  copy0MBB:
21836   //   %FalseValue = ...
21837   //   # fallthrough to sinkMBB
21838   copy0MBB->addSuccessor(sinkMBB);
21839
21840   //  sinkMBB:
21841   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21842   //  ...
21843   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21844   MachineBasicBlock::iterator MIItEnd =
21845     std::next(MachineBasicBlock::iterator(LastCMOV));
21846   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21847   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21848   MachineInstrBuilder MIB;
21849
21850   // As we are creating the PHIs, we have to be careful if there is more than
21851   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21852   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21853   // That also means that PHI construction must work forward from earlier to
21854   // later, and that the code must maintain a mapping from earlier PHI's
21855   // destination registers, and the registers that went into the PHI.
21856
21857   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21858     unsigned DestReg = MIIt->getOperand(0).getReg();
21859     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21860     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21861
21862     // If this CMOV we are generating is the opposite condition from
21863     // the jump we generated, then we have to swap the operands for the
21864     // PHI that is going to be generated.
21865     if (MIIt->getOperand(3).getImm() == OppCC)
21866         std::swap(Op1Reg, Op2Reg);
21867
21868     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21869       Op1Reg = RegRewriteTable[Op1Reg].first;
21870
21871     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21872       Op2Reg = RegRewriteTable[Op2Reg].second;
21873
21874     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21875                   TII->get(X86::PHI), DestReg)
21876           .addReg(Op1Reg).addMBB(copy0MBB)
21877           .addReg(Op2Reg).addMBB(thisMBB);
21878
21879     // Add this PHI to the rewrite table.
21880     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21881   }
21882
21883   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21884   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21885   if (CascadedCMOV) {
21886     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21887     // Copy the PHI result to the register defined by the second CMOV.
21888     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21889             DL, TII->get(TargetOpcode::COPY),
21890             CascadedCMOV->getOperand(0).getReg())
21891         .addReg(MI->getOperand(0).getReg());
21892     CascadedCMOV->eraseFromParent();
21893   }
21894
21895   // Now remove the CMOV(s).
21896   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21897     (MIIt++)->eraseFromParent();
21898
21899   return sinkMBB;
21900 }
21901
21902 MachineBasicBlock *
21903 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21904                                        MachineBasicBlock *BB) const {
21905   // Combine the following atomic floating-point modification pattern:
21906   //   a.store(reg OP a.load(acquire), release)
21907   // Transform them into:
21908   //   OPss (%gpr), %xmm
21909   //   movss %xmm, (%gpr)
21910   // Or sd equivalent for 64-bit operations.
21911   unsigned MOp, FOp;
21912   switch (MI->getOpcode()) {
21913   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21914   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21915   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21916   }
21917   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21918   DebugLoc DL = MI->getDebugLoc();
21919   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21920   MachineOperand MSrc = MI->getOperand(0);
21921   unsigned VSrc = MI->getOperand(5).getReg();
21922   const MachineOperand &Disp = MI->getOperand(3);
21923   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21924   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21925   if (hasDisp && MSrc.isReg())
21926     MSrc.setIsKill(false);
21927   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21928                                 .addOperand(/*Base=*/MSrc)
21929                                 .addImm(/*Scale=*/1)
21930                                 .addReg(/*Index=*/0)
21931                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21932                                 .addReg(0);
21933   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21934                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21935                           .addReg(VSrc)
21936                           .addOperand(/*Base=*/MSrc)
21937                           .addImm(/*Scale=*/1)
21938                           .addReg(/*Index=*/0)
21939                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21940                           .addReg(/*Segment=*/0);
21941   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21942   MI->eraseFromParent(); // The pseudo instruction is gone now.
21943   return BB;
21944 }
21945
21946 MachineBasicBlock *
21947 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21948                                         MachineBasicBlock *BB) const {
21949   MachineFunction *MF = BB->getParent();
21950   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21951   DebugLoc DL = MI->getDebugLoc();
21952   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21953
21954   assert(MF->shouldSplitStack());
21955
21956   const bool Is64Bit = Subtarget->is64Bit();
21957   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21958
21959   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21960   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21961
21962   // BB:
21963   //  ... [Till the alloca]
21964   // If stacklet is not large enough, jump to mallocMBB
21965   //
21966   // bumpMBB:
21967   //  Allocate by subtracting from RSP
21968   //  Jump to continueMBB
21969   //
21970   // mallocMBB:
21971   //  Allocate by call to runtime
21972   //
21973   // continueMBB:
21974   //  ...
21975   //  [rest of original BB]
21976   //
21977
21978   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21979   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21980   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21981
21982   MachineRegisterInfo &MRI = MF->getRegInfo();
21983   const TargetRegisterClass *AddrRegClass =
21984       getRegClassFor(getPointerTy(MF->getDataLayout()));
21985
21986   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21987     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21988     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21989     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21990     sizeVReg = MI->getOperand(1).getReg(),
21991     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21992
21993   MachineFunction::iterator MBBIter = ++BB->getIterator();
21994
21995   MF->insert(MBBIter, bumpMBB);
21996   MF->insert(MBBIter, mallocMBB);
21997   MF->insert(MBBIter, continueMBB);
21998
21999   continueMBB->splice(continueMBB->begin(), BB,
22000                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
22001   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
22002
22003   // Add code to the main basic block to check if the stack limit has been hit,
22004   // and if so, jump to mallocMBB otherwise to bumpMBB.
22005   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
22006   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
22007     .addReg(tmpSPVReg).addReg(sizeVReg);
22008   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
22009     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
22010     .addReg(SPLimitVReg);
22011   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
22012
22013   // bumpMBB simply decreases the stack pointer, since we know the current
22014   // stacklet has enough space.
22015   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
22016     .addReg(SPLimitVReg);
22017   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
22018     .addReg(SPLimitVReg);
22019   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22020
22021   // Calls into a routine in libgcc to allocate more space from the heap.
22022   const uint32_t *RegMask =
22023       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
22024   if (IsLP64) {
22025     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
22026       .addReg(sizeVReg);
22027     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22028       .addExternalSymbol("__morestack_allocate_stack_space")
22029       .addRegMask(RegMask)
22030       .addReg(X86::RDI, RegState::Implicit)
22031       .addReg(X86::RAX, RegState::ImplicitDefine);
22032   } else if (Is64Bit) {
22033     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
22034       .addReg(sizeVReg);
22035     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22036       .addExternalSymbol("__morestack_allocate_stack_space")
22037       .addRegMask(RegMask)
22038       .addReg(X86::EDI, RegState::Implicit)
22039       .addReg(X86::EAX, RegState::ImplicitDefine);
22040   } else {
22041     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
22042       .addImm(12);
22043     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
22044     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
22045       .addExternalSymbol("__morestack_allocate_stack_space")
22046       .addRegMask(RegMask)
22047       .addReg(X86::EAX, RegState::ImplicitDefine);
22048   }
22049
22050   if (!Is64Bit)
22051     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
22052       .addImm(16);
22053
22054   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
22055     .addReg(IsLP64 ? X86::RAX : X86::EAX);
22056   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22057
22058   // Set up the CFG correctly.
22059   BB->addSuccessor(bumpMBB);
22060   BB->addSuccessor(mallocMBB);
22061   mallocMBB->addSuccessor(continueMBB);
22062   bumpMBB->addSuccessor(continueMBB);
22063
22064   // Take care of the PHI nodes.
22065   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
22066           MI->getOperand(0).getReg())
22067     .addReg(mallocPtrVReg).addMBB(mallocMBB)
22068     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
22069
22070   // Delete the original pseudo instruction.
22071   MI->eraseFromParent();
22072
22073   // And we're done.
22074   return continueMBB;
22075 }
22076
22077 MachineBasicBlock *
22078 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
22079                                         MachineBasicBlock *BB) const {
22080   assert(!Subtarget->isTargetMachO());
22081   DebugLoc DL = MI->getDebugLoc();
22082   MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
22083       *BB->getParent(), *BB, MI, DL, false);
22084   MachineBasicBlock *ResumeBB = ResumeMI->getParent();
22085   MI->eraseFromParent(); // The pseudo instruction is gone now.
22086   return ResumeBB;
22087 }
22088
22089 MachineBasicBlock *
22090 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
22091                                        MachineBasicBlock *BB) const {
22092   MachineFunction *MF = BB->getParent();
22093   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22094   MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
22095   DebugLoc DL = MI->getDebugLoc();
22096
22097   assert(!isAsynchronousEHPersonality(
22098              classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
22099          "SEH does not use catchret!");
22100
22101   // Only 32-bit EH needs to worry about manually restoring stack pointers.
22102   if (!Subtarget->is32Bit())
22103     return BB;
22104
22105   // C++ EH creates a new target block to hold the restore code, and wires up
22106   // the new block to the return destination with a normal JMP_4.
22107   MachineBasicBlock *RestoreMBB =
22108       MF->CreateMachineBasicBlock(BB->getBasicBlock());
22109   assert(BB->succ_size() == 1);
22110   MF->insert(std::next(BB->getIterator()), RestoreMBB);
22111   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
22112   BB->addSuccessor(RestoreMBB);
22113   MI->getOperand(0).setMBB(RestoreMBB);
22114
22115   auto RestoreMBBI = RestoreMBB->begin();
22116   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
22117   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
22118   return BB;
22119 }
22120
22121 MachineBasicBlock *
22122 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
22123                                        MachineBasicBlock *BB) const {
22124   MachineFunction *MF = BB->getParent();
22125   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
22126   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
22127   // Only 32-bit SEH requires special handling for catchpad.
22128   if (IsSEH && Subtarget->is32Bit()) {
22129     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22130     DebugLoc DL = MI->getDebugLoc();
22131     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
22132   }
22133   MI->eraseFromParent();
22134   return BB;
22135 }
22136
22137 MachineBasicBlock *
22138 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
22139                                       MachineBasicBlock *BB) const {
22140   // This is pretty easy.  We're taking the value that we received from
22141   // our load from the relocation, sticking it in either RDI (x86-64)
22142   // or EAX and doing an indirect call.  The return value will then
22143   // be in the normal return register.
22144   MachineFunction *F = BB->getParent();
22145   const X86InstrInfo *TII = Subtarget->getInstrInfo();
22146   DebugLoc DL = MI->getDebugLoc();
22147
22148   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
22149   assert(MI->getOperand(3).isGlobal() && "This should be a global");
22150
22151   // Get a register mask for the lowered call.
22152   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
22153   // proper register mask.
22154   const uint32_t *RegMask =
22155       Subtarget->is64Bit() ?
22156       Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
22157       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
22158   if (Subtarget->is64Bit()) {
22159     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22160                                       TII->get(X86::MOV64rm), X86::RDI)
22161     .addReg(X86::RIP)
22162     .addImm(0).addReg(0)
22163     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22164                       MI->getOperand(3).getTargetFlags())
22165     .addReg(0);
22166     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
22167     addDirectMem(MIB, X86::RDI);
22168     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
22169   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
22170     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22171                                       TII->get(X86::MOV32rm), X86::EAX)
22172     .addReg(0)
22173     .addImm(0).addReg(0)
22174     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22175                       MI->getOperand(3).getTargetFlags())
22176     .addReg(0);
22177     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22178     addDirectMem(MIB, X86::EAX);
22179     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22180   } else {
22181     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22182                                       TII->get(X86::MOV32rm), X86::EAX)
22183     .addReg(TII->getGlobalBaseReg(F))
22184     .addImm(0).addReg(0)
22185     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22186                       MI->getOperand(3).getTargetFlags())
22187     .addReg(0);
22188     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22189     addDirectMem(MIB, X86::EAX);
22190     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22191   }
22192
22193   MI->eraseFromParent(); // The pseudo instruction is gone now.
22194   return BB;
22195 }
22196
22197 MachineBasicBlock *
22198 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
22199                                     MachineBasicBlock *MBB) const {
22200   DebugLoc DL = MI->getDebugLoc();
22201   MachineFunction *MF = MBB->getParent();
22202   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22203   MachineRegisterInfo &MRI = MF->getRegInfo();
22204
22205   const BasicBlock *BB = MBB->getBasicBlock();
22206   MachineFunction::iterator I = ++MBB->getIterator();
22207
22208   // Memory Reference
22209   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22210   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22211
22212   unsigned DstReg;
22213   unsigned MemOpndSlot = 0;
22214
22215   unsigned CurOp = 0;
22216
22217   DstReg = MI->getOperand(CurOp++).getReg();
22218   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
22219   assert(RC->hasType(MVT::i32) && "Invalid destination!");
22220   unsigned mainDstReg = MRI.createVirtualRegister(RC);
22221   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
22222
22223   MemOpndSlot = CurOp;
22224
22225   MVT PVT = getPointerTy(MF->getDataLayout());
22226   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22227          "Invalid Pointer Size!");
22228
22229   // For v = setjmp(buf), we generate
22230   //
22231   // thisMBB:
22232   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
22233   //  SjLjSetup restoreMBB
22234   //
22235   // mainMBB:
22236   //  v_main = 0
22237   //
22238   // sinkMBB:
22239   //  v = phi(main, restore)
22240   //
22241   // restoreMBB:
22242   //  if base pointer being used, load it from frame
22243   //  v_restore = 1
22244
22245   MachineBasicBlock *thisMBB = MBB;
22246   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22247   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22248   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
22249   MF->insert(I, mainMBB);
22250   MF->insert(I, sinkMBB);
22251   MF->push_back(restoreMBB);
22252   restoreMBB->setHasAddressTaken();
22253
22254   MachineInstrBuilder MIB;
22255
22256   // Transfer the remainder of BB and its successor edges to sinkMBB.
22257   sinkMBB->splice(sinkMBB->begin(), MBB,
22258                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22259   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22260
22261   // thisMBB:
22262   unsigned PtrStoreOpc = 0;
22263   unsigned LabelReg = 0;
22264   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22265   Reloc::Model RM = MF->getTarget().getRelocationModel();
22266   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
22267                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
22268
22269   // Prepare IP either in reg or imm.
22270   if (!UseImmLabel) {
22271     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
22272     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
22273     LabelReg = MRI.createVirtualRegister(PtrRC);
22274     if (Subtarget->is64Bit()) {
22275       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
22276               .addReg(X86::RIP)
22277               .addImm(0)
22278               .addReg(0)
22279               .addMBB(restoreMBB)
22280               .addReg(0);
22281     } else {
22282       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
22283       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
22284               .addReg(XII->getGlobalBaseReg(MF))
22285               .addImm(0)
22286               .addReg(0)
22287               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
22288               .addReg(0);
22289     }
22290   } else
22291     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
22292   // Store IP
22293   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
22294   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22295     if (i == X86::AddrDisp)
22296       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
22297     else
22298       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
22299   }
22300   if (!UseImmLabel)
22301     MIB.addReg(LabelReg);
22302   else
22303     MIB.addMBB(restoreMBB);
22304   MIB.setMemRefs(MMOBegin, MMOEnd);
22305   // Setup
22306   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
22307           .addMBB(restoreMBB);
22308
22309   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22310   MIB.addRegMask(RegInfo->getNoPreservedMask());
22311   thisMBB->addSuccessor(mainMBB);
22312   thisMBB->addSuccessor(restoreMBB);
22313
22314   // mainMBB:
22315   //  EAX = 0
22316   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
22317   mainMBB->addSuccessor(sinkMBB);
22318
22319   // sinkMBB:
22320   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
22321           TII->get(X86::PHI), DstReg)
22322     .addReg(mainDstReg).addMBB(mainMBB)
22323     .addReg(restoreDstReg).addMBB(restoreMBB);
22324
22325   // restoreMBB:
22326   if (RegInfo->hasBasePointer(*MF)) {
22327     const bool Uses64BitFramePtr =
22328         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
22329     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
22330     X86FI->setRestoreBasePointer(MF);
22331     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
22332     unsigned BasePtr = RegInfo->getBaseRegister();
22333     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
22334     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
22335                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
22336       .setMIFlag(MachineInstr::FrameSetup);
22337   }
22338   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
22339   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
22340   restoreMBB->addSuccessor(sinkMBB);
22341
22342   MI->eraseFromParent();
22343   return sinkMBB;
22344 }
22345
22346 MachineBasicBlock *
22347 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22348                                      MachineBasicBlock *MBB) const {
22349   DebugLoc DL = MI->getDebugLoc();
22350   MachineFunction *MF = MBB->getParent();
22351   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22352   MachineRegisterInfo &MRI = MF->getRegInfo();
22353
22354   // Memory Reference
22355   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22356   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22357
22358   MVT PVT = getPointerTy(MF->getDataLayout());
22359   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22360          "Invalid Pointer Size!");
22361
22362   const TargetRegisterClass *RC =
22363     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22364   unsigned Tmp = MRI.createVirtualRegister(RC);
22365   // Since FP is only updated here but NOT referenced, it's treated as GPR.
22366   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22367   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22368   unsigned SP = RegInfo->getStackRegister();
22369
22370   MachineInstrBuilder MIB;
22371
22372   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22373   const int64_t SPOffset = 2 * PVT.getStoreSize();
22374
22375   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22376   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22377
22378   // Reload FP
22379   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22380   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22381     MIB.addOperand(MI->getOperand(i));
22382   MIB.setMemRefs(MMOBegin, MMOEnd);
22383   // Reload IP
22384   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22385   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22386     if (i == X86::AddrDisp)
22387       MIB.addDisp(MI->getOperand(i), LabelOffset);
22388     else
22389       MIB.addOperand(MI->getOperand(i));
22390   }
22391   MIB.setMemRefs(MMOBegin, MMOEnd);
22392   // Reload SP
22393   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22394   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22395     if (i == X86::AddrDisp)
22396       MIB.addDisp(MI->getOperand(i), SPOffset);
22397     else
22398       MIB.addOperand(MI->getOperand(i));
22399   }
22400   MIB.setMemRefs(MMOBegin, MMOEnd);
22401   // Jump
22402   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22403
22404   MI->eraseFromParent();
22405   return MBB;
22406 }
22407
22408 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22409 // accumulator loops. Writing back to the accumulator allows the coalescer
22410 // to remove extra copies in the loop.
22411 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
22412 MachineBasicBlock *
22413 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22414                                  MachineBasicBlock *MBB) const {
22415   MachineOperand &AddendOp = MI->getOperand(3);
22416
22417   // Bail out early if the addend isn't a register - we can't switch these.
22418   if (!AddendOp.isReg())
22419     return MBB;
22420
22421   MachineFunction &MF = *MBB->getParent();
22422   MachineRegisterInfo &MRI = MF.getRegInfo();
22423
22424   // Check whether the addend is defined by a PHI:
22425   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22426   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22427   if (!AddendDef.isPHI())
22428     return MBB;
22429
22430   // Look for the following pattern:
22431   // loop:
22432   //   %addend = phi [%entry, 0], [%loop, %result]
22433   //   ...
22434   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22435
22436   // Replace with:
22437   //   loop:
22438   //   %addend = phi [%entry, 0], [%loop, %result]
22439   //   ...
22440   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22441
22442   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22443     assert(AddendDef.getOperand(i).isReg());
22444     MachineOperand PHISrcOp = AddendDef.getOperand(i);
22445     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22446     if (&PHISrcInst == MI) {
22447       // Found a matching instruction.
22448       unsigned NewFMAOpc = 0;
22449       switch (MI->getOpcode()) {
22450         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22451         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22452         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22453         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22454         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22455         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22456         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22457         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22458         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22459         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22460         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22461         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22462         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22463         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22464         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22465         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22466         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22467         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22468         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22469         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22470
22471         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22472         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22473         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22474         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22475         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22476         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22477         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22478         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22479         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22480         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22481         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22482         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22483         default: llvm_unreachable("Unrecognized FMA variant.");
22484       }
22485
22486       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22487       MachineInstrBuilder MIB =
22488         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22489         .addOperand(MI->getOperand(0))
22490         .addOperand(MI->getOperand(3))
22491         .addOperand(MI->getOperand(2))
22492         .addOperand(MI->getOperand(1));
22493       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22494       MI->eraseFromParent();
22495     }
22496   }
22497
22498   return MBB;
22499 }
22500
22501 MachineBasicBlock *
22502 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22503                                                MachineBasicBlock *BB) const {
22504   switch (MI->getOpcode()) {
22505   default: llvm_unreachable("Unexpected instr type to insert");
22506   case X86::TAILJMPd64:
22507   case X86::TAILJMPr64:
22508   case X86::TAILJMPm64:
22509   case X86::TAILJMPd64_REX:
22510   case X86::TAILJMPr64_REX:
22511   case X86::TAILJMPm64_REX:
22512     llvm_unreachable("TAILJMP64 would not be touched here.");
22513   case X86::TCRETURNdi64:
22514   case X86::TCRETURNri64:
22515   case X86::TCRETURNmi64:
22516     return BB;
22517   case X86::WIN_ALLOCA:
22518     return EmitLoweredWinAlloca(MI, BB);
22519   case X86::CATCHRET:
22520     return EmitLoweredCatchRet(MI, BB);
22521   case X86::CATCHPAD:
22522     return EmitLoweredCatchPad(MI, BB);
22523   case X86::SEG_ALLOCA_32:
22524   case X86::SEG_ALLOCA_64:
22525     return EmitLoweredSegAlloca(MI, BB);
22526   case X86::TLSCall_32:
22527   case X86::TLSCall_64:
22528     return EmitLoweredTLSCall(MI, BB);
22529   case X86::CMOV_FR32:
22530   case X86::CMOV_FR64:
22531   case X86::CMOV_FR128:
22532   case X86::CMOV_GR8:
22533   case X86::CMOV_GR16:
22534   case X86::CMOV_GR32:
22535   case X86::CMOV_RFP32:
22536   case X86::CMOV_RFP64:
22537   case X86::CMOV_RFP80:
22538   case X86::CMOV_V2F64:
22539   case X86::CMOV_V2I64:
22540   case X86::CMOV_V4F32:
22541   case X86::CMOV_V4F64:
22542   case X86::CMOV_V4I64:
22543   case X86::CMOV_V16F32:
22544   case X86::CMOV_V8F32:
22545   case X86::CMOV_V8F64:
22546   case X86::CMOV_V8I64:
22547   case X86::CMOV_V8I1:
22548   case X86::CMOV_V16I1:
22549   case X86::CMOV_V32I1:
22550   case X86::CMOV_V64I1:
22551     return EmitLoweredSelect(MI, BB);
22552
22553   case X86::RDFLAGS32:
22554   case X86::RDFLAGS64: {
22555     DebugLoc DL = MI->getDebugLoc();
22556     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22557     unsigned PushF =
22558         MI->getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
22559     unsigned Pop =
22560         MI->getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
22561     BuildMI(*BB, MI, DL, TII->get(PushF));
22562     BuildMI(*BB, MI, DL, TII->get(Pop), MI->getOperand(0).getReg());
22563
22564     MI->eraseFromParent(); // The pseudo is gone now.
22565     return BB;
22566   }
22567
22568   case X86::WRFLAGS32:
22569   case X86::WRFLAGS64: {
22570     DebugLoc DL = MI->getDebugLoc();
22571     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22572     unsigned Push =
22573         MI->getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
22574     unsigned PopF =
22575         MI->getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
22576     BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI->getOperand(0).getReg());
22577     BuildMI(*BB, MI, DL, TII->get(PopF));
22578
22579     MI->eraseFromParent(); // The pseudo is gone now.
22580     return BB;
22581   }
22582
22583   case X86::RELEASE_FADD32mr:
22584   case X86::RELEASE_FADD64mr:
22585     return EmitLoweredAtomicFP(MI, BB);
22586
22587   case X86::FP32_TO_INT16_IN_MEM:
22588   case X86::FP32_TO_INT32_IN_MEM:
22589   case X86::FP32_TO_INT64_IN_MEM:
22590   case X86::FP64_TO_INT16_IN_MEM:
22591   case X86::FP64_TO_INT32_IN_MEM:
22592   case X86::FP64_TO_INT64_IN_MEM:
22593   case X86::FP80_TO_INT16_IN_MEM:
22594   case X86::FP80_TO_INT32_IN_MEM:
22595   case X86::FP80_TO_INT64_IN_MEM: {
22596     MachineFunction *F = BB->getParent();
22597     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22598     DebugLoc DL = MI->getDebugLoc();
22599
22600     // Change the floating point control register to use "round towards zero"
22601     // mode when truncating to an integer value.
22602     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22603     addFrameReference(BuildMI(*BB, MI, DL,
22604                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
22605
22606     // Load the old value of the high byte of the control word...
22607     unsigned OldCW =
22608       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22609     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22610                       CWFrameIdx);
22611
22612     // Set the high part to be round to zero...
22613     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22614       .addImm(0xC7F);
22615
22616     // Reload the modified control word now...
22617     addFrameReference(BuildMI(*BB, MI, DL,
22618                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22619
22620     // Restore the memory image of control word to original value
22621     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22622       .addReg(OldCW);
22623
22624     // Get the X86 opcode to use.
22625     unsigned Opc;
22626     switch (MI->getOpcode()) {
22627     default: llvm_unreachable("illegal opcode!");
22628     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22629     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22630     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22631     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22632     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22633     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22634     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22635     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22636     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22637     }
22638
22639     X86AddressMode AM;
22640     MachineOperand &Op = MI->getOperand(0);
22641     if (Op.isReg()) {
22642       AM.BaseType = X86AddressMode::RegBase;
22643       AM.Base.Reg = Op.getReg();
22644     } else {
22645       AM.BaseType = X86AddressMode::FrameIndexBase;
22646       AM.Base.FrameIndex = Op.getIndex();
22647     }
22648     Op = MI->getOperand(1);
22649     if (Op.isImm())
22650       AM.Scale = Op.getImm();
22651     Op = MI->getOperand(2);
22652     if (Op.isImm())
22653       AM.IndexReg = Op.getImm();
22654     Op = MI->getOperand(3);
22655     if (Op.isGlobal()) {
22656       AM.GV = Op.getGlobal();
22657     } else {
22658       AM.Disp = Op.getImm();
22659     }
22660     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22661                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22662
22663     // Reload the original control word now.
22664     addFrameReference(BuildMI(*BB, MI, DL,
22665                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22666
22667     MI->eraseFromParent();   // The pseudo instruction is gone now.
22668     return BB;
22669   }
22670     // String/text processing lowering.
22671   case X86::PCMPISTRM128REG:
22672   case X86::VPCMPISTRM128REG:
22673   case X86::PCMPISTRM128MEM:
22674   case X86::VPCMPISTRM128MEM:
22675   case X86::PCMPESTRM128REG:
22676   case X86::VPCMPESTRM128REG:
22677   case X86::PCMPESTRM128MEM:
22678   case X86::VPCMPESTRM128MEM:
22679     assert(Subtarget->hasSSE42() &&
22680            "Target must have SSE4.2 or AVX features enabled");
22681     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22682
22683   // String/text processing lowering.
22684   case X86::PCMPISTRIREG:
22685   case X86::VPCMPISTRIREG:
22686   case X86::PCMPISTRIMEM:
22687   case X86::VPCMPISTRIMEM:
22688   case X86::PCMPESTRIREG:
22689   case X86::VPCMPESTRIREG:
22690   case X86::PCMPESTRIMEM:
22691   case X86::VPCMPESTRIMEM:
22692     assert(Subtarget->hasSSE42() &&
22693            "Target must have SSE4.2 or AVX features enabled");
22694     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22695
22696   // Thread synchronization.
22697   case X86::MONITOR:
22698     return EmitMonitor(MI, BB, Subtarget);
22699   // PKU feature
22700   case X86::WRPKRU:
22701     return EmitWRPKRU(MI, BB, Subtarget);
22702   case X86::RDPKRU:
22703     return EmitRDPKRU(MI, BB, Subtarget);
22704   // xbegin
22705   case X86::XBEGIN:
22706     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22707
22708   case X86::VASTART_SAVE_XMM_REGS:
22709     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22710
22711   case X86::VAARG_64:
22712     return EmitVAARG64WithCustomInserter(MI, BB);
22713
22714   case X86::EH_SjLj_SetJmp32:
22715   case X86::EH_SjLj_SetJmp64:
22716     return emitEHSjLjSetJmp(MI, BB);
22717
22718   case X86::EH_SjLj_LongJmp32:
22719   case X86::EH_SjLj_LongJmp64:
22720     return emitEHSjLjLongJmp(MI, BB);
22721
22722   case TargetOpcode::STATEPOINT:
22723     // As an implementation detail, STATEPOINT shares the STACKMAP format at
22724     // this point in the process.  We diverge later.
22725     return emitPatchPoint(MI, BB);
22726
22727   case TargetOpcode::STACKMAP:
22728   case TargetOpcode::PATCHPOINT:
22729     return emitPatchPoint(MI, BB);
22730
22731   case X86::VFMADDPDr213r:
22732   case X86::VFMADDPSr213r:
22733   case X86::VFMADDSDr213r:
22734   case X86::VFMADDSSr213r:
22735   case X86::VFMSUBPDr213r:
22736   case X86::VFMSUBPSr213r:
22737   case X86::VFMSUBSDr213r:
22738   case X86::VFMSUBSSr213r:
22739   case X86::VFNMADDPDr213r:
22740   case X86::VFNMADDPSr213r:
22741   case X86::VFNMADDSDr213r:
22742   case X86::VFNMADDSSr213r:
22743   case X86::VFNMSUBPDr213r:
22744   case X86::VFNMSUBPSr213r:
22745   case X86::VFNMSUBSDr213r:
22746   case X86::VFNMSUBSSr213r:
22747   case X86::VFMADDSUBPDr213r:
22748   case X86::VFMADDSUBPSr213r:
22749   case X86::VFMSUBADDPDr213r:
22750   case X86::VFMSUBADDPSr213r:
22751   case X86::VFMADDPDr213rY:
22752   case X86::VFMADDPSr213rY:
22753   case X86::VFMSUBPDr213rY:
22754   case X86::VFMSUBPSr213rY:
22755   case X86::VFNMADDPDr213rY:
22756   case X86::VFNMADDPSr213rY:
22757   case X86::VFNMSUBPDr213rY:
22758   case X86::VFNMSUBPSr213rY:
22759   case X86::VFMADDSUBPDr213rY:
22760   case X86::VFMADDSUBPSr213rY:
22761   case X86::VFMSUBADDPDr213rY:
22762   case X86::VFMSUBADDPSr213rY:
22763     return emitFMA3Instr(MI, BB);
22764   }
22765 }
22766
22767 //===----------------------------------------------------------------------===//
22768 //                           X86 Optimization Hooks
22769 //===----------------------------------------------------------------------===//
22770
22771 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22772                                                       APInt &KnownZero,
22773                                                       APInt &KnownOne,
22774                                                       const SelectionDAG &DAG,
22775                                                       unsigned Depth) const {
22776   unsigned BitWidth = KnownZero.getBitWidth();
22777   unsigned Opc = Op.getOpcode();
22778   assert((Opc >= ISD::BUILTIN_OP_END ||
22779           Opc == ISD::INTRINSIC_WO_CHAIN ||
22780           Opc == ISD::INTRINSIC_W_CHAIN ||
22781           Opc == ISD::INTRINSIC_VOID) &&
22782          "Should use MaskedValueIsZero if you don't know whether Op"
22783          " is a target node!");
22784
22785   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
22786   switch (Opc) {
22787   default: break;
22788   case X86ISD::ADD:
22789   case X86ISD::SUB:
22790   case X86ISD::ADC:
22791   case X86ISD::SBB:
22792   case X86ISD::SMUL:
22793   case X86ISD::UMUL:
22794   case X86ISD::INC:
22795   case X86ISD::DEC:
22796   case X86ISD::OR:
22797   case X86ISD::XOR:
22798   case X86ISD::AND:
22799     // These nodes' second result is a boolean.
22800     if (Op.getResNo() == 0)
22801       break;
22802     // Fallthrough
22803   case X86ISD::SETCC:
22804     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22805     break;
22806   case ISD::INTRINSIC_WO_CHAIN: {
22807     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22808     unsigned NumLoBits = 0;
22809     switch (IntId) {
22810     default: break;
22811     case Intrinsic::x86_sse_movmsk_ps:
22812     case Intrinsic::x86_avx_movmsk_ps_256:
22813     case Intrinsic::x86_sse2_movmsk_pd:
22814     case Intrinsic::x86_avx_movmsk_pd_256:
22815     case Intrinsic::x86_mmx_pmovmskb:
22816     case Intrinsic::x86_sse2_pmovmskb_128:
22817     case Intrinsic::x86_avx2_pmovmskb: {
22818       // High bits of movmskp{s|d}, pmovmskb are known zero.
22819       switch (IntId) {
22820         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22821         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22822         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22823         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22824         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22825         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22826         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22827         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22828       }
22829       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22830       break;
22831     }
22832     }
22833     break;
22834   }
22835   }
22836 }
22837
22838 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22839   SDValue Op,
22840   const SelectionDAG &,
22841   unsigned Depth) const {
22842   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22843   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22844     return Op.getValueType().getScalarSizeInBits();
22845
22846   // Fallback case.
22847   return 1;
22848 }
22849
22850 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22851 /// node is a GlobalAddress + offset.
22852 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22853                                        const GlobalValue* &GA,
22854                                        int64_t &Offset) const {
22855   if (N->getOpcode() == X86ISD::Wrapper) {
22856     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22857       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22858       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22859       return true;
22860     }
22861   }
22862   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22863 }
22864
22865 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22866 /// FIXME: This could be expanded to support 512 bit vectors as well.
22867 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22868                                         TargetLowering::DAGCombinerInfo &DCI,
22869                                         const X86Subtarget* Subtarget) {
22870   SDLoc dl(N);
22871   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22872   SDValue V1 = SVOp->getOperand(0);
22873   SDValue V2 = SVOp->getOperand(1);
22874   MVT VT = SVOp->getSimpleValueType(0);
22875   unsigned NumElems = VT.getVectorNumElements();
22876
22877   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22878       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22879     //
22880     //                   0,0,0,...
22881     //                      |
22882     //    V      UNDEF    BUILD_VECTOR    UNDEF
22883     //     \      /           \           /
22884     //  CONCAT_VECTOR         CONCAT_VECTOR
22885     //         \                  /
22886     //          \                /
22887     //          RESULT: V + zero extended
22888     //
22889     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22890         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22891         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22892       return SDValue();
22893
22894     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22895       return SDValue();
22896
22897     // To match the shuffle mask, the first half of the mask should
22898     // be exactly the first vector, and all the rest a splat with the
22899     // first element of the second one.
22900     for (unsigned i = 0; i != NumElems/2; ++i)
22901       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22902           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22903         return SDValue();
22904
22905     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22906     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22907       if (Ld->hasNUsesOfValue(1, 0)) {
22908         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22909         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22910         SDValue ResNode =
22911           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22912                                   Ld->getMemoryVT(),
22913                                   Ld->getPointerInfo(),
22914                                   Ld->getAlignment(),
22915                                   false/*isVolatile*/, true/*ReadMem*/,
22916                                   false/*WriteMem*/);
22917
22918         // Make sure the newly-created LOAD is in the same position as Ld in
22919         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22920         // and update uses of Ld's output chain to use the TokenFactor.
22921         if (Ld->hasAnyUseOfValue(1)) {
22922           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22923                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22924           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22925           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22926                                  SDValue(ResNode.getNode(), 1));
22927         }
22928
22929         return DAG.getBitcast(VT, ResNode);
22930       }
22931     }
22932
22933     // Emit a zeroed vector and insert the desired subvector on its
22934     // first half.
22935     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22936     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22937     return DCI.CombineTo(N, InsV);
22938   }
22939
22940   return SDValue();
22941 }
22942
22943 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22944 /// possible.
22945 ///
22946 /// This is the leaf of the recursive combinine below. When we have found some
22947 /// chain of single-use x86 shuffle instructions and accumulated the combined
22948 /// shuffle mask represented by them, this will try to pattern match that mask
22949 /// into either a single instruction if there is a special purpose instruction
22950 /// for this operation, or into a PSHUFB instruction which is a fully general
22951 /// instruction but should only be used to replace chains over a certain depth.
22952 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22953                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22954                                    TargetLowering::DAGCombinerInfo &DCI,
22955                                    const X86Subtarget *Subtarget) {
22956   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22957
22958   // Find the operand that enters the chain. Note that multiple uses are OK
22959   // here, we're not going to remove the operand we find.
22960   SDValue Input = Op.getOperand(0);
22961   while (Input.getOpcode() == ISD::BITCAST)
22962     Input = Input.getOperand(0);
22963
22964   MVT VT = Input.getSimpleValueType();
22965   MVT RootVT = Root.getSimpleValueType();
22966   SDLoc DL(Root);
22967
22968   if (Mask.size() == 1) {
22969     int Index = Mask[0];
22970     assert((Index >= 0 || Index == SM_SentinelUndef ||
22971             Index == SM_SentinelZero) &&
22972            "Invalid shuffle index found!");
22973
22974     // We may end up with an accumulated mask of size 1 as a result of
22975     // widening of shuffle operands (see function canWidenShuffleElements).
22976     // If the only shuffle index is equal to SM_SentinelZero then propagate
22977     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22978     // mask, and therefore the entire chain of shuffles can be folded away.
22979     if (Index == SM_SentinelZero)
22980       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22981     else
22982       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22983                     /*AddTo*/ true);
22984     return true;
22985   }
22986
22987   // Use the float domain if the operand type is a floating point type.
22988   bool FloatDomain = VT.isFloatingPoint();
22989
22990   // For floating point shuffles, we don't have free copies in the shuffle
22991   // instructions or the ability to load as part of the instruction, so
22992   // canonicalize their shuffles to UNPCK or MOV variants.
22993   //
22994   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22995   // vectors because it can have a load folded into it that UNPCK cannot. This
22996   // doesn't preclude something switching to the shorter encoding post-RA.
22997   //
22998   // FIXME: Should teach these routines about AVX vector widths.
22999   if (FloatDomain && VT.is128BitVector()) {
23000     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
23001       bool Lo = Mask.equals({0, 0});
23002       unsigned Shuffle;
23003       MVT ShuffleVT;
23004       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
23005       // is no slower than UNPCKLPD but has the option to fold the input operand
23006       // into even an unaligned memory load.
23007       if (Lo && Subtarget->hasSSE3()) {
23008         Shuffle = X86ISD::MOVDDUP;
23009         ShuffleVT = MVT::v2f64;
23010       } else {
23011         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
23012         // than the UNPCK variants.
23013         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
23014         ShuffleVT = MVT::v4f32;
23015       }
23016       if (Depth == 1 && Root->getOpcode() == Shuffle)
23017         return false; // Nothing to do!
23018       Op = DAG.getBitcast(ShuffleVT, Input);
23019       DCI.AddToWorklist(Op.getNode());
23020       if (Shuffle == X86ISD::MOVDDUP)
23021         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23022       else
23023         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23024       DCI.AddToWorklist(Op.getNode());
23025       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23026                     /*AddTo*/ true);
23027       return true;
23028     }
23029     if (Subtarget->hasSSE3() &&
23030         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
23031       bool Lo = Mask.equals({0, 0, 2, 2});
23032       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
23033       MVT ShuffleVT = MVT::v4f32;
23034       if (Depth == 1 && Root->getOpcode() == Shuffle)
23035         return false; // Nothing to do!
23036       Op = DAG.getBitcast(ShuffleVT, Input);
23037       DCI.AddToWorklist(Op.getNode());
23038       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23039       DCI.AddToWorklist(Op.getNode());
23040       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23041                     /*AddTo*/ true);
23042       return true;
23043     }
23044     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
23045       bool Lo = Mask.equals({0, 0, 1, 1});
23046       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23047       MVT ShuffleVT = MVT::v4f32;
23048       if (Depth == 1 && Root->getOpcode() == Shuffle)
23049         return false; // Nothing to do!
23050       Op = DAG.getBitcast(ShuffleVT, Input);
23051       DCI.AddToWorklist(Op.getNode());
23052       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23053       DCI.AddToWorklist(Op.getNode());
23054       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23055                     /*AddTo*/ true);
23056       return true;
23057     }
23058   }
23059
23060   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
23061   // variants as none of these have single-instruction variants that are
23062   // superior to the UNPCK formulation.
23063   if (!FloatDomain && VT.is128BitVector() &&
23064       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23065        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
23066        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
23067        Mask.equals(
23068            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
23069     bool Lo = Mask[0] == 0;
23070     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23071     if (Depth == 1 && Root->getOpcode() == Shuffle)
23072       return false; // Nothing to do!
23073     MVT ShuffleVT;
23074     switch (Mask.size()) {
23075     case 8:
23076       ShuffleVT = MVT::v8i16;
23077       break;
23078     case 16:
23079       ShuffleVT = MVT::v16i8;
23080       break;
23081     default:
23082       llvm_unreachable("Impossible mask size!");
23083     };
23084     Op = DAG.getBitcast(ShuffleVT, Input);
23085     DCI.AddToWorklist(Op.getNode());
23086     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23087     DCI.AddToWorklist(Op.getNode());
23088     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23089                   /*AddTo*/ true);
23090     return true;
23091   }
23092
23093   // Don't try to re-form single instruction chains under any circumstances now
23094   // that we've done encoding canonicalization for them.
23095   if (Depth < 2)
23096     return false;
23097
23098   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
23099   // can replace them with a single PSHUFB instruction profitably. Intel's
23100   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
23101   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
23102   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
23103     SmallVector<SDValue, 16> PSHUFBMask;
23104     int NumBytes = VT.getSizeInBits() / 8;
23105     int Ratio = NumBytes / Mask.size();
23106     for (int i = 0; i < NumBytes; ++i) {
23107       if (Mask[i / Ratio] == SM_SentinelUndef) {
23108         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
23109         continue;
23110       }
23111       int M = Mask[i / Ratio] != SM_SentinelZero
23112                   ? Ratio * Mask[i / Ratio] + i % Ratio
23113                   : 255;
23114       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
23115     }
23116     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
23117     Op = DAG.getBitcast(ByteVT, Input);
23118     DCI.AddToWorklist(Op.getNode());
23119     SDValue PSHUFBMaskOp =
23120         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
23121     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
23122     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
23123     DCI.AddToWorklist(Op.getNode());
23124     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23125                   /*AddTo*/ true);
23126     return true;
23127   }
23128
23129   // Failed to find any combines.
23130   return false;
23131 }
23132
23133 /// \brief Fully generic combining of x86 shuffle instructions.
23134 ///
23135 /// This should be the last combine run over the x86 shuffle instructions. Once
23136 /// they have been fully optimized, this will recursively consider all chains
23137 /// of single-use shuffle instructions, build a generic model of the cumulative
23138 /// shuffle operation, and check for simpler instructions which implement this
23139 /// operation. We use this primarily for two purposes:
23140 ///
23141 /// 1) Collapse generic shuffles to specialized single instructions when
23142 ///    equivalent. In most cases, this is just an encoding size win, but
23143 ///    sometimes we will collapse multiple generic shuffles into a single
23144 ///    special-purpose shuffle.
23145 /// 2) Look for sequences of shuffle instructions with 3 or more total
23146 ///    instructions, and replace them with the slightly more expensive SSSE3
23147 ///    PSHUFB instruction if available. We do this as the last combining step
23148 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
23149 ///    a suitable short sequence of other instructions. The PHUFB will either
23150 ///    use a register or have to read from memory and so is slightly (but only
23151 ///    slightly) more expensive than the other shuffle instructions.
23152 ///
23153 /// Because this is inherently a quadratic operation (for each shuffle in
23154 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
23155 /// This should never be an issue in practice as the shuffle lowering doesn't
23156 /// produce sequences of more than 8 instructions.
23157 ///
23158 /// FIXME: We will currently miss some cases where the redundant shuffling
23159 /// would simplify under the threshold for PSHUFB formation because of
23160 /// combine-ordering. To fix this, we should do the redundant instruction
23161 /// combining in this recursive walk.
23162 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
23163                                           ArrayRef<int> RootMask,
23164                                           int Depth, bool HasPSHUFB,
23165                                           SelectionDAG &DAG,
23166                                           TargetLowering::DAGCombinerInfo &DCI,
23167                                           const X86Subtarget *Subtarget) {
23168   // Bound the depth of our recursive combine because this is ultimately
23169   // quadratic in nature.
23170   if (Depth > 8)
23171     return false;
23172
23173   // Directly rip through bitcasts to find the underlying operand.
23174   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
23175     Op = Op.getOperand(0);
23176
23177   MVT VT = Op.getSimpleValueType();
23178   if (!VT.isVector())
23179     return false; // Bail if we hit a non-vector.
23180
23181   assert(Root.getSimpleValueType().isVector() &&
23182          "Shuffles operate on vector types!");
23183   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
23184          "Can only combine shuffles of the same vector register size.");
23185
23186   if (!isTargetShuffle(Op.getOpcode()))
23187     return false;
23188   SmallVector<int, 16> OpMask;
23189   bool IsUnary;
23190   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
23191   // We only can combine unary shuffles which we can decode the mask for.
23192   if (!HaveMask || !IsUnary)
23193     return false;
23194
23195   assert(VT.getVectorNumElements() == OpMask.size() &&
23196          "Different mask size from vector size!");
23197   assert(((RootMask.size() > OpMask.size() &&
23198            RootMask.size() % OpMask.size() == 0) ||
23199           (OpMask.size() > RootMask.size() &&
23200            OpMask.size() % RootMask.size() == 0) ||
23201           OpMask.size() == RootMask.size()) &&
23202          "The smaller number of elements must divide the larger.");
23203   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
23204   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
23205   assert(((RootRatio == 1 && OpRatio == 1) ||
23206           (RootRatio == 1) != (OpRatio == 1)) &&
23207          "Must not have a ratio for both incoming and op masks!");
23208
23209   SmallVector<int, 16> Mask;
23210   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
23211
23212   // Merge this shuffle operation's mask into our accumulated mask. Note that
23213   // this shuffle's mask will be the first applied to the input, followed by the
23214   // root mask to get us all the way to the root value arrangement. The reason
23215   // for this order is that we are recursing up the operation chain.
23216   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
23217     int RootIdx = i / RootRatio;
23218     if (RootMask[RootIdx] < 0) {
23219       // This is a zero or undef lane, we're done.
23220       Mask.push_back(RootMask[RootIdx]);
23221       continue;
23222     }
23223
23224     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
23225     int OpIdx = RootMaskedIdx / OpRatio;
23226     if (OpMask[OpIdx] < 0) {
23227       // The incoming lanes are zero or undef, it doesn't matter which ones we
23228       // are using.
23229       Mask.push_back(OpMask[OpIdx]);
23230       continue;
23231     }
23232
23233     // Ok, we have non-zero lanes, map them through.
23234     Mask.push_back(OpMask[OpIdx] * OpRatio +
23235                    RootMaskedIdx % OpRatio);
23236   }
23237
23238   // See if we can recurse into the operand to combine more things.
23239   switch (Op.getOpcode()) {
23240   case X86ISD::PSHUFB:
23241     HasPSHUFB = true;
23242   case X86ISD::PSHUFD:
23243   case X86ISD::PSHUFHW:
23244   case X86ISD::PSHUFLW:
23245     if (Op.getOperand(0).hasOneUse() &&
23246         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23247                                       HasPSHUFB, DAG, DCI, Subtarget))
23248       return true;
23249     break;
23250
23251   case X86ISD::UNPCKL:
23252   case X86ISD::UNPCKH:
23253     assert(Op.getOperand(0) == Op.getOperand(1) &&
23254            "We only combine unary shuffles!");
23255     // We can't check for single use, we have to check that this shuffle is the
23256     // only user.
23257     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
23258         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23259                                       HasPSHUFB, DAG, DCI, Subtarget))
23260       return true;
23261     break;
23262   }
23263
23264   // Minor canonicalization of the accumulated shuffle mask to make it easier
23265   // to match below. All this does is detect masks with squential pairs of
23266   // elements, and shrink them to the half-width mask. It does this in a loop
23267   // so it will reduce the size of the mask to the minimal width mask which
23268   // performs an equivalent shuffle.
23269   SmallVector<int, 16> WidenedMask;
23270   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
23271     Mask = std::move(WidenedMask);
23272     WidenedMask.clear();
23273   }
23274
23275   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
23276                                 Subtarget);
23277 }
23278
23279 /// \brief Get the PSHUF-style mask from PSHUF node.
23280 ///
23281 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
23282 /// PSHUF-style masks that can be reused with such instructions.
23283 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
23284   MVT VT = N.getSimpleValueType();
23285   SmallVector<int, 4> Mask;
23286   bool IsUnary;
23287   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
23288   (void)HaveMask;
23289   assert(HaveMask);
23290
23291   // If we have more than 128-bits, only the low 128-bits of shuffle mask
23292   // matter. Check that the upper masks are repeats and remove them.
23293   if (VT.getSizeInBits() > 128) {
23294     int LaneElts = 128 / VT.getScalarSizeInBits();
23295 #ifndef NDEBUG
23296     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
23297       for (int j = 0; j < LaneElts; ++j)
23298         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
23299                "Mask doesn't repeat in high 128-bit lanes!");
23300 #endif
23301     Mask.resize(LaneElts);
23302   }
23303
23304   switch (N.getOpcode()) {
23305   case X86ISD::PSHUFD:
23306     return Mask;
23307   case X86ISD::PSHUFLW:
23308     Mask.resize(4);
23309     return Mask;
23310   case X86ISD::PSHUFHW:
23311     Mask.erase(Mask.begin(), Mask.begin() + 4);
23312     for (int &M : Mask)
23313       M -= 4;
23314     return Mask;
23315   default:
23316     llvm_unreachable("No valid shuffle instruction found!");
23317   }
23318 }
23319
23320 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
23321 ///
23322 /// We walk up the chain and look for a combinable shuffle, skipping over
23323 /// shuffles that we could hoist this shuffle's transformation past without
23324 /// altering anything.
23325 static SDValue
23326 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23327                              SelectionDAG &DAG,
23328                              TargetLowering::DAGCombinerInfo &DCI) {
23329   assert(N.getOpcode() == X86ISD::PSHUFD &&
23330          "Called with something other than an x86 128-bit half shuffle!");
23331   SDLoc DL(N);
23332
23333   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23334   // of the shuffles in the chain so that we can form a fresh chain to replace
23335   // this one.
23336   SmallVector<SDValue, 8> Chain;
23337   SDValue V = N.getOperand(0);
23338   for (; V.hasOneUse(); V = V.getOperand(0)) {
23339     switch (V.getOpcode()) {
23340     default:
23341       return SDValue(); // Nothing combined!
23342
23343     case ISD::BITCAST:
23344       // Skip bitcasts as we always know the type for the target specific
23345       // instructions.
23346       continue;
23347
23348     case X86ISD::PSHUFD:
23349       // Found another dword shuffle.
23350       break;
23351
23352     case X86ISD::PSHUFLW:
23353       // Check that the low words (being shuffled) are the identity in the
23354       // dword shuffle, and the high words are self-contained.
23355       if (Mask[0] != 0 || Mask[1] != 1 ||
23356           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23357         return SDValue();
23358
23359       Chain.push_back(V);
23360       continue;
23361
23362     case X86ISD::PSHUFHW:
23363       // Check that the high words (being shuffled) are the identity in the
23364       // dword shuffle, and the low words are self-contained.
23365       if (Mask[2] != 2 || Mask[3] != 3 ||
23366           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23367         return SDValue();
23368
23369       Chain.push_back(V);
23370       continue;
23371
23372     case X86ISD::UNPCKL:
23373     case X86ISD::UNPCKH:
23374       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23375       // shuffle into a preceding word shuffle.
23376       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23377           V.getSimpleValueType().getVectorElementType() != MVT::i16)
23378         return SDValue();
23379
23380       // Search for a half-shuffle which we can combine with.
23381       unsigned CombineOp =
23382           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23383       if (V.getOperand(0) != V.getOperand(1) ||
23384           !V->isOnlyUserOf(V.getOperand(0).getNode()))
23385         return SDValue();
23386       Chain.push_back(V);
23387       V = V.getOperand(0);
23388       do {
23389         switch (V.getOpcode()) {
23390         default:
23391           return SDValue(); // Nothing to combine.
23392
23393         case X86ISD::PSHUFLW:
23394         case X86ISD::PSHUFHW:
23395           if (V.getOpcode() == CombineOp)
23396             break;
23397
23398           Chain.push_back(V);
23399
23400           // Fallthrough!
23401         case ISD::BITCAST:
23402           V = V.getOperand(0);
23403           continue;
23404         }
23405         break;
23406       } while (V.hasOneUse());
23407       break;
23408     }
23409     // Break out of the loop if we break out of the switch.
23410     break;
23411   }
23412
23413   if (!V.hasOneUse())
23414     // We fell out of the loop without finding a viable combining instruction.
23415     return SDValue();
23416
23417   // Merge this node's mask and our incoming mask.
23418   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23419   for (int &M : Mask)
23420     M = VMask[M];
23421   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23422                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23423
23424   // Rebuild the chain around this new shuffle.
23425   while (!Chain.empty()) {
23426     SDValue W = Chain.pop_back_val();
23427
23428     if (V.getValueType() != W.getOperand(0).getValueType())
23429       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23430
23431     switch (W.getOpcode()) {
23432     default:
23433       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23434
23435     case X86ISD::UNPCKL:
23436     case X86ISD::UNPCKH:
23437       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23438       break;
23439
23440     case X86ISD::PSHUFD:
23441     case X86ISD::PSHUFLW:
23442     case X86ISD::PSHUFHW:
23443       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23444       break;
23445     }
23446   }
23447   if (V.getValueType() != N.getValueType())
23448     V = DAG.getBitcast(N.getValueType(), V);
23449
23450   // Return the new chain to replace N.
23451   return V;
23452 }
23453
23454 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23455 /// pshufhw.
23456 ///
23457 /// We walk up the chain, skipping shuffles of the other half and looking
23458 /// through shuffles which switch halves trying to find a shuffle of the same
23459 /// pair of dwords.
23460 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23461                                         SelectionDAG &DAG,
23462                                         TargetLowering::DAGCombinerInfo &DCI) {
23463   assert(
23464       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23465       "Called with something other than an x86 128-bit half shuffle!");
23466   SDLoc DL(N);
23467   unsigned CombineOpcode = N.getOpcode();
23468
23469   // Walk up a single-use chain looking for a combinable shuffle.
23470   SDValue V = N.getOperand(0);
23471   for (; V.hasOneUse(); V = V.getOperand(0)) {
23472     switch (V.getOpcode()) {
23473     default:
23474       return false; // Nothing combined!
23475
23476     case ISD::BITCAST:
23477       // Skip bitcasts as we always know the type for the target specific
23478       // instructions.
23479       continue;
23480
23481     case X86ISD::PSHUFLW:
23482     case X86ISD::PSHUFHW:
23483       if (V.getOpcode() == CombineOpcode)
23484         break;
23485
23486       // Other-half shuffles are no-ops.
23487       continue;
23488     }
23489     // Break out of the loop if we break out of the switch.
23490     break;
23491   }
23492
23493   if (!V.hasOneUse())
23494     // We fell out of the loop without finding a viable combining instruction.
23495     return false;
23496
23497   // Combine away the bottom node as its shuffle will be accumulated into
23498   // a preceding shuffle.
23499   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23500
23501   // Record the old value.
23502   SDValue Old = V;
23503
23504   // Merge this node's mask and our incoming mask (adjusted to account for all
23505   // the pshufd instructions encountered).
23506   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23507   for (int &M : Mask)
23508     M = VMask[M];
23509   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23510                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23511
23512   // Check that the shuffles didn't cancel each other out. If not, we need to
23513   // combine to the new one.
23514   if (Old != V)
23515     // Replace the combinable shuffle with the combined one, updating all users
23516     // so that we re-evaluate the chain here.
23517     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23518
23519   return true;
23520 }
23521
23522 /// \brief Try to combine x86 target specific shuffles.
23523 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23524                                            TargetLowering::DAGCombinerInfo &DCI,
23525                                            const X86Subtarget *Subtarget) {
23526   SDLoc DL(N);
23527   MVT VT = N.getSimpleValueType();
23528   SmallVector<int, 4> Mask;
23529
23530   switch (N.getOpcode()) {
23531   case X86ISD::PSHUFD:
23532   case X86ISD::PSHUFLW:
23533   case X86ISD::PSHUFHW:
23534     Mask = getPSHUFShuffleMask(N);
23535     assert(Mask.size() == 4);
23536     break;
23537   case X86ISD::UNPCKL: {
23538     // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23539     // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23540     // moves upper half elements into the lower half part. For example:
23541     //
23542     // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23543     //     undef:v16i8
23544     // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23545     //
23546     // will be combined to:
23547     //
23548     // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23549
23550     // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23551     // happen due to advanced instructions.
23552     if (!VT.is128BitVector())
23553       return SDValue();
23554
23555     auto Op0 = N.getOperand(0);
23556     auto Op1 = N.getOperand(1);
23557     if (Op0.getOpcode() == ISD::UNDEF &&
23558         Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23559       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23560
23561       unsigned NumElts = VT.getVectorNumElements();
23562       SmallVector<int, 8> ExpectedMask(NumElts, -1);
23563       std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23564                 NumElts / 2);
23565
23566       auto ShufOp = Op1.getOperand(0);
23567       if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23568         return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23569     }
23570     return SDValue();
23571   }
23572   case X86ISD::BLENDI: {
23573     SDValue V0 = N->getOperand(0);
23574     SDValue V1 = N->getOperand(1);
23575     assert(VT == V0.getSimpleValueType() && VT == V1.getSimpleValueType() &&
23576            "Unexpected input vector types");
23577
23578     // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23579     // operands and changing the mask to 1. This saves us a bunch of
23580     // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23581     // x86InstrInfo knows how to commute this back after instruction selection
23582     // if it would help register allocation.
23583
23584     // TODO: If optimizing for size or a processor that doesn't suffer from
23585     // partial register update stalls, this should be transformed into a MOVSD
23586     // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23587
23588     if (VT == MVT::v2f64)
23589       if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23590         if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23591           SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23592           return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23593         }
23594
23595     return SDValue();
23596   }
23597   default:
23598     return SDValue();
23599   }
23600
23601   // Nuke no-op shuffles that show up after combining.
23602   if (isNoopShuffleMask(Mask))
23603     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23604
23605   // Look for simplifications involving one or two shuffle instructions.
23606   SDValue V = N.getOperand(0);
23607   switch (N.getOpcode()) {
23608   default:
23609     break;
23610   case X86ISD::PSHUFLW:
23611   case X86ISD::PSHUFHW:
23612     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23613
23614     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23615       return SDValue(); // We combined away this shuffle, so we're done.
23616
23617     // See if this reduces to a PSHUFD which is no more expensive and can
23618     // combine with more operations. Note that it has to at least flip the
23619     // dwords as otherwise it would have been removed as a no-op.
23620     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23621       int DMask[] = {0, 1, 2, 3};
23622       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23623       DMask[DOffset + 0] = DOffset + 1;
23624       DMask[DOffset + 1] = DOffset + 0;
23625       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23626       V = DAG.getBitcast(DVT, V);
23627       DCI.AddToWorklist(V.getNode());
23628       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23629                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23630       DCI.AddToWorklist(V.getNode());
23631       return DAG.getBitcast(VT, V);
23632     }
23633
23634     // Look for shuffle patterns which can be implemented as a single unpack.
23635     // FIXME: This doesn't handle the location of the PSHUFD generically, and
23636     // only works when we have a PSHUFD followed by two half-shuffles.
23637     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23638         (V.getOpcode() == X86ISD::PSHUFLW ||
23639          V.getOpcode() == X86ISD::PSHUFHW) &&
23640         V.getOpcode() != N.getOpcode() &&
23641         V.hasOneUse()) {
23642       SDValue D = V.getOperand(0);
23643       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23644         D = D.getOperand(0);
23645       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23646         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23647         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23648         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23649         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23650         int WordMask[8];
23651         for (int i = 0; i < 4; ++i) {
23652           WordMask[i + NOffset] = Mask[i] + NOffset;
23653           WordMask[i + VOffset] = VMask[i] + VOffset;
23654         }
23655         // Map the word mask through the DWord mask.
23656         int MappedMask[8];
23657         for (int i = 0; i < 8; ++i)
23658           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23659         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23660             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23661           // We can replace all three shuffles with an unpack.
23662           V = DAG.getBitcast(VT, D.getOperand(0));
23663           DCI.AddToWorklist(V.getNode());
23664           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23665                                                 : X86ISD::UNPCKH,
23666                              DL, VT, V, V);
23667         }
23668       }
23669     }
23670
23671     break;
23672
23673   case X86ISD::PSHUFD:
23674     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23675       return NewN;
23676
23677     break;
23678   }
23679
23680   return SDValue();
23681 }
23682
23683 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23684 ///
23685 /// We combine this directly on the abstract vector shuffle nodes so it is
23686 /// easier to generically match. We also insert dummy vector shuffle nodes for
23687 /// the operands which explicitly discard the lanes which are unused by this
23688 /// operation to try to flow through the rest of the combiner the fact that
23689 /// they're unused.
23690 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
23691   SDLoc DL(N);
23692   EVT VT = N->getValueType(0);
23693
23694   // We only handle target-independent shuffles.
23695   // FIXME: It would be easy and harmless to use the target shuffle mask
23696   // extraction tool to support more.
23697   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23698     return SDValue();
23699
23700   auto *SVN = cast<ShuffleVectorSDNode>(N);
23701   SmallVector<int, 8> Mask;
23702   for (int M : SVN->getMask())
23703     Mask.push_back(M);
23704
23705   SDValue V1 = N->getOperand(0);
23706   SDValue V2 = N->getOperand(1);
23707
23708   // We require the first shuffle operand to be the FSUB node, and the second to
23709   // be the FADD node.
23710   if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23711     ShuffleVectorSDNode::commuteMask(Mask);
23712     std::swap(V1, V2);
23713   } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23714     return SDValue();
23715
23716   // If there are other uses of these operations we can't fold them.
23717   if (!V1->hasOneUse() || !V2->hasOneUse())
23718     return SDValue();
23719
23720   // Ensure that both operations have the same operands. Note that we can
23721   // commute the FADD operands.
23722   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23723   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23724       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23725     return SDValue();
23726
23727   // We're looking for blends between FADD and FSUB nodes. We insist on these
23728   // nodes being lined up in a specific expected pattern.
23729   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23730         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23731         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23732     return SDValue();
23733
23734   // Only specific types are legal at this point, assert so we notice if and
23735   // when these change.
23736   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
23737           VT == MVT::v4f64) &&
23738          "Unknown vector type encountered!");
23739
23740   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23741 }
23742
23743 /// PerformShuffleCombine - Performs several different shuffle combines.
23744 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23745                                      TargetLowering::DAGCombinerInfo &DCI,
23746                                      const X86Subtarget *Subtarget) {
23747   SDLoc dl(N);
23748   SDValue N0 = N->getOperand(0);
23749   SDValue N1 = N->getOperand(1);
23750   EVT VT = N->getValueType(0);
23751
23752   // Don't create instructions with illegal types after legalize types has run.
23753   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23754   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23755     return SDValue();
23756
23757   // If we have legalized the vector types, look for blends of FADD and FSUB
23758   // nodes that we can fuse into an ADDSUB node.
23759   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
23760     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
23761       return AddSub;
23762
23763   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23764   if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23765       N->getOpcode() == ISD::VECTOR_SHUFFLE)
23766     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23767
23768   // During Type Legalization, when promoting illegal vector types,
23769   // the backend might introduce new shuffle dag nodes and bitcasts.
23770   //
23771   // This code performs the following transformation:
23772   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23773   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23774   //
23775   // We do this only if both the bitcast and the BINOP dag nodes have
23776   // one use. Also, perform this transformation only if the new binary
23777   // operation is legal. This is to avoid introducing dag nodes that
23778   // potentially need to be further expanded (or custom lowered) into a
23779   // less optimal sequence of dag nodes.
23780   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23781       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23782       N0.getOpcode() == ISD::BITCAST) {
23783     SDValue BC0 = N0.getOperand(0);
23784     EVT SVT = BC0.getValueType();
23785     unsigned Opcode = BC0.getOpcode();
23786     unsigned NumElts = VT.getVectorNumElements();
23787
23788     if (BC0.hasOneUse() && SVT.isVector() &&
23789         SVT.getVectorNumElements() * 2 == NumElts &&
23790         TLI.isOperationLegal(Opcode, VT)) {
23791       bool CanFold = false;
23792       switch (Opcode) {
23793       default : break;
23794       case ISD::ADD :
23795       case ISD::FADD :
23796       case ISD::SUB :
23797       case ISD::FSUB :
23798       case ISD::MUL :
23799       case ISD::FMUL :
23800         CanFold = true;
23801       }
23802
23803       unsigned SVTNumElts = SVT.getVectorNumElements();
23804       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23805       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23806         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23807       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23808         CanFold = SVOp->getMaskElt(i) < 0;
23809
23810       if (CanFold) {
23811         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23812         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23813         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23814         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23815       }
23816     }
23817   }
23818
23819   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23820   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23821   // consecutive, non-overlapping, and in the right order.
23822   SmallVector<SDValue, 16> Elts;
23823   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23824     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23825
23826   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23827     return LD;
23828
23829   if (isTargetShuffle(N->getOpcode())) {
23830     SDValue Shuffle =
23831         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23832     if (Shuffle.getNode())
23833       return Shuffle;
23834
23835     // Try recursively combining arbitrary sequences of x86 shuffle
23836     // instructions into higher-order shuffles. We do this after combining
23837     // specific PSHUF instruction sequences into their minimal form so that we
23838     // can evaluate how many specialized shuffle instructions are involved in
23839     // a particular chain.
23840     SmallVector<int, 1> NonceMask; // Just a placeholder.
23841     NonceMask.push_back(0);
23842     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23843                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23844                                       DCI, Subtarget))
23845       return SDValue(); // This routine will use CombineTo to replace N.
23846   }
23847
23848   return SDValue();
23849 }
23850
23851 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23852 /// specific shuffle of a load can be folded into a single element load.
23853 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23854 /// shuffles have been custom lowered so we need to handle those here.
23855 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23856                                          TargetLowering::DAGCombinerInfo &DCI) {
23857   if (DCI.isBeforeLegalizeOps())
23858     return SDValue();
23859
23860   SDValue InVec = N->getOperand(0);
23861   SDValue EltNo = N->getOperand(1);
23862
23863   if (!isa<ConstantSDNode>(EltNo))
23864     return SDValue();
23865
23866   EVT OriginalVT = InVec.getValueType();
23867
23868   if (InVec.getOpcode() == ISD::BITCAST) {
23869     // Don't duplicate a load with other uses.
23870     if (!InVec.hasOneUse())
23871       return SDValue();
23872     EVT BCVT = InVec.getOperand(0).getValueType();
23873     if (!BCVT.isVector() ||
23874         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23875       return SDValue();
23876     InVec = InVec.getOperand(0);
23877   }
23878
23879   EVT CurrentVT = InVec.getValueType();
23880
23881   if (!isTargetShuffle(InVec.getOpcode()))
23882     return SDValue();
23883
23884   // Don't duplicate a load with other uses.
23885   if (!InVec.hasOneUse())
23886     return SDValue();
23887
23888   SmallVector<int, 16> ShuffleMask;
23889   bool UnaryShuffle;
23890   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23891                             ShuffleMask, UnaryShuffle))
23892     return SDValue();
23893
23894   // Select the input vector, guarding against out of range extract vector.
23895   unsigned NumElems = CurrentVT.getVectorNumElements();
23896   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23897   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23898   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23899                                          : InVec.getOperand(1);
23900
23901   // If inputs to shuffle are the same for both ops, then allow 2 uses
23902   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23903                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23904
23905   if (LdNode.getOpcode() == ISD::BITCAST) {
23906     // Don't duplicate a load with other uses.
23907     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23908       return SDValue();
23909
23910     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23911     LdNode = LdNode.getOperand(0);
23912   }
23913
23914   if (!ISD::isNormalLoad(LdNode.getNode()))
23915     return SDValue();
23916
23917   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23918
23919   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23920     return SDValue();
23921
23922   EVT EltVT = N->getValueType(0);
23923   // If there's a bitcast before the shuffle, check if the load type and
23924   // alignment is valid.
23925   unsigned Align = LN0->getAlignment();
23926   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23927   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23928       EltVT.getTypeForEVT(*DAG.getContext()));
23929
23930   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23931     return SDValue();
23932
23933   // All checks match so transform back to vector_shuffle so that DAG combiner
23934   // can finish the job
23935   SDLoc dl(N);
23936
23937   // Create shuffle node taking into account the case that its a unary shuffle
23938   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23939                                    : InVec.getOperand(1);
23940   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23941                                  InVec.getOperand(0), Shuffle,
23942                                  &ShuffleMask[0]);
23943   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23944   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23945                      EltNo);
23946 }
23947
23948 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
23949                                      const X86Subtarget *Subtarget) {
23950   SDValue N0 = N->getOperand(0);
23951   EVT VT = N->getValueType(0);
23952
23953   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23954   // special and don't usually play with other vector types, it's better to
23955   // handle them early to be sure we emit efficient code by avoiding
23956   // store-load conversions.
23957   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
23958       N0.getValueType() == MVT::v2i32 &&
23959       isNullConstant(N0.getOperand(1))) {
23960     SDValue N00 = N0->getOperand(0);
23961     if (N00.getValueType() == MVT::i32)
23962       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
23963   }
23964
23965   // Convert a bitcasted integer logic operation that has one bitcasted
23966   // floating-point operand and one constant operand into a floating-point
23967   // logic operation. This may create a load of the constant, but that is
23968   // cheaper than materializing the constant in an integer register and
23969   // transferring it to an SSE register or transferring the SSE operand to
23970   // integer register and back.
23971   unsigned FPOpcode;
23972   switch (N0.getOpcode()) {
23973     case ISD::AND: FPOpcode = X86ISD::FAND; break;
23974     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
23975     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
23976     default: return SDValue();
23977   }
23978   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
23979        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
23980       isa<ConstantSDNode>(N0.getOperand(1)) &&
23981       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
23982       N0.getOperand(0).getOperand(0).getValueType() == VT) {
23983     SDValue N000 = N0.getOperand(0).getOperand(0);
23984     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
23985     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
23986   }
23987
23988   return SDValue();
23989 }
23990
23991 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23992 /// generation and convert it from being a bunch of shuffles and extracts
23993 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23994 /// storing the value and loading scalars back, while for x64 we should
23995 /// use 64-bit extracts and shifts.
23996 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23997                                          TargetLowering::DAGCombinerInfo &DCI) {
23998   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23999     return NewOp;
24000
24001   SDValue InputVector = N->getOperand(0);
24002   SDLoc dl(InputVector);
24003   // Detect mmx to i32 conversion through a v2i32 elt extract.
24004   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
24005       N->getValueType(0) == MVT::i32 &&
24006       InputVector.getValueType() == MVT::v2i32) {
24007
24008     // The bitcast source is a direct mmx result.
24009     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
24010     if (MMXSrc.getValueType() == MVT::x86mmx)
24011       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24012                          N->getValueType(0),
24013                          InputVector.getNode()->getOperand(0));
24014
24015     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
24016     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
24017         MMXSrc.getValueType() == MVT::i64) {
24018       SDValue MMXSrcOp = MMXSrc.getOperand(0);
24019       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
24020           MMXSrcOp.getValueType() == MVT::v1i64 &&
24021           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
24022         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24023                            N->getValueType(0), MMXSrcOp.getOperand(0));
24024     }
24025   }
24026
24027   EVT VT = N->getValueType(0);
24028
24029   if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
24030       InputVector.getOpcode() == ISD::BITCAST &&
24031       isa<ConstantSDNode>(InputVector.getOperand(0))) {
24032     uint64_t ExtractedElt =
24033         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
24034     uint64_t InputValue =
24035         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
24036     uint64_t Res = (InputValue >> ExtractedElt) & 1;
24037     return DAG.getConstant(Res, dl, MVT::i1);
24038   }
24039   // Only operate on vectors of 4 elements, where the alternative shuffling
24040   // gets to be more expensive.
24041   if (InputVector.getValueType() != MVT::v4i32)
24042     return SDValue();
24043
24044   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
24045   // single use which is a sign-extend or zero-extend, and all elements are
24046   // used.
24047   SmallVector<SDNode *, 4> Uses;
24048   unsigned ExtractedElements = 0;
24049   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
24050        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
24051     if (UI.getUse().getResNo() != InputVector.getResNo())
24052       return SDValue();
24053
24054     SDNode *Extract = *UI;
24055     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
24056       return SDValue();
24057
24058     if (Extract->getValueType(0) != MVT::i32)
24059       return SDValue();
24060     if (!Extract->hasOneUse())
24061       return SDValue();
24062     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
24063         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
24064       return SDValue();
24065     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
24066       return SDValue();
24067
24068     // Record which element was extracted.
24069     ExtractedElements |=
24070       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
24071
24072     Uses.push_back(Extract);
24073   }
24074
24075   // If not all the elements were used, this may not be worthwhile.
24076   if (ExtractedElements != 15)
24077     return SDValue();
24078
24079   // Ok, we've now decided to do the transformation.
24080   // If 64-bit shifts are legal, use the extract-shift sequence,
24081   // otherwise bounce the vector off the cache.
24082   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24083   SDValue Vals[4];
24084
24085   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
24086     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
24087     auto &DL = DAG.getDataLayout();
24088     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
24089     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24090       DAG.getConstant(0, dl, VecIdxTy));
24091     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24092       DAG.getConstant(1, dl, VecIdxTy));
24093
24094     SDValue ShAmt = DAG.getConstant(
24095         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
24096     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
24097     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24098       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
24099     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
24100     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24101       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
24102   } else {
24103     // Store the value to a temporary stack slot.
24104     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
24105     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
24106       MachinePointerInfo(), false, false, 0);
24107
24108     EVT ElementType = InputVector.getValueType().getVectorElementType();
24109     unsigned EltSize = ElementType.getSizeInBits() / 8;
24110
24111     // Replace each use (extract) with a load of the appropriate element.
24112     for (unsigned i = 0; i < 4; ++i) {
24113       uint64_t Offset = EltSize * i;
24114       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24115       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
24116
24117       SDValue ScalarAddr =
24118           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
24119
24120       // Load the scalar.
24121       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
24122                             ScalarAddr, MachinePointerInfo(),
24123                             false, false, false, 0);
24124
24125     }
24126   }
24127
24128   // Replace the extracts
24129   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
24130     UE = Uses.end(); UI != UE; ++UI) {
24131     SDNode *Extract = *UI;
24132
24133     SDValue Idx = Extract->getOperand(1);
24134     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
24135     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
24136   }
24137
24138   // The replacement was made in place; don't return anything.
24139   return SDValue();
24140 }
24141
24142 static SDValue
24143 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
24144                                       const X86Subtarget *Subtarget) {
24145   SDLoc dl(N);
24146   SDValue Cond = N->getOperand(0);
24147   SDValue LHS = N->getOperand(1);
24148   SDValue RHS = N->getOperand(2);
24149
24150   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
24151     SDValue CondSrc = Cond->getOperand(0);
24152     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
24153       Cond = CondSrc->getOperand(0);
24154   }
24155
24156   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
24157     return SDValue();
24158
24159   // A vselect where all conditions and data are constants can be optimized into
24160   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
24161   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
24162       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
24163     return SDValue();
24164
24165   unsigned MaskValue = 0;
24166   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
24167     return SDValue();
24168
24169   MVT VT = N->getSimpleValueType(0);
24170   unsigned NumElems = VT.getVectorNumElements();
24171   SmallVector<int, 8> ShuffleMask(NumElems, -1);
24172   for (unsigned i = 0; i < NumElems; ++i) {
24173     // Be sure we emit undef where we can.
24174     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
24175       ShuffleMask[i] = -1;
24176     else
24177       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
24178   }
24179
24180   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24181   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
24182     return SDValue();
24183   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
24184 }
24185
24186 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
24187 /// nodes.
24188 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
24189                                     TargetLowering::DAGCombinerInfo &DCI,
24190                                     const X86Subtarget *Subtarget) {
24191   SDLoc DL(N);
24192   SDValue Cond = N->getOperand(0);
24193   // Get the LHS/RHS of the select.
24194   SDValue LHS = N->getOperand(1);
24195   SDValue RHS = N->getOperand(2);
24196   EVT VT = LHS.getValueType();
24197   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24198
24199   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
24200   // instructions match the semantics of the common C idiom x<y?x:y but not
24201   // x<=y?x:y, because of how they handle negative zero (which can be
24202   // ignored in unsafe-math mode).
24203   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
24204   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
24205       VT != MVT::f80 && VT != MVT::f128 &&
24206       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
24207       (Subtarget->hasSSE2() ||
24208        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
24209     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24210
24211     unsigned Opcode = 0;
24212     // Check for x CC y ? x : y.
24213     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24214         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24215       switch (CC) {
24216       default: break;
24217       case ISD::SETULT:
24218         // Converting this to a min would handle NaNs incorrectly, and swapping
24219         // the operands would cause it to handle comparisons between positive
24220         // and negative zero incorrectly.
24221         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24222           if (!DAG.getTarget().Options.UnsafeFPMath &&
24223               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24224             break;
24225           std::swap(LHS, RHS);
24226         }
24227         Opcode = X86ISD::FMIN;
24228         break;
24229       case ISD::SETOLE:
24230         // Converting this to a min would handle comparisons between positive
24231         // and negative zero incorrectly.
24232         if (!DAG.getTarget().Options.UnsafeFPMath &&
24233             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24234           break;
24235         Opcode = X86ISD::FMIN;
24236         break;
24237       case ISD::SETULE:
24238         // Converting this to a min would handle both negative zeros and NaNs
24239         // incorrectly, but we can swap the operands to fix both.
24240         std::swap(LHS, RHS);
24241       case ISD::SETOLT:
24242       case ISD::SETLT:
24243       case ISD::SETLE:
24244         Opcode = X86ISD::FMIN;
24245         break;
24246
24247       case ISD::SETOGE:
24248         // Converting this to a max would handle comparisons between positive
24249         // and negative zero incorrectly.
24250         if (!DAG.getTarget().Options.UnsafeFPMath &&
24251             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24252           break;
24253         Opcode = X86ISD::FMAX;
24254         break;
24255       case ISD::SETUGT:
24256         // Converting this to a max would handle NaNs incorrectly, and swapping
24257         // the operands would cause it to handle comparisons between positive
24258         // and negative zero incorrectly.
24259         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24260           if (!DAG.getTarget().Options.UnsafeFPMath &&
24261               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24262             break;
24263           std::swap(LHS, RHS);
24264         }
24265         Opcode = X86ISD::FMAX;
24266         break;
24267       case ISD::SETUGE:
24268         // Converting this to a max would handle both negative zeros and NaNs
24269         // incorrectly, but we can swap the operands to fix both.
24270         std::swap(LHS, RHS);
24271       case ISD::SETOGT:
24272       case ISD::SETGT:
24273       case ISD::SETGE:
24274         Opcode = X86ISD::FMAX;
24275         break;
24276       }
24277     // Check for x CC y ? y : x -- a min/max with reversed arms.
24278     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
24279                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
24280       switch (CC) {
24281       default: break;
24282       case ISD::SETOGE:
24283         // Converting this to a min would handle comparisons between positive
24284         // and negative zero incorrectly, and swapping the operands would
24285         // cause it to handle NaNs incorrectly.
24286         if (!DAG.getTarget().Options.UnsafeFPMath &&
24287             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
24288           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24289             break;
24290           std::swap(LHS, RHS);
24291         }
24292         Opcode = X86ISD::FMIN;
24293         break;
24294       case ISD::SETUGT:
24295         // Converting this to a min would handle NaNs incorrectly.
24296         if (!DAG.getTarget().Options.UnsafeFPMath &&
24297             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
24298           break;
24299         Opcode = X86ISD::FMIN;
24300         break;
24301       case ISD::SETUGE:
24302         // Converting this to a min would handle both negative zeros and NaNs
24303         // incorrectly, but we can swap the operands to fix both.
24304         std::swap(LHS, RHS);
24305       case ISD::SETOGT:
24306       case ISD::SETGT:
24307       case ISD::SETGE:
24308         Opcode = X86ISD::FMIN;
24309         break;
24310
24311       case ISD::SETULT:
24312         // Converting this to a max would handle NaNs incorrectly.
24313         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24314           break;
24315         Opcode = X86ISD::FMAX;
24316         break;
24317       case ISD::SETOLE:
24318         // Converting this to a max would handle comparisons between positive
24319         // and negative zero incorrectly, and swapping the operands would
24320         // cause it to handle NaNs incorrectly.
24321         if (!DAG.getTarget().Options.UnsafeFPMath &&
24322             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
24323           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24324             break;
24325           std::swap(LHS, RHS);
24326         }
24327         Opcode = X86ISD::FMAX;
24328         break;
24329       case ISD::SETULE:
24330         // Converting this to a max would handle both negative zeros and NaNs
24331         // incorrectly, but we can swap the operands to fix both.
24332         std::swap(LHS, RHS);
24333       case ISD::SETOLT:
24334       case ISD::SETLT:
24335       case ISD::SETLE:
24336         Opcode = X86ISD::FMAX;
24337         break;
24338       }
24339     }
24340
24341     if (Opcode)
24342       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
24343   }
24344
24345   EVT CondVT = Cond.getValueType();
24346   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
24347       CondVT.getVectorElementType() == MVT::i1) {
24348     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
24349     // lowering on KNL. In this case we convert it to
24350     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24351     // The same situation for all 128 and 256-bit vectors of i8 and i16.
24352     // Since SKX these selects have a proper lowering.
24353     EVT OpVT = LHS.getValueType();
24354     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24355         (OpVT.getVectorElementType() == MVT::i8 ||
24356          OpVT.getVectorElementType() == MVT::i16) &&
24357         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24358       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24359       DCI.AddToWorklist(Cond.getNode());
24360       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24361     }
24362   }
24363   // If this is a select between two integer constants, try to do some
24364   // optimizations.
24365   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24366     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24367       // Don't do this for crazy integer types.
24368       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24369         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24370         // so that TrueC (the true value) is larger than FalseC.
24371         bool NeedsCondInvert = false;
24372
24373         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24374             // Efficiently invertible.
24375             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
24376              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
24377               isa<ConstantSDNode>(Cond.getOperand(1))))) {
24378           NeedsCondInvert = true;
24379           std::swap(TrueC, FalseC);
24380         }
24381
24382         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
24383         if (FalseC->getAPIntValue() == 0 &&
24384             TrueC->getAPIntValue().isPowerOf2()) {
24385           if (NeedsCondInvert) // Invert the condition if needed.
24386             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24387                                DAG.getConstant(1, DL, Cond.getValueType()));
24388
24389           // Zero extend the condition if needed.
24390           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
24391
24392           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24393           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24394                              DAG.getConstant(ShAmt, DL, MVT::i8));
24395         }
24396
24397         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24398         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24399           if (NeedsCondInvert) // Invert the condition if needed.
24400             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24401                                DAG.getConstant(1, DL, Cond.getValueType()));
24402
24403           // Zero extend the condition if needed.
24404           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24405                              FalseC->getValueType(0), Cond);
24406           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24407                              SDValue(FalseC, 0));
24408         }
24409
24410         // Optimize cases that will turn into an LEA instruction.  This requires
24411         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24412         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24413           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24414           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24415
24416           bool isFastMultiplier = false;
24417           if (Diff < 10) {
24418             switch ((unsigned char)Diff) {
24419               default: break;
24420               case 1:  // result = add base, cond
24421               case 2:  // result = lea base(    , cond*2)
24422               case 3:  // result = lea base(cond, cond*2)
24423               case 4:  // result = lea base(    , cond*4)
24424               case 5:  // result = lea base(cond, cond*4)
24425               case 8:  // result = lea base(    , cond*8)
24426               case 9:  // result = lea base(cond, cond*8)
24427                 isFastMultiplier = true;
24428                 break;
24429             }
24430           }
24431
24432           if (isFastMultiplier) {
24433             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24434             if (NeedsCondInvert) // Invert the condition if needed.
24435               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24436                                  DAG.getConstant(1, DL, Cond.getValueType()));
24437
24438             // Zero extend the condition if needed.
24439             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24440                                Cond);
24441             // Scale the condition by the difference.
24442             if (Diff != 1)
24443               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24444                                  DAG.getConstant(Diff, DL,
24445                                                  Cond.getValueType()));
24446
24447             // Add the base if non-zero.
24448             if (FalseC->getAPIntValue() != 0)
24449               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24450                                  SDValue(FalseC, 0));
24451             return Cond;
24452           }
24453         }
24454       }
24455   }
24456
24457   // Canonicalize max and min:
24458   // (x > y) ? x : y -> (x >= y) ? x : y
24459   // (x < y) ? x : y -> (x <= y) ? x : y
24460   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24461   // the need for an extra compare
24462   // against zero. e.g.
24463   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24464   // subl   %esi, %edi
24465   // testl  %edi, %edi
24466   // movl   $0, %eax
24467   // cmovgl %edi, %eax
24468   // =>
24469   // xorl   %eax, %eax
24470   // subl   %esi, $edi
24471   // cmovsl %eax, %edi
24472   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24473       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24474       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24475     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24476     switch (CC) {
24477     default: break;
24478     case ISD::SETLT:
24479     case ISD::SETGT: {
24480       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24481       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24482                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
24483       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24484     }
24485     }
24486   }
24487
24488   // Early exit check
24489   if (!TLI.isTypeLegal(VT))
24490     return SDValue();
24491
24492   // Match VSELECTs into subs with unsigned saturation.
24493   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24494       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24495       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24496        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24497     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24498
24499     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24500     // left side invert the predicate to simplify logic below.
24501     SDValue Other;
24502     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24503       Other = RHS;
24504       CC = ISD::getSetCCInverse(CC, true);
24505     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24506       Other = LHS;
24507     }
24508
24509     if (Other.getNode() && Other->getNumOperands() == 2 &&
24510         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24511       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24512       SDValue CondRHS = Cond->getOperand(1);
24513
24514       // Look for a general sub with unsigned saturation first.
24515       // x >= y ? x-y : 0 --> subus x, y
24516       // x >  y ? x-y : 0 --> subus x, y
24517       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24518           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24519         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24520
24521       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24522         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24523           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24524             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24525               // If the RHS is a constant we have to reverse the const
24526               // canonicalization.
24527               // x > C-1 ? x+-C : 0 --> subus x, C
24528               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24529                   CondRHSConst->getAPIntValue() ==
24530                       (-OpRHSConst->getAPIntValue() - 1))
24531                 return DAG.getNode(
24532                     X86ISD::SUBUS, DL, VT, OpLHS,
24533                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24534
24535           // Another special case: If C was a sign bit, the sub has been
24536           // canonicalized into a xor.
24537           // FIXME: Would it be better to use computeKnownBits to determine
24538           //        whether it's safe to decanonicalize the xor?
24539           // x s< 0 ? x^C : 0 --> subus x, C
24540           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24541               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24542               OpRHSConst->getAPIntValue().isSignBit())
24543             // Note that we have to rebuild the RHS constant here to ensure we
24544             // don't rely on particular values of undef lanes.
24545             return DAG.getNode(
24546                 X86ISD::SUBUS, DL, VT, OpLHS,
24547                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24548         }
24549     }
24550   }
24551
24552   // Simplify vector selection if condition value type matches vselect
24553   // operand type
24554   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24555     assert(Cond.getValueType().isVector() &&
24556            "vector select expects a vector selector!");
24557
24558     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24559     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24560
24561     // Try invert the condition if true value is not all 1s and false value
24562     // is not all 0s.
24563     if (!TValIsAllOnes && !FValIsAllZeros &&
24564         // Check if the selector will be produced by CMPP*/PCMP*
24565         Cond.getOpcode() == ISD::SETCC &&
24566         // Check if SETCC has already been promoted
24567         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24568             CondVT) {
24569       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24570       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24571
24572       if (TValIsAllZeros || FValIsAllOnes) {
24573         SDValue CC = Cond.getOperand(2);
24574         ISD::CondCode NewCC =
24575           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24576                                Cond.getOperand(0).getValueType().isInteger());
24577         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24578         std::swap(LHS, RHS);
24579         TValIsAllOnes = FValIsAllOnes;
24580         FValIsAllZeros = TValIsAllZeros;
24581       }
24582     }
24583
24584     if (TValIsAllOnes || FValIsAllZeros) {
24585       SDValue Ret;
24586
24587       if (TValIsAllOnes && FValIsAllZeros)
24588         Ret = Cond;
24589       else if (TValIsAllOnes)
24590         Ret =
24591             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24592       else if (FValIsAllZeros)
24593         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24594                           DAG.getBitcast(CondVT, LHS));
24595
24596       return DAG.getBitcast(VT, Ret);
24597     }
24598   }
24599
24600   // We should generate an X86ISD::BLENDI from a vselect if its argument
24601   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24602   // constants. This specific pattern gets generated when we split a
24603   // selector for a 512 bit vector in a machine without AVX512 (but with
24604   // 256-bit vectors), during legalization:
24605   //
24606   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24607   //
24608   // Iff we find this pattern and the build_vectors are built from
24609   // constants, we translate the vselect into a shuffle_vector that we
24610   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24611   if ((N->getOpcode() == ISD::VSELECT ||
24612        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24613       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24614     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24615     if (Shuffle.getNode())
24616       return Shuffle;
24617   }
24618
24619   // If this is a *dynamic* select (non-constant condition) and we can match
24620   // this node with one of the variable blend instructions, restructure the
24621   // condition so that the blends can use the high bit of each element and use
24622   // SimplifyDemandedBits to simplify the condition operand.
24623   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24624       !DCI.isBeforeLegalize() &&
24625       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24626     unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24627
24628     // Don't optimize vector selects that map to mask-registers.
24629     if (BitWidth == 1)
24630       return SDValue();
24631
24632     // We can only handle the cases where VSELECT is directly legal on the
24633     // subtarget. We custom lower VSELECT nodes with constant conditions and
24634     // this makes it hard to see whether a dynamic VSELECT will correctly
24635     // lower, so we both check the operation's status and explicitly handle the
24636     // cases where a *dynamic* blend will fail even though a constant-condition
24637     // blend could be custom lowered.
24638     // FIXME: We should find a better way to handle this class of problems.
24639     // Potentially, we should combine constant-condition vselect nodes
24640     // pre-legalization into shuffles and not mark as many types as custom
24641     // lowered.
24642     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24643       return SDValue();
24644     // FIXME: We don't support i16-element blends currently. We could and
24645     // should support them by making *all* the bits in the condition be set
24646     // rather than just the high bit and using an i8-element blend.
24647     if (VT.getVectorElementType() == MVT::i16)
24648       return SDValue();
24649     // Dynamic blending was only available from SSE4.1 onward.
24650     if (VT.is128BitVector() && !Subtarget->hasSSE41())
24651       return SDValue();
24652     // Byte blends are only available in AVX2
24653     if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24654       return SDValue();
24655
24656     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24657     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24658
24659     APInt KnownZero, KnownOne;
24660     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24661                                           DCI.isBeforeLegalizeOps());
24662     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24663         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24664                                  TLO)) {
24665       // If we changed the computation somewhere in the DAG, this change
24666       // will affect all users of Cond.
24667       // Make sure it is fine and update all the nodes so that we do not
24668       // use the generic VSELECT anymore. Otherwise, we may perform
24669       // wrong optimizations as we messed up with the actual expectation
24670       // for the vector boolean values.
24671       if (Cond != TLO.Old) {
24672         // Check all uses of that condition operand to check whether it will be
24673         // consumed by non-BLEND instructions, which may depend on all bits are
24674         // set properly.
24675         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24676              I != E; ++I)
24677           if (I->getOpcode() != ISD::VSELECT)
24678             // TODO: Add other opcodes eventually lowered into BLEND.
24679             return SDValue();
24680
24681         // Update all the users of the condition, before committing the change,
24682         // so that the VSELECT optimizations that expect the correct vector
24683         // boolean value will not be triggered.
24684         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24685              I != E; ++I)
24686           DAG.ReplaceAllUsesOfValueWith(
24687               SDValue(*I, 0),
24688               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24689                           Cond, I->getOperand(1), I->getOperand(2)));
24690         DCI.CommitTargetLoweringOpt(TLO);
24691         return SDValue();
24692       }
24693       // At this point, only Cond is changed. Change the condition
24694       // just for N to keep the opportunity to optimize all other
24695       // users their own way.
24696       DAG.ReplaceAllUsesOfValueWith(
24697           SDValue(N, 0),
24698           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24699                       TLO.New, N->getOperand(1), N->getOperand(2)));
24700       return SDValue();
24701     }
24702   }
24703
24704   return SDValue();
24705 }
24706
24707 // Check whether a boolean test is testing a boolean value generated by
24708 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24709 // code.
24710 //
24711 // Simplify the following patterns:
24712 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24713 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24714 // to (Op EFLAGS Cond)
24715 //
24716 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24717 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24718 // to (Op EFLAGS !Cond)
24719 //
24720 // where Op could be BRCOND or CMOV.
24721 //
24722 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24723   // Quit if not CMP and SUB with its value result used.
24724   if (Cmp.getOpcode() != X86ISD::CMP &&
24725       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24726       return SDValue();
24727
24728   // Quit if not used as a boolean value.
24729   if (CC != X86::COND_E && CC != X86::COND_NE)
24730     return SDValue();
24731
24732   // Check CMP operands. One of them should be 0 or 1 and the other should be
24733   // an SetCC or extended from it.
24734   SDValue Op1 = Cmp.getOperand(0);
24735   SDValue Op2 = Cmp.getOperand(1);
24736
24737   SDValue SetCC;
24738   const ConstantSDNode* C = nullptr;
24739   bool needOppositeCond = (CC == X86::COND_E);
24740   bool checkAgainstTrue = false; // Is it a comparison against 1?
24741
24742   if ((C = dyn_cast<ConstantSDNode>(Op1)))
24743     SetCC = Op2;
24744   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24745     SetCC = Op1;
24746   else // Quit if all operands are not constants.
24747     return SDValue();
24748
24749   if (C->getZExtValue() == 1) {
24750     needOppositeCond = !needOppositeCond;
24751     checkAgainstTrue = true;
24752   } else if (C->getZExtValue() != 0)
24753     // Quit if the constant is neither 0 or 1.
24754     return SDValue();
24755
24756   bool truncatedToBoolWithAnd = false;
24757   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24758   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24759          SetCC.getOpcode() == ISD::TRUNCATE ||
24760          SetCC.getOpcode() == ISD::AND) {
24761     if (SetCC.getOpcode() == ISD::AND) {
24762       int OpIdx = -1;
24763       if (isOneConstant(SetCC.getOperand(0)))
24764         OpIdx = 1;
24765       if (isOneConstant(SetCC.getOperand(1)))
24766         OpIdx = 0;
24767       if (OpIdx == -1)
24768         break;
24769       SetCC = SetCC.getOperand(OpIdx);
24770       truncatedToBoolWithAnd = true;
24771     } else
24772       SetCC = SetCC.getOperand(0);
24773   }
24774
24775   switch (SetCC.getOpcode()) {
24776   case X86ISD::SETCC_CARRY:
24777     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24778     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24779     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24780     // truncated to i1 using 'and'.
24781     if (checkAgainstTrue && !truncatedToBoolWithAnd)
24782       break;
24783     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24784            "Invalid use of SETCC_CARRY!");
24785     // FALL THROUGH
24786   case X86ISD::SETCC:
24787     // Set the condition code or opposite one if necessary.
24788     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24789     if (needOppositeCond)
24790       CC = X86::GetOppositeBranchCondition(CC);
24791     return SetCC.getOperand(1);
24792   case X86ISD::CMOV: {
24793     // Check whether false/true value has canonical one, i.e. 0 or 1.
24794     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24795     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24796     // Quit if true value is not a constant.
24797     if (!TVal)
24798       return SDValue();
24799     // Quit if false value is not a constant.
24800     if (!FVal) {
24801       SDValue Op = SetCC.getOperand(0);
24802       // Skip 'zext' or 'trunc' node.
24803       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24804           Op.getOpcode() == ISD::TRUNCATE)
24805         Op = Op.getOperand(0);
24806       // A special case for rdrand/rdseed, where 0 is set if false cond is
24807       // found.
24808       if ((Op.getOpcode() != X86ISD::RDRAND &&
24809            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24810         return SDValue();
24811     }
24812     // Quit if false value is not the constant 0 or 1.
24813     bool FValIsFalse = true;
24814     if (FVal && FVal->getZExtValue() != 0) {
24815       if (FVal->getZExtValue() != 1)
24816         return SDValue();
24817       // If FVal is 1, opposite cond is needed.
24818       needOppositeCond = !needOppositeCond;
24819       FValIsFalse = false;
24820     }
24821     // Quit if TVal is not the constant opposite of FVal.
24822     if (FValIsFalse && TVal->getZExtValue() != 1)
24823       return SDValue();
24824     if (!FValIsFalse && TVal->getZExtValue() != 0)
24825       return SDValue();
24826     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24827     if (needOppositeCond)
24828       CC = X86::GetOppositeBranchCondition(CC);
24829     return SetCC.getOperand(3);
24830   }
24831   }
24832
24833   return SDValue();
24834 }
24835
24836 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24837 /// Match:
24838 ///   (X86or (X86setcc) (X86setcc))
24839 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24840 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24841                                            X86::CondCode &CC1, SDValue &Flags,
24842                                            bool &isAnd) {
24843   if (Cond->getOpcode() == X86ISD::CMP) {
24844     if (!isNullConstant(Cond->getOperand(1)))
24845       return false;
24846
24847     Cond = Cond->getOperand(0);
24848   }
24849
24850   isAnd = false;
24851
24852   SDValue SetCC0, SetCC1;
24853   switch (Cond->getOpcode()) {
24854   default: return false;
24855   case ISD::AND:
24856   case X86ISD::AND:
24857     isAnd = true;
24858     // fallthru
24859   case ISD::OR:
24860   case X86ISD::OR:
24861     SetCC0 = Cond->getOperand(0);
24862     SetCC1 = Cond->getOperand(1);
24863     break;
24864   };
24865
24866   // Make sure we have SETCC nodes, using the same flags value.
24867   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24868       SetCC1.getOpcode() != X86ISD::SETCC ||
24869       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24870     return false;
24871
24872   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24873   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24874   Flags = SetCC0->getOperand(1);
24875   return true;
24876 }
24877
24878 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24879 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24880                                   TargetLowering::DAGCombinerInfo &DCI,
24881                                   const X86Subtarget *Subtarget) {
24882   SDLoc DL(N);
24883
24884   // If the flag operand isn't dead, don't touch this CMOV.
24885   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24886     return SDValue();
24887
24888   SDValue FalseOp = N->getOperand(0);
24889   SDValue TrueOp = N->getOperand(1);
24890   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24891   SDValue Cond = N->getOperand(3);
24892
24893   if (CC == X86::COND_E || CC == X86::COND_NE) {
24894     switch (Cond.getOpcode()) {
24895     default: break;
24896     case X86ISD::BSR:
24897     case X86ISD::BSF:
24898       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24899       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24900         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24901     }
24902   }
24903
24904   SDValue Flags;
24905
24906   Flags = checkBoolTestSetCCCombine(Cond, CC);
24907   if (Flags.getNode() &&
24908       // Extra check as FCMOV only supports a subset of X86 cond.
24909       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24910     SDValue Ops[] = { FalseOp, TrueOp,
24911                       DAG.getConstant(CC, DL, MVT::i8), Flags };
24912     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24913   }
24914
24915   // If this is a select between two integer constants, try to do some
24916   // optimizations.  Note that the operands are ordered the opposite of SELECT
24917   // operands.
24918   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24919     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24920       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24921       // larger than FalseC (the false value).
24922       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24923         CC = X86::GetOppositeBranchCondition(CC);
24924         std::swap(TrueC, FalseC);
24925         std::swap(TrueOp, FalseOp);
24926       }
24927
24928       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24929       // This is efficient for any integer data type (including i8/i16) and
24930       // shift amount.
24931       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24932         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24933                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24934
24935         // Zero extend the condition if needed.
24936         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24937
24938         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24939         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24940                            DAG.getConstant(ShAmt, DL, MVT::i8));
24941         if (N->getNumValues() == 2)  // Dead flag value?
24942           return DCI.CombineTo(N, Cond, SDValue());
24943         return Cond;
24944       }
24945
24946       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
24947       // for any integer data type, including i8/i16.
24948       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24949         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24950                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24951
24952         // Zero extend the condition if needed.
24953         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24954                            FalseC->getValueType(0), Cond);
24955         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24956                            SDValue(FalseC, 0));
24957
24958         if (N->getNumValues() == 2)  // Dead flag value?
24959           return DCI.CombineTo(N, Cond, SDValue());
24960         return Cond;
24961       }
24962
24963       // Optimize cases that will turn into an LEA instruction.  This requires
24964       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24965       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24966         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24967         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24968
24969         bool isFastMultiplier = false;
24970         if (Diff < 10) {
24971           switch ((unsigned char)Diff) {
24972           default: break;
24973           case 1:  // result = add base, cond
24974           case 2:  // result = lea base(    , cond*2)
24975           case 3:  // result = lea base(cond, cond*2)
24976           case 4:  // result = lea base(    , cond*4)
24977           case 5:  // result = lea base(cond, cond*4)
24978           case 8:  // result = lea base(    , cond*8)
24979           case 9:  // result = lea base(cond, cond*8)
24980             isFastMultiplier = true;
24981             break;
24982           }
24983         }
24984
24985         if (isFastMultiplier) {
24986           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24987           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24988                              DAG.getConstant(CC, DL, MVT::i8), Cond);
24989           // Zero extend the condition if needed.
24990           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24991                              Cond);
24992           // Scale the condition by the difference.
24993           if (Diff != 1)
24994             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24995                                DAG.getConstant(Diff, DL, Cond.getValueType()));
24996
24997           // Add the base if non-zero.
24998           if (FalseC->getAPIntValue() != 0)
24999             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25000                                SDValue(FalseC, 0));
25001           if (N->getNumValues() == 2)  // Dead flag value?
25002             return DCI.CombineTo(N, Cond, SDValue());
25003           return Cond;
25004         }
25005       }
25006     }
25007   }
25008
25009   // Handle these cases:
25010   //   (select (x != c), e, c) -> select (x != c), e, x),
25011   //   (select (x == c), c, e) -> select (x == c), x, e)
25012   // where the c is an integer constant, and the "select" is the combination
25013   // of CMOV and CMP.
25014   //
25015   // The rationale for this change is that the conditional-move from a constant
25016   // needs two instructions, however, conditional-move from a register needs
25017   // only one instruction.
25018   //
25019   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
25020   //  some instruction-combining opportunities. This opt needs to be
25021   //  postponed as late as possible.
25022   //
25023   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
25024     // the DCI.xxxx conditions are provided to postpone the optimization as
25025     // late as possible.
25026
25027     ConstantSDNode *CmpAgainst = nullptr;
25028     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
25029         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
25030         !isa<ConstantSDNode>(Cond.getOperand(0))) {
25031
25032       if (CC == X86::COND_NE &&
25033           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
25034         CC = X86::GetOppositeBranchCondition(CC);
25035         std::swap(TrueOp, FalseOp);
25036       }
25037
25038       if (CC == X86::COND_E &&
25039           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
25040         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
25041                           DAG.getConstant(CC, DL, MVT::i8), Cond };
25042         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
25043       }
25044     }
25045   }
25046
25047   // Fold and/or of setcc's to double CMOV:
25048   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
25049   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
25050   //
25051   // This combine lets us generate:
25052   //   cmovcc1 (jcc1 if we don't have CMOV)
25053   //   cmovcc2 (same)
25054   // instead of:
25055   //   setcc1
25056   //   setcc2
25057   //   and/or
25058   //   cmovne (jne if we don't have CMOV)
25059   // When we can't use the CMOV instruction, it might increase branch
25060   // mispredicts.
25061   // When we can use CMOV, or when there is no mispredict, this improves
25062   // throughput and reduces register pressure.
25063   //
25064   if (CC == X86::COND_NE) {
25065     SDValue Flags;
25066     X86::CondCode CC0, CC1;
25067     bool isAndSetCC;
25068     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
25069       if (isAndSetCC) {
25070         std::swap(FalseOp, TrueOp);
25071         CC0 = X86::GetOppositeBranchCondition(CC0);
25072         CC1 = X86::GetOppositeBranchCondition(CC1);
25073       }
25074
25075       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
25076         Flags};
25077       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
25078       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
25079       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25080       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
25081       return CMOV;
25082     }
25083   }
25084
25085   return SDValue();
25086 }
25087
25088 /// PerformMulCombine - Optimize a single multiply with constant into two
25089 /// in order to implement it with two cheaper instructions, e.g.
25090 /// LEA + SHL, LEA + LEA.
25091 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
25092                                  TargetLowering::DAGCombinerInfo &DCI) {
25093   // An imul is usually smaller than the alternative sequence.
25094   if (DAG.getMachineFunction().getFunction()->optForMinSize())
25095     return SDValue();
25096
25097   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
25098     return SDValue();
25099
25100   EVT VT = N->getValueType(0);
25101   if (VT != MVT::i64 && VT != MVT::i32)
25102     return SDValue();
25103
25104   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
25105   if (!C)
25106     return SDValue();
25107   uint64_t MulAmt = C->getZExtValue();
25108   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
25109     return SDValue();
25110
25111   uint64_t MulAmt1 = 0;
25112   uint64_t MulAmt2 = 0;
25113   if ((MulAmt % 9) == 0) {
25114     MulAmt1 = 9;
25115     MulAmt2 = MulAmt / 9;
25116   } else if ((MulAmt % 5) == 0) {
25117     MulAmt1 = 5;
25118     MulAmt2 = MulAmt / 5;
25119   } else if ((MulAmt % 3) == 0) {
25120     MulAmt1 = 3;
25121     MulAmt2 = MulAmt / 3;
25122   }
25123
25124   SDLoc DL(N);
25125   SDValue NewMul;
25126   if (MulAmt2 &&
25127       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
25128
25129     if (isPowerOf2_64(MulAmt2) &&
25130         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
25131       // If second multiplifer is pow2, issue it first. We want the multiply by
25132       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
25133       // is an add.
25134       std::swap(MulAmt1, MulAmt2);
25135
25136     if (isPowerOf2_64(MulAmt1))
25137       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25138                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
25139     else
25140       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
25141                            DAG.getConstant(MulAmt1, DL, VT));
25142
25143     if (isPowerOf2_64(MulAmt2))
25144       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
25145                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
25146     else
25147       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
25148                            DAG.getConstant(MulAmt2, DL, VT));
25149   }
25150
25151   if (!NewMul) {
25152     assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
25153            && "Both cases that could cause potential overflows should have "
25154               "already been handled.");
25155     if (isPowerOf2_64(MulAmt - 1))
25156       // (mul x, 2^N + 1) => (add (shl x, N), x)
25157       NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
25158                                 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25159                                 DAG.getConstant(Log2_64(MulAmt - 1), DL,
25160                                 MVT::i8)));
25161
25162     else if (isPowerOf2_64(MulAmt + 1))
25163       // (mul x, 2^N - 1) => (sub (shl x, N), x)
25164       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
25165                                 N->getOperand(0),
25166                                 DAG.getConstant(Log2_64(MulAmt + 1),
25167                                 DL, MVT::i8)), N->getOperand(0));
25168   }
25169
25170   if (NewMul)
25171     // Do not add new nodes to DAG combiner worklist.
25172     DCI.CombineTo(N, NewMul, false);
25173
25174   return SDValue();
25175 }
25176
25177 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
25178   SDValue N0 = N->getOperand(0);
25179   SDValue N1 = N->getOperand(1);
25180   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
25181   EVT VT = N0.getValueType();
25182
25183   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
25184   // since the result of setcc_c is all zero's or all ones.
25185   if (VT.isInteger() && !VT.isVector() &&
25186       N1C && N0.getOpcode() == ISD::AND &&
25187       N0.getOperand(1).getOpcode() == ISD::Constant) {
25188     SDValue N00 = N0.getOperand(0);
25189     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
25190     APInt ShAmt = N1C->getAPIntValue();
25191     Mask = Mask.shl(ShAmt);
25192     bool MaskOK = false;
25193     // We can handle cases concerning bit-widening nodes containing setcc_c if
25194     // we carefully interrogate the mask to make sure we are semantics
25195     // preserving.
25196     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
25197     // of the underlying setcc_c operation if the setcc_c was zero extended.
25198     // Consider the following example:
25199     //   zext(setcc_c)                 -> i32 0x0000FFFF
25200     //   c1                            -> i32 0x0000FFFF
25201     //   c2                            -> i32 0x00000001
25202     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
25203     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
25204     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25205       MaskOK = true;
25206     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
25207                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25208       MaskOK = true;
25209     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
25210                 N00.getOpcode() == ISD::ANY_EXTEND) &&
25211                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25212       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
25213     }
25214     if (MaskOK && Mask != 0) {
25215       SDLoc DL(N);
25216       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
25217     }
25218   }
25219
25220   // Hardware support for vector shifts is sparse which makes us scalarize the
25221   // vector operations in many cases. Also, on sandybridge ADD is faster than
25222   // shl.
25223   // (shl V, 1) -> add V,V
25224   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
25225     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
25226       assert(N0.getValueType().isVector() && "Invalid vector shift type");
25227       // We shift all of the values by one. In many cases we do not have
25228       // hardware support for this operation. This is better expressed as an ADD
25229       // of two values.
25230       if (N1SplatC->getAPIntValue() == 1)
25231         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
25232     }
25233
25234   return SDValue();
25235 }
25236
25237 static SDValue PerformSRACombine(SDNode *N, SelectionDAG &DAG) {
25238   SDValue N0 = N->getOperand(0);
25239   SDValue N1 = N->getOperand(1);
25240   EVT VT = N0.getValueType();
25241   unsigned Size = VT.getSizeInBits();
25242
25243   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
25244   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
25245   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
25246   // depending on sign of (SarConst - [56,48,32,24,16])
25247
25248   // sexts in X86 are MOVs. The MOVs have the same code size
25249   // as above SHIFTs (only SHIFT on 1 has lower code size).
25250   // However the MOVs have 2 advantages to a SHIFT:
25251   // 1. MOVs can write to a register that differs from source
25252   // 2. MOVs accept memory operands
25253
25254   if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
25255       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
25256       N0.getOperand(1).getOpcode() != ISD::Constant)
25257     return SDValue();
25258
25259   SDValue N00 = N0.getOperand(0);
25260   SDValue N01 = N0.getOperand(1);
25261   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
25262   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
25263   EVT CVT = N1.getValueType();
25264
25265   if (SarConst.isNegative())
25266     return SDValue();
25267
25268   for (MVT SVT : MVT::integer_valuetypes()) {
25269     unsigned ShiftSize = SVT.getSizeInBits();
25270     // skipping types without corresponding sext/zext and
25271     // ShlConst that is not one of [56,48,32,24,16]
25272     if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
25273       continue;
25274     SDLoc DL(N);
25275     SDValue NN =
25276         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
25277     SarConst = SarConst - (Size - ShiftSize);
25278     if (SarConst == 0)
25279       return NN;
25280     else if (SarConst.isNegative())
25281       return DAG.getNode(ISD::SHL, DL, VT, NN,
25282                          DAG.getConstant(-SarConst, DL, CVT));
25283     else
25284       return DAG.getNode(ISD::SRA, DL, VT, NN,
25285                          DAG.getConstant(SarConst, DL, CVT));
25286   }
25287   return SDValue();
25288 }
25289
25290 /// \brief Returns a vector of 0s if the node in input is a vector logical
25291 /// shift by a constant amount which is known to be bigger than or equal
25292 /// to the vector element size in bits.
25293 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
25294                                       const X86Subtarget *Subtarget) {
25295   EVT VT = N->getValueType(0);
25296
25297   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
25298       (!Subtarget->hasInt256() ||
25299        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
25300     return SDValue();
25301
25302   SDValue Amt = N->getOperand(1);
25303   SDLoc DL(N);
25304   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
25305     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
25306       APInt ShiftAmt = AmtSplat->getAPIntValue();
25307       unsigned MaxAmount =
25308         VT.getSimpleVT().getVectorElementType().getSizeInBits();
25309
25310       // SSE2/AVX2 logical shifts always return a vector of 0s
25311       // if the shift amount is bigger than or equal to
25312       // the element size. The constant shift amount will be
25313       // encoded as a 8-bit immediate.
25314       if (ShiftAmt.trunc(8).uge(MaxAmount))
25315         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
25316     }
25317
25318   return SDValue();
25319 }
25320
25321 /// PerformShiftCombine - Combine shifts.
25322 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
25323                                    TargetLowering::DAGCombinerInfo &DCI,
25324                                    const X86Subtarget *Subtarget) {
25325   if (N->getOpcode() == ISD::SHL)
25326     if (SDValue V = PerformSHLCombine(N, DAG))
25327       return V;
25328
25329   if (N->getOpcode() == ISD::SRA)
25330     if (SDValue V = PerformSRACombine(N, DAG))
25331       return V;
25332
25333   // Try to fold this logical shift into a zero vector.
25334   if (N->getOpcode() != ISD::SRA)
25335     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
25336       return V;
25337
25338   return SDValue();
25339 }
25340
25341 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
25342 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
25343 // and friends.  Likewise for OR -> CMPNEQSS.
25344 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
25345                             TargetLowering::DAGCombinerInfo &DCI,
25346                             const X86Subtarget *Subtarget) {
25347   unsigned opcode;
25348
25349   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
25350   // we're requiring SSE2 for both.
25351   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
25352     SDValue N0 = N->getOperand(0);
25353     SDValue N1 = N->getOperand(1);
25354     SDValue CMP0 = N0->getOperand(1);
25355     SDValue CMP1 = N1->getOperand(1);
25356     SDLoc DL(N);
25357
25358     // The SETCCs should both refer to the same CMP.
25359     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
25360       return SDValue();
25361
25362     SDValue CMP00 = CMP0->getOperand(0);
25363     SDValue CMP01 = CMP0->getOperand(1);
25364     EVT     VT    = CMP00.getValueType();
25365
25366     if (VT == MVT::f32 || VT == MVT::f64) {
25367       bool ExpectingFlags = false;
25368       // Check for any users that want flags:
25369       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
25370            !ExpectingFlags && UI != UE; ++UI)
25371         switch (UI->getOpcode()) {
25372         default:
25373         case ISD::BR_CC:
25374         case ISD::BRCOND:
25375         case ISD::SELECT:
25376           ExpectingFlags = true;
25377           break;
25378         case ISD::CopyToReg:
25379         case ISD::SIGN_EXTEND:
25380         case ISD::ZERO_EXTEND:
25381         case ISD::ANY_EXTEND:
25382           break;
25383         }
25384
25385       if (!ExpectingFlags) {
25386         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
25387         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
25388
25389         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
25390           X86::CondCode tmp = cc0;
25391           cc0 = cc1;
25392           cc1 = tmp;
25393         }
25394
25395         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
25396             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
25397           // FIXME: need symbolic constants for these magic numbers.
25398           // See X86ATTInstPrinter.cpp:printSSECC().
25399           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
25400           if (Subtarget->hasAVX512()) {
25401             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
25402                                          CMP01,
25403                                          DAG.getConstant(x86cc, DL, MVT::i8));
25404             if (N->getValueType(0) != MVT::i1)
25405               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25406                                  FSetCC);
25407             return FSetCC;
25408           }
25409           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25410                                               CMP00.getValueType(), CMP00, CMP01,
25411                                               DAG.getConstant(x86cc, DL,
25412                                                               MVT::i8));
25413
25414           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25415           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25416
25417           if (is64BitFP && !Subtarget->is64Bit()) {
25418             // On a 32-bit target, we cannot bitcast the 64-bit float to a
25419             // 64-bit integer, since that's not a legal type. Since
25420             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25421             // bits, but can do this little dance to extract the lowest 32 bits
25422             // and work with those going forward.
25423             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25424                                            OnesOrZeroesF);
25425             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25426             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25427                                         Vector32, DAG.getIntPtrConstant(0, DL));
25428             IntVT = MVT::i32;
25429           }
25430
25431           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25432           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25433                                       DAG.getConstant(1, DL, IntVT));
25434           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25435                                               ANDed);
25436           return OneBitOfTruth;
25437         }
25438       }
25439     }
25440   }
25441   return SDValue();
25442 }
25443
25444 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25445 /// so it can be folded inside ANDNP.
25446 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25447   EVT VT = N->getValueType(0);
25448
25449   // Match direct AllOnes for 128 and 256-bit vectors
25450   if (ISD::isBuildVectorAllOnes(N))
25451     return true;
25452
25453   // Look through a bit convert.
25454   if (N->getOpcode() == ISD::BITCAST)
25455     N = N->getOperand(0).getNode();
25456
25457   // Sometimes the operand may come from a insert_subvector building a 256-bit
25458   // allones vector
25459   if (VT.is256BitVector() &&
25460       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25461     SDValue V1 = N->getOperand(0);
25462     SDValue V2 = N->getOperand(1);
25463
25464     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25465         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25466         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25467         ISD::isBuildVectorAllOnes(V2.getNode()))
25468       return true;
25469   }
25470
25471   return false;
25472 }
25473
25474 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25475 // register. In most cases we actually compare or select YMM-sized registers
25476 // and mixing the two types creates horrible code. This method optimizes
25477 // some of the transition sequences.
25478 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25479                                  TargetLowering::DAGCombinerInfo &DCI,
25480                                  const X86Subtarget *Subtarget) {
25481   EVT VT = N->getValueType(0);
25482   if (!VT.is256BitVector())
25483     return SDValue();
25484
25485   assert((N->getOpcode() == ISD::ANY_EXTEND ||
25486           N->getOpcode() == ISD::ZERO_EXTEND ||
25487           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25488
25489   SDValue Narrow = N->getOperand(0);
25490   EVT NarrowVT = Narrow->getValueType(0);
25491   if (!NarrowVT.is128BitVector())
25492     return SDValue();
25493
25494   if (Narrow->getOpcode() != ISD::XOR &&
25495       Narrow->getOpcode() != ISD::AND &&
25496       Narrow->getOpcode() != ISD::OR)
25497     return SDValue();
25498
25499   SDValue N0  = Narrow->getOperand(0);
25500   SDValue N1  = Narrow->getOperand(1);
25501   SDLoc DL(Narrow);
25502
25503   // The Left side has to be a trunc.
25504   if (N0.getOpcode() != ISD::TRUNCATE)
25505     return SDValue();
25506
25507   // The type of the truncated inputs.
25508   EVT WideVT = N0->getOperand(0)->getValueType(0);
25509   if (WideVT != VT)
25510     return SDValue();
25511
25512   // The right side has to be a 'trunc' or a constant vector.
25513   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25514   ConstantSDNode *RHSConstSplat = nullptr;
25515   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25516     RHSConstSplat = RHSBV->getConstantSplatNode();
25517   if (!RHSTrunc && !RHSConstSplat)
25518     return SDValue();
25519
25520   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25521
25522   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25523     return SDValue();
25524
25525   // Set N0 and N1 to hold the inputs to the new wide operation.
25526   N0 = N0->getOperand(0);
25527   if (RHSConstSplat) {
25528     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25529                      SDValue(RHSConstSplat, 0));
25530     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25531     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25532   } else if (RHSTrunc) {
25533     N1 = N1->getOperand(0);
25534   }
25535
25536   // Generate the wide operation.
25537   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25538   unsigned Opcode = N->getOpcode();
25539   switch (Opcode) {
25540   case ISD::ANY_EXTEND:
25541     return Op;
25542   case ISD::ZERO_EXTEND: {
25543     unsigned InBits = NarrowVT.getScalarSizeInBits();
25544     APInt Mask = APInt::getAllOnesValue(InBits);
25545     Mask = Mask.zext(VT.getScalarSizeInBits());
25546     return DAG.getNode(ISD::AND, DL, VT,
25547                        Op, DAG.getConstant(Mask, DL, VT));
25548   }
25549   case ISD::SIGN_EXTEND:
25550     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25551                        Op, DAG.getValueType(NarrowVT));
25552   default:
25553     llvm_unreachable("Unexpected opcode");
25554   }
25555 }
25556
25557 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25558                                  TargetLowering::DAGCombinerInfo &DCI,
25559                                  const X86Subtarget *Subtarget) {
25560   SDValue N0 = N->getOperand(0);
25561   SDValue N1 = N->getOperand(1);
25562   SDLoc DL(N);
25563
25564   // A vector zext_in_reg may be represented as a shuffle,
25565   // feeding into a bitcast (this represents anyext) feeding into
25566   // an and with a mask.
25567   // We'd like to try to combine that into a shuffle with zero
25568   // plus a bitcast, removing the and.
25569   if (N0.getOpcode() != ISD::BITCAST ||
25570       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25571     return SDValue();
25572
25573   // The other side of the AND should be a splat of 2^C, where C
25574   // is the number of bits in the source type.
25575   if (N1.getOpcode() == ISD::BITCAST)
25576     N1 = N1.getOperand(0);
25577   if (N1.getOpcode() != ISD::BUILD_VECTOR)
25578     return SDValue();
25579   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25580
25581   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25582   EVT SrcType = Shuffle->getValueType(0);
25583
25584   // We expect a single-source shuffle
25585   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25586     return SDValue();
25587
25588   unsigned SrcSize = SrcType.getScalarSizeInBits();
25589
25590   APInt SplatValue, SplatUndef;
25591   unsigned SplatBitSize;
25592   bool HasAnyUndefs;
25593   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25594                                 SplatBitSize, HasAnyUndefs))
25595     return SDValue();
25596
25597   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25598   // Make sure the splat matches the mask we expect
25599   if (SplatBitSize > ResSize ||
25600       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25601     return SDValue();
25602
25603   // Make sure the input and output size make sense
25604   if (SrcSize >= ResSize || ResSize % SrcSize)
25605     return SDValue();
25606
25607   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25608   // The number of u's between each two values depends on the ratio between
25609   // the source and dest type.
25610   unsigned ZextRatio = ResSize / SrcSize;
25611   bool IsZext = true;
25612   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25613     if (i % ZextRatio) {
25614       if (Shuffle->getMaskElt(i) > 0) {
25615         // Expected undef
25616         IsZext = false;
25617         break;
25618       }
25619     } else {
25620       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25621         // Expected element number
25622         IsZext = false;
25623         break;
25624       }
25625     }
25626   }
25627
25628   if (!IsZext)
25629     return SDValue();
25630
25631   // Ok, perform the transformation - replace the shuffle with
25632   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25633   // (instead of undef) where the k elements come from the zero vector.
25634   SmallVector<int, 8> Mask;
25635   unsigned NumElems = SrcType.getVectorNumElements();
25636   for (unsigned i = 0; i < NumElems; ++i)
25637     if (i % ZextRatio)
25638       Mask.push_back(NumElems);
25639     else
25640       Mask.push_back(i / ZextRatio);
25641
25642   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25643     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25644   return DAG.getBitcast(N0.getValueType(), NewShuffle);
25645 }
25646
25647 /// If both input operands of a logic op are being cast from floating point
25648 /// types, try to convert this into a floating point logic node to avoid
25649 /// unnecessary moves from SSE to integer registers.
25650 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25651                                         const X86Subtarget *Subtarget) {
25652   unsigned FPOpcode = ISD::DELETED_NODE;
25653   if (N->getOpcode() == ISD::AND)
25654     FPOpcode = X86ISD::FAND;
25655   else if (N->getOpcode() == ISD::OR)
25656     FPOpcode = X86ISD::FOR;
25657   else if (N->getOpcode() == ISD::XOR)
25658     FPOpcode = X86ISD::FXOR;
25659
25660   assert(FPOpcode != ISD::DELETED_NODE &&
25661          "Unexpected input node for FP logic conversion");
25662
25663   EVT VT = N->getValueType(0);
25664   SDValue N0 = N->getOperand(0);
25665   SDValue N1 = N->getOperand(1);
25666   SDLoc DL(N);
25667   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25668       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25669        (Subtarget->hasSSE2() && VT == MVT::i64))) {
25670     SDValue N00 = N0.getOperand(0);
25671     SDValue N10 = N1.getOperand(0);
25672     EVT N00Type = N00.getValueType();
25673     EVT N10Type = N10.getValueType();
25674     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25675       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25676       return DAG.getBitcast(VT, FPLogic);
25677     }
25678   }
25679   return SDValue();
25680 }
25681
25682 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25683                                  TargetLowering::DAGCombinerInfo &DCI,
25684                                  const X86Subtarget *Subtarget) {
25685   if (DCI.isBeforeLegalizeOps())
25686     return SDValue();
25687
25688   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25689     return Zext;
25690
25691   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25692     return R;
25693
25694   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25695     return FPLogic;
25696
25697   EVT VT = N->getValueType(0);
25698   SDValue N0 = N->getOperand(0);
25699   SDValue N1 = N->getOperand(1);
25700   SDLoc DL(N);
25701
25702   // Create BEXTR instructions
25703   // BEXTR is ((X >> imm) & (2**size-1))
25704   if (VT == MVT::i32 || VT == MVT::i64) {
25705     // Check for BEXTR.
25706     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25707         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25708       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25709       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25710       if (MaskNode && ShiftNode) {
25711         uint64_t Mask = MaskNode->getZExtValue();
25712         uint64_t Shift = ShiftNode->getZExtValue();
25713         if (isMask_64(Mask)) {
25714           uint64_t MaskSize = countPopulation(Mask);
25715           if (Shift + MaskSize <= VT.getSizeInBits())
25716             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25717                                DAG.getConstant(Shift | (MaskSize << 8), DL,
25718                                                VT));
25719         }
25720       }
25721     } // BEXTR
25722
25723     return SDValue();
25724   }
25725
25726   // Want to form ANDNP nodes:
25727   // 1) In the hopes of then easily combining them with OR and AND nodes
25728   //    to form PBLEND/PSIGN.
25729   // 2) To match ANDN packed intrinsics
25730   if (VT != MVT::v2i64 && VT != MVT::v4i64)
25731     return SDValue();
25732
25733   // Check LHS for vnot
25734   if (N0.getOpcode() == ISD::XOR &&
25735       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25736       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25737     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25738
25739   // Check RHS for vnot
25740   if (N1.getOpcode() == ISD::XOR &&
25741       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25742       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25743     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25744
25745   return SDValue();
25746 }
25747
25748 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25749                                 TargetLowering::DAGCombinerInfo &DCI,
25750                                 const X86Subtarget *Subtarget) {
25751   if (DCI.isBeforeLegalizeOps())
25752     return SDValue();
25753
25754   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25755     return R;
25756
25757   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25758     return FPLogic;
25759
25760   SDValue N0 = N->getOperand(0);
25761   SDValue N1 = N->getOperand(1);
25762   EVT VT = N->getValueType(0);
25763
25764   // look for psign/blend
25765   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25766     if (!Subtarget->hasSSSE3() ||
25767         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25768       return SDValue();
25769
25770     // Canonicalize pandn to RHS
25771     if (N0.getOpcode() == X86ISD::ANDNP)
25772       std::swap(N0, N1);
25773     // or (and (m, y), (pandn m, x))
25774     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25775       SDValue Mask = N1.getOperand(0);
25776       SDValue X    = N1.getOperand(1);
25777       SDValue Y;
25778       if (N0.getOperand(0) == Mask)
25779         Y = N0.getOperand(1);
25780       if (N0.getOperand(1) == Mask)
25781         Y = N0.getOperand(0);
25782
25783       // Check to see if the mask appeared in both the AND and ANDNP and
25784       if (!Y.getNode())
25785         return SDValue();
25786
25787       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25788       // Look through mask bitcast.
25789       if (Mask.getOpcode() == ISD::BITCAST)
25790         Mask = Mask.getOperand(0);
25791       if (X.getOpcode() == ISD::BITCAST)
25792         X = X.getOperand(0);
25793       if (Y.getOpcode() == ISD::BITCAST)
25794         Y = Y.getOperand(0);
25795
25796       EVT MaskVT = Mask.getValueType();
25797
25798       // Validate that the Mask operand is a vector sra node.
25799       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25800       // there is no psrai.b
25801       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25802       unsigned SraAmt = ~0;
25803       if (Mask.getOpcode() == ISD::SRA) {
25804         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25805           if (auto *AmtConst = AmtBV->getConstantSplatNode())
25806             SraAmt = AmtConst->getZExtValue();
25807       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25808         SDValue SraC = Mask.getOperand(1);
25809         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
25810       }
25811       if ((SraAmt + 1) != EltBits)
25812         return SDValue();
25813
25814       SDLoc DL(N);
25815
25816       // Now we know we at least have a plendvb with the mask val.  See if
25817       // we can form a psignb/w/d.
25818       // psign = x.type == y.type == mask.type && y = sub(0, x);
25819       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25820           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25821           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25822         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25823                "Unsupported VT for PSIGN");
25824         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25825         return DAG.getBitcast(VT, Mask);
25826       }
25827       // PBLENDVB only available on SSE 4.1
25828       if (!Subtarget->hasSSE41())
25829         return SDValue();
25830
25831       MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25832
25833       X = DAG.getBitcast(BlendVT, X);
25834       Y = DAG.getBitcast(BlendVT, Y);
25835       Mask = DAG.getBitcast(BlendVT, Mask);
25836       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25837       return DAG.getBitcast(VT, Mask);
25838     }
25839   }
25840
25841   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25842     return SDValue();
25843
25844   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25845   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25846
25847   // SHLD/SHRD instructions have lower register pressure, but on some
25848   // platforms they have higher latency than the equivalent
25849   // series of shifts/or that would otherwise be generated.
25850   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25851   // have higher latencies and we are not optimizing for size.
25852   if (!OptForSize && Subtarget->isSHLDSlow())
25853     return SDValue();
25854
25855   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25856     std::swap(N0, N1);
25857   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25858     return SDValue();
25859   if (!N0.hasOneUse() || !N1.hasOneUse())
25860     return SDValue();
25861
25862   SDValue ShAmt0 = N0.getOperand(1);
25863   if (ShAmt0.getValueType() != MVT::i8)
25864     return SDValue();
25865   SDValue ShAmt1 = N1.getOperand(1);
25866   if (ShAmt1.getValueType() != MVT::i8)
25867     return SDValue();
25868   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25869     ShAmt0 = ShAmt0.getOperand(0);
25870   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25871     ShAmt1 = ShAmt1.getOperand(0);
25872
25873   SDLoc DL(N);
25874   unsigned Opc = X86ISD::SHLD;
25875   SDValue Op0 = N0.getOperand(0);
25876   SDValue Op1 = N1.getOperand(0);
25877   if (ShAmt0.getOpcode() == ISD::SUB) {
25878     Opc = X86ISD::SHRD;
25879     std::swap(Op0, Op1);
25880     std::swap(ShAmt0, ShAmt1);
25881   }
25882
25883   unsigned Bits = VT.getSizeInBits();
25884   if (ShAmt1.getOpcode() == ISD::SUB) {
25885     SDValue Sum = ShAmt1.getOperand(0);
25886     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25887       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25888       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25889         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25890       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25891         return DAG.getNode(Opc, DL, VT,
25892                            Op0, Op1,
25893                            DAG.getNode(ISD::TRUNCATE, DL,
25894                                        MVT::i8, ShAmt0));
25895     }
25896   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25897     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25898     if (ShAmt0C &&
25899         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25900       return DAG.getNode(Opc, DL, VT,
25901                          N0.getOperand(0), N1.getOperand(0),
25902                          DAG.getNode(ISD::TRUNCATE, DL,
25903                                        MVT::i8, ShAmt0));
25904   }
25905
25906   return SDValue();
25907 }
25908
25909 // Generate NEG and CMOV for integer abs.
25910 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25911   EVT VT = N->getValueType(0);
25912
25913   // Since X86 does not have CMOV for 8-bit integer, we don't convert
25914   // 8-bit integer abs to NEG and CMOV.
25915   if (VT.isInteger() && VT.getSizeInBits() == 8)
25916     return SDValue();
25917
25918   SDValue N0 = N->getOperand(0);
25919   SDValue N1 = N->getOperand(1);
25920   SDLoc DL(N);
25921
25922   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25923   // and change it to SUB and CMOV.
25924   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25925       N0.getOpcode() == ISD::ADD &&
25926       N0.getOperand(1) == N1 &&
25927       N1.getOpcode() == ISD::SRA &&
25928       N1.getOperand(0) == N0.getOperand(0))
25929     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25930       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25931         // Generate SUB & CMOV.
25932         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25933                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
25934
25935         SDValue Ops[] = { N0.getOperand(0), Neg,
25936                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25937                           SDValue(Neg.getNode(), 1) };
25938         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25939       }
25940   return SDValue();
25941 }
25942
25943 // Try to turn tests against the signbit in the form of:
25944 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25945 // into:
25946 //   SETGT(X, -1)
25947 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25948   // This is only worth doing if the output type is i8.
25949   if (N->getValueType(0) != MVT::i8)
25950     return SDValue();
25951
25952   SDValue N0 = N->getOperand(0);
25953   SDValue N1 = N->getOperand(1);
25954
25955   // We should be performing an xor against a truncated shift.
25956   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25957     return SDValue();
25958
25959   // Make sure we are performing an xor against one.
25960   if (!isOneConstant(N1))
25961     return SDValue();
25962
25963   // SetCC on x86 zero extends so only act on this if it's a logical shift.
25964   SDValue Shift = N0.getOperand(0);
25965   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25966     return SDValue();
25967
25968   // Make sure we are truncating from one of i16, i32 or i64.
25969   EVT ShiftTy = Shift.getValueType();
25970   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25971     return SDValue();
25972
25973   // Make sure the shift amount extracts the sign bit.
25974   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25975       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25976     return SDValue();
25977
25978   // Create a greater-than comparison against -1.
25979   // N.B. Using SETGE against 0 works but we want a canonical looking
25980   // comparison, using SETGT matches up with what TranslateX86CC.
25981   SDLoc DL(N);
25982   SDValue ShiftOp = Shift.getOperand(0);
25983   EVT ShiftOpTy = ShiftOp.getValueType();
25984   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
25985                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
25986   return Cond;
25987 }
25988
25989 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
25990                                  TargetLowering::DAGCombinerInfo &DCI,
25991                                  const X86Subtarget *Subtarget) {
25992   if (DCI.isBeforeLegalizeOps())
25993     return SDValue();
25994
25995   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
25996     return RV;
25997
25998   if (Subtarget->hasCMov())
25999     if (SDValue RV = performIntegerAbsCombine(N, DAG))
26000       return RV;
26001
26002   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
26003     return FPLogic;
26004
26005   return SDValue();
26006 }
26007
26008 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
26009 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
26010 /// X86ISD::AVG instruction.
26011 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
26012                                 const X86Subtarget *Subtarget, SDLoc DL) {
26013   if (!VT.isVector() || !VT.isSimple())
26014     return SDValue();
26015   EVT InVT = In.getValueType();
26016   unsigned NumElems = VT.getVectorNumElements();
26017
26018   EVT ScalarVT = VT.getVectorElementType();
26019   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
26020         isPowerOf2_32(NumElems)))
26021     return SDValue();
26022
26023   // InScalarVT is the intermediate type in AVG pattern and it should be greater
26024   // than the original input type (i8/i16).
26025   EVT InScalarVT = InVT.getVectorElementType();
26026   if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
26027     return SDValue();
26028
26029   if (Subtarget->hasAVX512()) {
26030     if (VT.getSizeInBits() > 512)
26031       return SDValue();
26032   } else if (Subtarget->hasAVX2()) {
26033     if (VT.getSizeInBits() > 256)
26034       return SDValue();
26035   } else {
26036     if (VT.getSizeInBits() > 128)
26037       return SDValue();
26038   }
26039
26040   // Detect the following pattern:
26041   //
26042   //   %1 = zext <N x i8> %a to <N x i32>
26043   //   %2 = zext <N x i8> %b to <N x i32>
26044   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
26045   //   %4 = add nuw nsw <N x i32> %3, %2
26046   //   %5 = lshr <N x i32> %N, <i32 1 x N>
26047   //   %6 = trunc <N x i32> %5 to <N x i8>
26048   //
26049   // In AVX512, the last instruction can also be a trunc store.
26050
26051   if (In.getOpcode() != ISD::SRL)
26052     return SDValue();
26053
26054   // A lambda checking the given SDValue is a constant vector and each element
26055   // is in the range [Min, Max].
26056   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
26057     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
26058     if (!BV || !BV->isConstant())
26059       return false;
26060     for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
26061       ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
26062       if (!C)
26063         return false;
26064       uint64_t Val = C->getZExtValue();
26065       if (Val < Min || Val > Max)
26066         return false;
26067     }
26068     return true;
26069   };
26070
26071   // Check if each element of the vector is left-shifted by one.
26072   auto LHS = In.getOperand(0);
26073   auto RHS = In.getOperand(1);
26074   if (!IsConstVectorInRange(RHS, 1, 1))
26075     return SDValue();
26076   if (LHS.getOpcode() != ISD::ADD)
26077     return SDValue();
26078
26079   // Detect a pattern of a + b + 1 where the order doesn't matter.
26080   SDValue Operands[3];
26081   Operands[0] = LHS.getOperand(0);
26082   Operands[1] = LHS.getOperand(1);
26083
26084   // Take care of the case when one of the operands is a constant vector whose
26085   // element is in the range [1, 256].
26086   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
26087       Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
26088       Operands[0].getOperand(0).getValueType() == VT) {
26089     // The pattern is detected. Subtract one from the constant vector, then
26090     // demote it and emit X86ISD::AVG instruction.
26091     SDValue One = DAG.getConstant(1, DL, InScalarVT);
26092     SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
26093                                SmallVector<SDValue, 8>(NumElems, One));
26094     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
26095     Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
26096     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26097                        Operands[1]);
26098   }
26099
26100   if (Operands[0].getOpcode() == ISD::ADD)
26101     std::swap(Operands[0], Operands[1]);
26102   else if (Operands[1].getOpcode() != ISD::ADD)
26103     return SDValue();
26104   Operands[2] = Operands[1].getOperand(0);
26105   Operands[1] = Operands[1].getOperand(1);
26106
26107   // Now we have three operands of two additions. Check that one of them is a
26108   // constant vector with ones, and the other two are promoted from i8/i16.
26109   for (int i = 0; i < 3; ++i) {
26110     if (!IsConstVectorInRange(Operands[i], 1, 1))
26111       continue;
26112     std::swap(Operands[i], Operands[2]);
26113
26114     // Check if Operands[0] and Operands[1] are results of type promotion.
26115     for (int j = 0; j < 2; ++j)
26116       if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
26117           Operands[j].getOperand(0).getValueType() != VT)
26118         return SDValue();
26119
26120     // The pattern is detected, emit X86ISD::AVG instruction.
26121     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26122                        Operands[1].getOperand(0));
26123   }
26124
26125   return SDValue();
26126 }
26127
26128 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
26129 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
26130                                   TargetLowering::DAGCombinerInfo &DCI,
26131                                   const X86Subtarget *Subtarget) {
26132   LoadSDNode *Ld = cast<LoadSDNode>(N);
26133   EVT RegVT = Ld->getValueType(0);
26134   EVT MemVT = Ld->getMemoryVT();
26135   SDLoc dl(Ld);
26136   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26137
26138   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
26139   // into two 16-byte operations.
26140   ISD::LoadExtType Ext = Ld->getExtensionType();
26141   bool Fast;
26142   unsigned AddressSpace = Ld->getAddressSpace();
26143   unsigned Alignment = Ld->getAlignment();
26144   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
26145       Ext == ISD::NON_EXTLOAD &&
26146       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
26147                              AddressSpace, Alignment, &Fast) && !Fast) {
26148     unsigned NumElems = RegVT.getVectorNumElements();
26149     if (NumElems < 2)
26150       return SDValue();
26151
26152     SDValue Ptr = Ld->getBasePtr();
26153     SDValue Increment =
26154         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26155
26156     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
26157                                   NumElems/2);
26158     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26159                                 Ld->getPointerInfo(), Ld->isVolatile(),
26160                                 Ld->isNonTemporal(), Ld->isInvariant(),
26161                                 Alignment);
26162     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26163     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26164                                 Ld->getPointerInfo(), Ld->isVolatile(),
26165                                 Ld->isNonTemporal(), Ld->isInvariant(),
26166                                 std::min(16U, Alignment));
26167     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
26168                              Load1.getValue(1),
26169                              Load2.getValue(1));
26170
26171     SDValue NewVec = DAG.getUNDEF(RegVT);
26172     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
26173     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
26174     return DCI.CombineTo(N, NewVec, TF, true);
26175   }
26176
26177   return SDValue();
26178 }
26179
26180 /// PerformMLOADCombine - Resolve extending loads
26181 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
26182                                    TargetLowering::DAGCombinerInfo &DCI,
26183                                    const X86Subtarget *Subtarget) {
26184   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
26185   if (Mld->getExtensionType() != ISD::SEXTLOAD)
26186     return SDValue();
26187
26188   EVT VT = Mld->getValueType(0);
26189   unsigned NumElems = VT.getVectorNumElements();
26190   EVT LdVT = Mld->getMemoryVT();
26191   SDLoc dl(Mld);
26192
26193   assert(LdVT != VT && "Cannot extend to the same type");
26194   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
26195   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
26196   // From, To sizes and ElemCount must be pow of two
26197   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26198     "Unexpected size for extending masked load");
26199
26200   unsigned SizeRatio  = ToSz / FromSz;
26201   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
26202
26203   // Create a type on which we perform the shuffle
26204   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26205           LdVT.getScalarType(), NumElems*SizeRatio);
26206   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26207
26208   // Convert Src0 value
26209   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
26210   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
26211     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26212     for (unsigned i = 0; i != NumElems; ++i)
26213       ShuffleVec[i] = i * SizeRatio;
26214
26215     // Can't shuffle using an illegal type.
26216     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26217            "WideVecVT should be legal");
26218     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
26219                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
26220   }
26221   // Prepare the new mask
26222   SDValue NewMask;
26223   SDValue Mask = Mld->getMask();
26224   if (Mask.getValueType() == VT) {
26225     // Mask and original value have the same type
26226     NewMask = DAG.getBitcast(WideVecVT, Mask);
26227     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26228     for (unsigned i = 0; i != NumElems; ++i)
26229       ShuffleVec[i] = i * SizeRatio;
26230     for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
26231       ShuffleVec[i] = NumElems * SizeRatio;
26232     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26233                                    DAG.getConstant(0, dl, WideVecVT),
26234                                    &ShuffleVec[0]);
26235   }
26236   else {
26237     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26238     unsigned WidenNumElts = NumElems*SizeRatio;
26239     unsigned MaskNumElts = VT.getVectorNumElements();
26240     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26241                                      WidenNumElts);
26242
26243     unsigned NumConcat = WidenNumElts / MaskNumElts;
26244     SmallVector<SDValue, 16> Ops(NumConcat);
26245     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26246     Ops[0] = Mask;
26247     for (unsigned i = 1; i != NumConcat; ++i)
26248       Ops[i] = ZeroVal;
26249
26250     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26251   }
26252
26253   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
26254                                      Mld->getBasePtr(), NewMask, WideSrc0,
26255                                      Mld->getMemoryVT(), Mld->getMemOperand(),
26256                                      ISD::NON_EXTLOAD);
26257   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
26258   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
26259 }
26260 /// PerformMSTORECombine - Resolve truncating stores
26261 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
26262                                     const X86Subtarget *Subtarget) {
26263   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
26264   if (!Mst->isTruncatingStore())
26265     return SDValue();
26266
26267   EVT VT = Mst->getValue().getValueType();
26268   unsigned NumElems = VT.getVectorNumElements();
26269   EVT StVT = Mst->getMemoryVT();
26270   SDLoc dl(Mst);
26271
26272   assert(StVT != VT && "Cannot truncate to the same type");
26273   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26274   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26275
26276   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26277
26278   // The truncating store is legal in some cases. For example
26279   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26280   // are designated for truncate store.
26281   // In this case we don't need any further transformations.
26282   if (TLI.isTruncStoreLegal(VT, StVT))
26283     return SDValue();
26284
26285   // From, To sizes and ElemCount must be pow of two
26286   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26287     "Unexpected size for truncating masked store");
26288   // We are going to use the original vector elt for storing.
26289   // Accumulated smaller vector elements must be a multiple of the store size.
26290   assert (((NumElems * FromSz) % ToSz) == 0 &&
26291           "Unexpected ratio for truncating masked store");
26292
26293   unsigned SizeRatio  = FromSz / ToSz;
26294   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26295
26296   // Create a type on which we perform the shuffle
26297   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26298           StVT.getScalarType(), NumElems*SizeRatio);
26299
26300   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26301
26302   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
26303   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26304   for (unsigned i = 0; i != NumElems; ++i)
26305     ShuffleVec[i] = i * SizeRatio;
26306
26307   // Can't shuffle using an illegal type.
26308   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26309          "WideVecVT should be legal");
26310
26311   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26312                                               DAG.getUNDEF(WideVecVT),
26313                                               &ShuffleVec[0]);
26314
26315   SDValue NewMask;
26316   SDValue Mask = Mst->getMask();
26317   if (Mask.getValueType() == VT) {
26318     // Mask and original value have the same type
26319     NewMask = DAG.getBitcast(WideVecVT, Mask);
26320     for (unsigned i = 0; i != NumElems; ++i)
26321       ShuffleVec[i] = i * SizeRatio;
26322     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
26323       ShuffleVec[i] = NumElems*SizeRatio;
26324     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26325                                    DAG.getConstant(0, dl, WideVecVT),
26326                                    &ShuffleVec[0]);
26327   }
26328   else {
26329     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26330     unsigned WidenNumElts = NumElems*SizeRatio;
26331     unsigned MaskNumElts = VT.getVectorNumElements();
26332     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26333                                      WidenNumElts);
26334
26335     unsigned NumConcat = WidenNumElts / MaskNumElts;
26336     SmallVector<SDValue, 16> Ops(NumConcat);
26337     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26338     Ops[0] = Mask;
26339     for (unsigned i = 1; i != NumConcat; ++i)
26340       Ops[i] = ZeroVal;
26341
26342     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26343   }
26344
26345   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
26346                             Mst->getBasePtr(), NewMask, StVT,
26347                             Mst->getMemOperand(), false);
26348 }
26349 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
26350 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
26351                                    const X86Subtarget *Subtarget) {
26352   StoreSDNode *St = cast<StoreSDNode>(N);
26353   EVT VT = St->getValue().getValueType();
26354   EVT StVT = St->getMemoryVT();
26355   SDLoc dl(St);
26356   SDValue StoredVal = St->getOperand(1);
26357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26358
26359   // If we are saving a concatenation of two XMM registers and 32-byte stores
26360   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
26361   bool Fast;
26362   unsigned AddressSpace = St->getAddressSpace();
26363   unsigned Alignment = St->getAlignment();
26364   if (VT.is256BitVector() && StVT == VT &&
26365       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
26366                              AddressSpace, Alignment, &Fast) && !Fast) {
26367     unsigned NumElems = VT.getVectorNumElements();
26368     if (NumElems < 2)
26369       return SDValue();
26370
26371     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
26372     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
26373
26374     SDValue Stride =
26375         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26376     SDValue Ptr0 = St->getBasePtr();
26377     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
26378
26379     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
26380                                 St->getPointerInfo(), St->isVolatile(),
26381                                 St->isNonTemporal(), Alignment);
26382     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
26383                                 St->getPointerInfo(), St->isVolatile(),
26384                                 St->isNonTemporal(),
26385                                 std::min(16U, Alignment));
26386     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
26387   }
26388
26389   // Optimize trunc store (of multiple scalars) to shuffle and store.
26390   // First, pack all of the elements in one place. Next, store to memory
26391   // in fewer chunks.
26392   if (St->isTruncatingStore() && VT.isVector()) {
26393     // Check if we can detect an AVG pattern from the truncation. If yes,
26394     // replace the trunc store by a normal store with the result of X86ISD::AVG
26395     // instruction.
26396     SDValue Avg =
26397         detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
26398     if (Avg.getNode())
26399       return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
26400                           St->getPointerInfo(), St->isVolatile(),
26401                           St->isNonTemporal(), St->getAlignment());
26402
26403     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26404     unsigned NumElems = VT.getVectorNumElements();
26405     assert(StVT != VT && "Cannot truncate to the same type");
26406     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26407     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26408
26409     // The truncating store is legal in some cases. For example
26410     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26411     // are designated for truncate store.
26412     // In this case we don't need any further transformations.
26413     if (TLI.isTruncStoreLegal(VT, StVT))
26414       return SDValue();
26415
26416     // From, To sizes and ElemCount must be pow of two
26417     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26418     // We are going to use the original vector elt for storing.
26419     // Accumulated smaller vector elements must be a multiple of the store size.
26420     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26421
26422     unsigned SizeRatio  = FromSz / ToSz;
26423
26424     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26425
26426     // Create a type on which we perform the shuffle
26427     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26428             StVT.getScalarType(), NumElems*SizeRatio);
26429
26430     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26431
26432     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26433     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26434     for (unsigned i = 0; i != NumElems; ++i)
26435       ShuffleVec[i] = i * SizeRatio;
26436
26437     // Can't shuffle using an illegal type.
26438     if (!TLI.isTypeLegal(WideVecVT))
26439       return SDValue();
26440
26441     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26442                                          DAG.getUNDEF(WideVecVT),
26443                                          &ShuffleVec[0]);
26444     // At this point all of the data is stored at the bottom of the
26445     // register. We now need to save it to mem.
26446
26447     // Find the largest store unit
26448     MVT StoreType = MVT::i8;
26449     for (MVT Tp : MVT::integer_valuetypes()) {
26450       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26451         StoreType = Tp;
26452     }
26453
26454     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26455     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26456         (64 <= NumElems * ToSz))
26457       StoreType = MVT::f64;
26458
26459     // Bitcast the original vector into a vector of store-size units
26460     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26461             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26462     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26463     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26464     SmallVector<SDValue, 8> Chains;
26465     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26466                                         TLI.getPointerTy(DAG.getDataLayout()));
26467     SDValue Ptr = St->getBasePtr();
26468
26469     // Perform one or more big stores into memory.
26470     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26471       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26472                                    StoreType, ShuffWide,
26473                                    DAG.getIntPtrConstant(i, dl));
26474       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26475                                 St->getPointerInfo(), St->isVolatile(),
26476                                 St->isNonTemporal(), St->getAlignment());
26477       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26478       Chains.push_back(Ch);
26479     }
26480
26481     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26482   }
26483
26484   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
26485   // the FP state in cases where an emms may be missing.
26486   // A preferable solution to the general problem is to figure out the right
26487   // places to insert EMMS.  This qualifies as a quick hack.
26488
26489   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26490   if (VT.getSizeInBits() != 64)
26491     return SDValue();
26492
26493   const Function *F = DAG.getMachineFunction().getFunction();
26494   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26495   bool F64IsLegal =
26496       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26497   if ((VT.isVector() ||
26498        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26499       isa<LoadSDNode>(St->getValue()) &&
26500       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26501       St->getChain().hasOneUse() && !St->isVolatile()) {
26502     SDNode* LdVal = St->getValue().getNode();
26503     LoadSDNode *Ld = nullptr;
26504     int TokenFactorIndex = -1;
26505     SmallVector<SDValue, 8> Ops;
26506     SDNode* ChainVal = St->getChain().getNode();
26507     // Must be a store of a load.  We currently handle two cases:  the load
26508     // is a direct child, and it's under an intervening TokenFactor.  It is
26509     // possible to dig deeper under nested TokenFactors.
26510     if (ChainVal == LdVal)
26511       Ld = cast<LoadSDNode>(St->getChain());
26512     else if (St->getValue().hasOneUse() &&
26513              ChainVal->getOpcode() == ISD::TokenFactor) {
26514       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26515         if (ChainVal->getOperand(i).getNode() == LdVal) {
26516           TokenFactorIndex = i;
26517           Ld = cast<LoadSDNode>(St->getValue());
26518         } else
26519           Ops.push_back(ChainVal->getOperand(i));
26520       }
26521     }
26522
26523     if (!Ld || !ISD::isNormalLoad(Ld))
26524       return SDValue();
26525
26526     // If this is not the MMX case, i.e. we are just turning i64 load/store
26527     // into f64 load/store, avoid the transformation if there are multiple
26528     // uses of the loaded value.
26529     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26530       return SDValue();
26531
26532     SDLoc LdDL(Ld);
26533     SDLoc StDL(N);
26534     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26535     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26536     // pair instead.
26537     if (Subtarget->is64Bit() || F64IsLegal) {
26538       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26539       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26540                                   Ld->getPointerInfo(), Ld->isVolatile(),
26541                                   Ld->isNonTemporal(), Ld->isInvariant(),
26542                                   Ld->getAlignment());
26543       SDValue NewChain = NewLd.getValue(1);
26544       if (TokenFactorIndex != -1) {
26545         Ops.push_back(NewChain);
26546         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26547       }
26548       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26549                           St->getPointerInfo(),
26550                           St->isVolatile(), St->isNonTemporal(),
26551                           St->getAlignment());
26552     }
26553
26554     // Otherwise, lower to two pairs of 32-bit loads / stores.
26555     SDValue LoAddr = Ld->getBasePtr();
26556     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26557                                  DAG.getConstant(4, LdDL, MVT::i32));
26558
26559     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26560                                Ld->getPointerInfo(),
26561                                Ld->isVolatile(), Ld->isNonTemporal(),
26562                                Ld->isInvariant(), Ld->getAlignment());
26563     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26564                                Ld->getPointerInfo().getWithOffset(4),
26565                                Ld->isVolatile(), Ld->isNonTemporal(),
26566                                Ld->isInvariant(),
26567                                MinAlign(Ld->getAlignment(), 4));
26568
26569     SDValue NewChain = LoLd.getValue(1);
26570     if (TokenFactorIndex != -1) {
26571       Ops.push_back(LoLd);
26572       Ops.push_back(HiLd);
26573       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26574     }
26575
26576     LoAddr = St->getBasePtr();
26577     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26578                          DAG.getConstant(4, StDL, MVT::i32));
26579
26580     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26581                                 St->getPointerInfo(),
26582                                 St->isVolatile(), St->isNonTemporal(),
26583                                 St->getAlignment());
26584     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26585                                 St->getPointerInfo().getWithOffset(4),
26586                                 St->isVolatile(),
26587                                 St->isNonTemporal(),
26588                                 MinAlign(St->getAlignment(), 4));
26589     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26590   }
26591
26592   // This is similar to the above case, but here we handle a scalar 64-bit
26593   // integer store that is extracted from a vector on a 32-bit target.
26594   // If we have SSE2, then we can treat it like a floating-point double
26595   // to get past legalization. The execution dependencies fixup pass will
26596   // choose the optimal machine instruction for the store if this really is
26597   // an integer or v2f32 rather than an f64.
26598   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26599       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26600     SDValue OldExtract = St->getOperand(1);
26601     SDValue ExtOp0 = OldExtract.getOperand(0);
26602     unsigned VecSize = ExtOp0.getValueSizeInBits();
26603     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26604     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26605     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26606                                      BitCast, OldExtract.getOperand(1));
26607     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26608                         St->getPointerInfo(), St->isVolatile(),
26609                         St->isNonTemporal(), St->getAlignment());
26610   }
26611
26612   return SDValue();
26613 }
26614
26615 /// Return 'true' if this vector operation is "horizontal"
26616 /// and return the operands for the horizontal operation in LHS and RHS.  A
26617 /// horizontal operation performs the binary operation on successive elements
26618 /// of its first operand, then on successive elements of its second operand,
26619 /// returning the resulting values in a vector.  For example, if
26620 ///   A = < float a0, float a1, float a2, float a3 >
26621 /// and
26622 ///   B = < float b0, float b1, float b2, float b3 >
26623 /// then the result of doing a horizontal operation on A and B is
26624 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26625 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26626 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26627 /// set to A, RHS to B, and the routine returns 'true'.
26628 /// Note that the binary operation should have the property that if one of the
26629 /// operands is UNDEF then the result is UNDEF.
26630 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26631   // Look for the following pattern: if
26632   //   A = < float a0, float a1, float a2, float a3 >
26633   //   B = < float b0, float b1, float b2, float b3 >
26634   // and
26635   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26636   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26637   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26638   // which is A horizontal-op B.
26639
26640   // At least one of the operands should be a vector shuffle.
26641   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26642       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26643     return false;
26644
26645   MVT VT = LHS.getSimpleValueType();
26646
26647   assert((VT.is128BitVector() || VT.is256BitVector()) &&
26648          "Unsupported vector type for horizontal add/sub");
26649
26650   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26651   // operate independently on 128-bit lanes.
26652   unsigned NumElts = VT.getVectorNumElements();
26653   unsigned NumLanes = VT.getSizeInBits()/128;
26654   unsigned NumLaneElts = NumElts / NumLanes;
26655   assert((NumLaneElts % 2 == 0) &&
26656          "Vector type should have an even number of elements in each lane");
26657   unsigned HalfLaneElts = NumLaneElts/2;
26658
26659   // View LHS in the form
26660   //   LHS = VECTOR_SHUFFLE A, B, LMask
26661   // If LHS is not a shuffle then pretend it is the shuffle
26662   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26663   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26664   // type VT.
26665   SDValue A, B;
26666   SmallVector<int, 16> LMask(NumElts);
26667   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26668     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26669       A = LHS.getOperand(0);
26670     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26671       B = LHS.getOperand(1);
26672     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26673     std::copy(Mask.begin(), Mask.end(), LMask.begin());
26674   } else {
26675     if (LHS.getOpcode() != ISD::UNDEF)
26676       A = LHS;
26677     for (unsigned i = 0; i != NumElts; ++i)
26678       LMask[i] = i;
26679   }
26680
26681   // Likewise, view RHS in the form
26682   //   RHS = VECTOR_SHUFFLE C, D, RMask
26683   SDValue C, D;
26684   SmallVector<int, 16> RMask(NumElts);
26685   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26686     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26687       C = RHS.getOperand(0);
26688     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26689       D = RHS.getOperand(1);
26690     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26691     std::copy(Mask.begin(), Mask.end(), RMask.begin());
26692   } else {
26693     if (RHS.getOpcode() != ISD::UNDEF)
26694       C = RHS;
26695     for (unsigned i = 0; i != NumElts; ++i)
26696       RMask[i] = i;
26697   }
26698
26699   // Check that the shuffles are both shuffling the same vectors.
26700   if (!(A == C && B == D) && !(A == D && B == C))
26701     return false;
26702
26703   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26704   if (!A.getNode() && !B.getNode())
26705     return false;
26706
26707   // If A and B occur in reverse order in RHS, then "swap" them (which means
26708   // rewriting the mask).
26709   if (A != C)
26710     ShuffleVectorSDNode::commuteMask(RMask);
26711
26712   // At this point LHS and RHS are equivalent to
26713   //   LHS = VECTOR_SHUFFLE A, B, LMask
26714   //   RHS = VECTOR_SHUFFLE A, B, RMask
26715   // Check that the masks correspond to performing a horizontal operation.
26716   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26717     for (unsigned i = 0; i != NumLaneElts; ++i) {
26718       int LIdx = LMask[i+l], RIdx = RMask[i+l];
26719
26720       // Ignore any UNDEF components.
26721       if (LIdx < 0 || RIdx < 0 ||
26722           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26723           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26724         continue;
26725
26726       // Check that successive elements are being operated on.  If not, this is
26727       // not a horizontal operation.
26728       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26729       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26730       if (!(LIdx == Index && RIdx == Index + 1) &&
26731           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26732         return false;
26733     }
26734   }
26735
26736   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26737   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26738   return true;
26739 }
26740
26741 /// Do target-specific dag combines on floating point adds.
26742 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26743                                   const X86Subtarget *Subtarget) {
26744   EVT VT = N->getValueType(0);
26745   SDValue LHS = N->getOperand(0);
26746   SDValue RHS = N->getOperand(1);
26747
26748   // Try to synthesize horizontal adds from adds of shuffles.
26749   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26750        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26751       isHorizontalBinOp(LHS, RHS, true))
26752     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26753   return SDValue();
26754 }
26755
26756 /// Do target-specific dag combines on floating point subs.
26757 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26758                                   const X86Subtarget *Subtarget) {
26759   EVT VT = N->getValueType(0);
26760   SDValue LHS = N->getOperand(0);
26761   SDValue RHS = N->getOperand(1);
26762
26763   // Try to synthesize horizontal subs from subs of shuffles.
26764   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26765        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26766       isHorizontalBinOp(LHS, RHS, false))
26767     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26768   return SDValue();
26769 }
26770
26771 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
26772 static SDValue
26773 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
26774                                   SmallVector<SDValue, 8> &Regs) {
26775   assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
26776                              Regs[0].getValueType() == MVT::v2i64));
26777   EVT OutVT = N->getValueType(0);
26778   EVT OutSVT = OutVT.getVectorElementType();
26779   EVT InVT = Regs[0].getValueType();
26780   EVT InSVT = InVT.getVectorElementType();
26781   SDLoc DL(N);
26782
26783   // First, use mask to unset all bits that won't appear in the result.
26784   assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
26785          "OutSVT can only be either i8 or i16.");
26786   SDValue MaskVal =
26787       DAG.getConstant(OutSVT == MVT::i8 ? 0xFF : 0xFFFF, DL, InSVT);
26788   SDValue MaskVec = DAG.getNode(
26789       ISD::BUILD_VECTOR, DL, InVT,
26790       SmallVector<SDValue, 8>(InVT.getVectorNumElements(), MaskVal));
26791   for (auto &Reg : Regs)
26792     Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVec, Reg);
26793
26794   MVT UnpackedVT, PackedVT;
26795   if (OutSVT == MVT::i8) {
26796     UnpackedVT = MVT::v8i16;
26797     PackedVT = MVT::v16i8;
26798   } else {
26799     UnpackedVT = MVT::v4i32;
26800     PackedVT = MVT::v8i16;
26801   }
26802
26803   // In each iteration, truncate the type by a half size.
26804   auto RegNum = Regs.size();
26805   for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
26806        j < e; j *= 2, RegNum /= 2) {
26807     for (unsigned i = 0; i < RegNum; i++)
26808       Regs[i] = DAG.getNode(ISD::BITCAST, DL, UnpackedVT, Regs[i]);
26809     for (unsigned i = 0; i < RegNum / 2; i++)
26810       Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
26811                             Regs[i * 2 + 1]);
26812   }
26813
26814   // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
26815   // then extract a subvector as the result since v8i8 is not a legal type.
26816   if (OutVT == MVT::v8i8) {
26817     Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
26818     Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
26819                           DAG.getIntPtrConstant(0, DL));
26820     return Regs[0];
26821   } else if (RegNum > 1) {
26822     Regs.resize(RegNum);
26823     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26824   } else
26825     return Regs[0];
26826 }
26827
26828 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
26829 static SDValue
26830 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
26831                                   SmallVector<SDValue, 8> &Regs) {
26832   assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
26833   EVT OutVT = N->getValueType(0);
26834   SDLoc DL(N);
26835
26836   // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
26837   SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
26838   for (auto &Reg : Regs) {
26839     Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26840     Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26841   }
26842
26843   for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
26844     Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
26845                           Regs[i * 2 + 1]);
26846
26847   if (Regs.size() > 2) {
26848     Regs.resize(Regs.size() / 2);
26849     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26850   } else
26851     return Regs[0];
26852 }
26853
26854 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
26855 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
26856 /// legalization the truncation will be translated into a BUILD_VECTOR with each
26857 /// element that is extracted from a vector and then truncated, and it is
26858 /// diffcult to do this optimization based on them.
26859 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
26860                                        const X86Subtarget *Subtarget) {
26861   EVT OutVT = N->getValueType(0);
26862   if (!OutVT.isVector())
26863     return SDValue();
26864
26865   SDValue In = N->getOperand(0);
26866   if (!In.getValueType().isSimple())
26867     return SDValue();
26868
26869   EVT InVT = In.getValueType();
26870   unsigned NumElems = OutVT.getVectorNumElements();
26871
26872   // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
26873   // SSE2, and we need to take care of it specially.
26874   // AVX512 provides vpmovdb.
26875   if (!Subtarget->hasSSE2() || Subtarget->hasAVX2())
26876     return SDValue();
26877
26878   EVT OutSVT = OutVT.getVectorElementType();
26879   EVT InSVT = InVT.getVectorElementType();
26880   if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
26881         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
26882         NumElems >= 8))
26883     return SDValue();
26884
26885   // SSSE3's pshufb results in less instructions in the cases below.
26886   if (Subtarget->hasSSSE3() && NumElems == 8 &&
26887       ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
26888        (InSVT == MVT::i32 && OutSVT == MVT::i16)))
26889     return SDValue();
26890
26891   SDLoc DL(N);
26892
26893   // Split a long vector into vectors of legal type.
26894   unsigned RegNum = InVT.getSizeInBits() / 128;
26895   SmallVector<SDValue, 8> SubVec(RegNum);
26896   if (InSVT == MVT::i32) {
26897     for (unsigned i = 0; i < RegNum; i++)
26898       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
26899                               DAG.getIntPtrConstant(i * 4, DL));
26900   } else {
26901     for (unsigned i = 0; i < RegNum; i++)
26902       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
26903                               DAG.getIntPtrConstant(i * 2, DL));
26904   }
26905
26906   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PAKCUS
26907   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
26908   // truncate 2 x v4i32 to v8i16.
26909   if (Subtarget->hasSSE41() || OutSVT == MVT::i8)
26910     return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
26911   else if (InSVT == MVT::i32)
26912     return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
26913   else
26914     return SDValue();
26915 }
26916
26917 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
26918                                       const X86Subtarget *Subtarget) {
26919   // Try to detect AVG pattern first.
26920   SDValue Avg = detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG,
26921                                  Subtarget, SDLoc(N));
26922   if (Avg.getNode())
26923     return Avg;
26924
26925   return combineVectorTruncation(N, DAG, Subtarget);
26926 }
26927
26928 /// Do target-specific dag combines on floating point negations.
26929 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
26930                                   const X86Subtarget *Subtarget) {
26931   EVT VT = N->getValueType(0);
26932   EVT SVT = VT.getScalarType();
26933   SDValue Arg = N->getOperand(0);
26934   SDLoc DL(N);
26935
26936   // Let legalize expand this if it isn't a legal type yet.
26937   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26938     return SDValue();
26939
26940   // If we're negating a FMUL node on a target with FMA, then we can avoid the
26941   // use of a constant by performing (-0 - A*B) instead.
26942   // FIXME: Check rounding control flags as well once it becomes available.
26943   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
26944       Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
26945     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
26946     return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26947                        Arg.getOperand(1), Zero);
26948   }
26949
26950   // If we're negating a FMA node, then we can adjust the
26951   // instruction to include the extra negation.
26952   if (Arg.hasOneUse()) {
26953     switch (Arg.getOpcode()) {
26954     case X86ISD::FMADD:
26955       return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26956                          Arg.getOperand(1), Arg.getOperand(2));
26957     case X86ISD::FMSUB:
26958       return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
26959                          Arg.getOperand(1), Arg.getOperand(2));
26960     case X86ISD::FNMADD:
26961       return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
26962                          Arg.getOperand(1), Arg.getOperand(2));
26963     case X86ISD::FNMSUB:
26964       return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
26965                          Arg.getOperand(1), Arg.getOperand(2));
26966     }
26967   }
26968   return SDValue();
26969 }
26970
26971 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
26972                               const X86Subtarget *Subtarget) {
26973   EVT VT = N->getValueType(0);
26974   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
26975     // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
26976     // These logic operations may be executed in the integer domain.
26977     SDLoc dl(N);
26978     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
26979     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
26980
26981     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
26982     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
26983     unsigned IntOpcode = 0;
26984     switch (N->getOpcode()) {
26985       default: llvm_unreachable("Unexpected FP logic op");
26986       case X86ISD::FOR: IntOpcode = ISD::OR; break;
26987       case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
26988       case X86ISD::FAND: IntOpcode = ISD::AND; break;
26989       case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
26990     }
26991     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
26992     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
26993   }
26994   return SDValue();
26995 }
26996 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
26997 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
26998                                  const X86Subtarget *Subtarget) {
26999   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
27000
27001   // F[X]OR(0.0, x) -> x
27002   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27003     if (C->getValueAPF().isPosZero())
27004       return N->getOperand(1);
27005
27006   // F[X]OR(x, 0.0) -> x
27007   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27008     if (C->getValueAPF().isPosZero())
27009       return N->getOperand(0);
27010
27011   return lowerX86FPLogicOp(N, DAG, Subtarget);
27012 }
27013
27014 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
27015 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
27016   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
27017
27018   // Only perform optimizations if UnsafeMath is used.
27019   if (!DAG.getTarget().Options.UnsafeFPMath)
27020     return SDValue();
27021
27022   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
27023   // into FMINC and FMAXC, which are Commutative operations.
27024   unsigned NewOp = 0;
27025   switch (N->getOpcode()) {
27026     default: llvm_unreachable("unknown opcode");
27027     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
27028     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
27029   }
27030
27031   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
27032                      N->getOperand(0), N->getOperand(1));
27033 }
27034
27035 static SDValue performFMinNumFMaxNumCombine(SDNode *N, SelectionDAG &DAG,
27036                                             const X86Subtarget *Subtarget) {
27037   if (Subtarget->useSoftFloat())
27038     return SDValue();
27039
27040   // TODO: Check for global or instruction-level "nnan". In that case, we
27041   //       should be able to lower to FMAX/FMIN alone.
27042   // TODO: If an operand is already known to be a NaN or not a NaN, this
27043   //       should be an optional swap and FMAX/FMIN.
27044
27045   EVT VT = N->getValueType(0);
27046   if (!((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
27047         (Subtarget->hasSSE2() && (VT == MVT::f64 || VT == MVT::v2f64)) ||
27048         (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))))
27049     return SDValue();
27050
27051   // This takes at least 3 instructions, so favor a library call when operating
27052   // on a scalar and minimizing code size.
27053   if (!VT.isVector() && DAG.getMachineFunction().getFunction()->optForMinSize())
27054     return SDValue();
27055
27056   SDValue Op0 = N->getOperand(0);
27057   SDValue Op1 = N->getOperand(1);
27058   SDLoc DL(N);
27059   EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
27060       DAG.getDataLayout(), *DAG.getContext(), VT);
27061
27062   // There are 4 possibilities involving NaN inputs, and these are the required
27063   // outputs:
27064   //                   Op1
27065   //               Num     NaN
27066   //            ----------------
27067   //       Num  |  Max  |  Op0 |
27068   // Op0        ----------------
27069   //       NaN  |  Op1  |  NaN |
27070   //            ----------------
27071   //
27072   // The SSE FP max/min instructions were not designed for this case, but rather
27073   // to implement:
27074   //   Min = Op1 < Op0 ? Op1 : Op0
27075   //   Max = Op1 > Op0 ? Op1 : Op0
27076   //
27077   // So they always return Op0 if either input is a NaN. However, we can still
27078   // use those instructions for fmaxnum by selecting away a NaN input.
27079
27080   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
27081   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
27082   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
27083   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
27084
27085   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
27086   // are NaN, the NaN value of Op1 is the result.
27087   auto SelectOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
27088   return DAG.getNode(SelectOpcode, DL, VT, IsOp0Nan, Op1, MinOrMax);
27089 }
27090
27091 /// Do target-specific dag combines on X86ISD::FAND nodes.
27092 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
27093                                   const X86Subtarget *Subtarget) {
27094   // FAND(0.0, x) -> 0.0
27095   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27096     if (C->getValueAPF().isPosZero())
27097       return N->getOperand(0);
27098
27099   // FAND(x, 0.0) -> 0.0
27100   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27101     if (C->getValueAPF().isPosZero())
27102       return N->getOperand(1);
27103
27104   return lowerX86FPLogicOp(N, DAG, Subtarget);
27105 }
27106
27107 /// Do target-specific dag combines on X86ISD::FANDN nodes
27108 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
27109                                    const X86Subtarget *Subtarget) {
27110   // FANDN(0.0, x) -> x
27111   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27112     if (C->getValueAPF().isPosZero())
27113       return N->getOperand(1);
27114
27115   // FANDN(x, 0.0) -> 0.0
27116   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27117     if (C->getValueAPF().isPosZero())
27118       return N->getOperand(1);
27119
27120   return lowerX86FPLogicOp(N, DAG, Subtarget);
27121 }
27122
27123 static SDValue PerformBTCombine(SDNode *N,
27124                                 SelectionDAG &DAG,
27125                                 TargetLowering::DAGCombinerInfo &DCI) {
27126   // BT ignores high bits in the bit index operand.
27127   SDValue Op1 = N->getOperand(1);
27128   if (Op1.hasOneUse()) {
27129     unsigned BitWidth = Op1.getValueSizeInBits();
27130     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
27131     APInt KnownZero, KnownOne;
27132     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
27133                                           !DCI.isBeforeLegalizeOps());
27134     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27135     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
27136         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
27137       DCI.CommitTargetLoweringOpt(TLO);
27138   }
27139   return SDValue();
27140 }
27141
27142 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
27143   SDValue Op = N->getOperand(0);
27144   if (Op.getOpcode() == ISD::BITCAST)
27145     Op = Op.getOperand(0);
27146   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
27147   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
27148       VT.getVectorElementType().getSizeInBits() ==
27149       OpVT.getVectorElementType().getSizeInBits()) {
27150     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
27151   }
27152   return SDValue();
27153 }
27154
27155 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
27156                                                const X86Subtarget *Subtarget) {
27157   EVT VT = N->getValueType(0);
27158   if (!VT.isVector())
27159     return SDValue();
27160
27161   SDValue N0 = N->getOperand(0);
27162   SDValue N1 = N->getOperand(1);
27163   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
27164   SDLoc dl(N);
27165
27166   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
27167   // both SSE and AVX2 since there is no sign-extended shift right
27168   // operation on a vector with 64-bit elements.
27169   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
27170   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
27171   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
27172       N0.getOpcode() == ISD::SIGN_EXTEND)) {
27173     SDValue N00 = N0.getOperand(0);
27174
27175     // EXTLOAD has a better solution on AVX2,
27176     // it may be replaced with X86ISD::VSEXT node.
27177     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
27178       if (!ISD::isNormalLoad(N00.getNode()))
27179         return SDValue();
27180
27181     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
27182         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
27183                                   N00, N1);
27184       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
27185     }
27186   }
27187   return SDValue();
27188 }
27189
27190 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
27191 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
27192 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
27193 /// eliminate extend, add, and shift instructions.
27194 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
27195                                        const X86Subtarget *Subtarget) {
27196   // TODO: This should be valid for other integer types.
27197   EVT VT = Sext->getValueType(0);
27198   if (VT != MVT::i64)
27199     return SDValue();
27200
27201   // We need an 'add nsw' feeding into the 'sext'.
27202   SDValue Add = Sext->getOperand(0);
27203   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
27204     return SDValue();
27205
27206   // Having a constant operand to the 'add' ensures that we are not increasing
27207   // the instruction count because the constant is extended for free below.
27208   // A constant operand can also become the displacement field of an LEA.
27209   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
27210   if (!AddOp1)
27211     return SDValue();
27212
27213   // Don't make the 'add' bigger if there's no hope of combining it with some
27214   // other 'add' or 'shl' instruction.
27215   // TODO: It may be profitable to generate simpler LEA instructions in place
27216   // of single 'add' instructions, but the cost model for selecting an LEA
27217   // currently has a high threshold.
27218   bool HasLEAPotential = false;
27219   for (auto *User : Sext->uses()) {
27220     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
27221       HasLEAPotential = true;
27222       break;
27223     }
27224   }
27225   if (!HasLEAPotential)
27226     return SDValue();
27227
27228   // Everything looks good, so pull the 'sext' ahead of the 'add'.
27229   int64_t AddConstant = AddOp1->getSExtValue();
27230   SDValue AddOp0 = Add.getOperand(0);
27231   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
27232   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
27233
27234   // The wider add is guaranteed to not wrap because both operands are
27235   // sign-extended.
27236   SDNodeFlags Flags;
27237   Flags.setNoSignedWrap(true);
27238   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
27239 }
27240
27241 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
27242                                   TargetLowering::DAGCombinerInfo &DCI,
27243                                   const X86Subtarget *Subtarget) {
27244   SDValue N0 = N->getOperand(0);
27245   EVT VT = N->getValueType(0);
27246   EVT SVT = VT.getScalarType();
27247   EVT InVT = N0.getValueType();
27248   EVT InSVT = InVT.getScalarType();
27249   SDLoc DL(N);
27250
27251   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
27252   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
27253   // This exposes the sext to the sdivrem lowering, so that it directly extends
27254   // from AH (which we otherwise need to do contortions to access).
27255   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
27256       InVT == MVT::i8 && VT == MVT::i32) {
27257     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27258     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
27259                             N0.getOperand(0), N0.getOperand(1));
27260     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27261     return R.getValue(1);
27262   }
27263
27264   if (!DCI.isBeforeLegalizeOps()) {
27265     if (InVT == MVT::i1) {
27266       SDValue Zero = DAG.getConstant(0, DL, VT);
27267       SDValue AllOnes =
27268         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
27269       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
27270     }
27271     return SDValue();
27272   }
27273
27274   if (VT.isVector() && Subtarget->hasSSE2()) {
27275     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
27276       EVT InVT = N.getValueType();
27277       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
27278                                    Size / InVT.getScalarSizeInBits());
27279       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
27280                                     DAG.getUNDEF(InVT));
27281       Opnds[0] = N;
27282       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
27283     };
27284
27285     // If target-size is less than 128-bits, extend to a type that would extend
27286     // to 128 bits, extend that and extract the original target vector.
27287     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
27288         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27289         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27290       unsigned Scale = 128 / VT.getSizeInBits();
27291       EVT ExVT =
27292           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
27293       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
27294       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
27295       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
27296                          DAG.getIntPtrConstant(0, DL));
27297     }
27298
27299     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
27300     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
27301     if (VT.getSizeInBits() == 128 &&
27302         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27303         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27304       SDValue ExOp = ExtendVecSize(DL, N0, 128);
27305       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
27306     }
27307
27308     // On pre-AVX2 targets, split into 128-bit nodes of
27309     // ISD::SIGN_EXTEND_VECTOR_INREG.
27310     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
27311         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27312         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27313       unsigned NumVecs = VT.getSizeInBits() / 128;
27314       unsigned NumSubElts = 128 / SVT.getSizeInBits();
27315       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
27316       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
27317
27318       SmallVector<SDValue, 8> Opnds;
27319       for (unsigned i = 0, Offset = 0; i != NumVecs;
27320            ++i, Offset += NumSubElts) {
27321         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
27322                                      DAG.getIntPtrConstant(Offset, DL));
27323         SrcVec = ExtendVecSize(DL, SrcVec, 128);
27324         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
27325         Opnds.push_back(SrcVec);
27326       }
27327       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
27328     }
27329   }
27330
27331   if (Subtarget->hasAVX() && VT.is256BitVector())
27332     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27333       return R;
27334
27335   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
27336     return NewAdd;
27337
27338   return SDValue();
27339 }
27340
27341 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
27342                                  const X86Subtarget* Subtarget) {
27343   SDLoc dl(N);
27344   EVT VT = N->getValueType(0);
27345
27346   // Let legalize expand this if it isn't a legal type yet.
27347   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27348     return SDValue();
27349
27350   EVT ScalarVT = VT.getScalarType();
27351   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
27352     return SDValue();
27353
27354   SDValue A = N->getOperand(0);
27355   SDValue B = N->getOperand(1);
27356   SDValue C = N->getOperand(2);
27357
27358   bool NegA = (A.getOpcode() == ISD::FNEG);
27359   bool NegB = (B.getOpcode() == ISD::FNEG);
27360   bool NegC = (C.getOpcode() == ISD::FNEG);
27361
27362   // Negative multiplication when NegA xor NegB
27363   bool NegMul = (NegA != NegB);
27364   if (NegA)
27365     A = A.getOperand(0);
27366   if (NegB)
27367     B = B.getOperand(0);
27368   if (NegC)
27369     C = C.getOperand(0);
27370
27371   unsigned Opcode;
27372   if (!NegMul)
27373     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
27374   else
27375     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
27376
27377   return DAG.getNode(Opcode, dl, VT, A, B, C);
27378 }
27379
27380 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
27381                                   TargetLowering::DAGCombinerInfo &DCI,
27382                                   const X86Subtarget *Subtarget) {
27383   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
27384   //           (and (i32 x86isd::setcc_carry), 1)
27385   // This eliminates the zext. This transformation is necessary because
27386   // ISD::SETCC is always legalized to i8.
27387   SDLoc dl(N);
27388   SDValue N0 = N->getOperand(0);
27389   EVT VT = N->getValueType(0);
27390
27391   if (N0.getOpcode() == ISD::AND &&
27392       N0.hasOneUse() &&
27393       N0.getOperand(0).hasOneUse()) {
27394     SDValue N00 = N0.getOperand(0);
27395     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27396       if (!isOneConstant(N0.getOperand(1)))
27397         return SDValue();
27398       return DAG.getNode(ISD::AND, dl, VT,
27399                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27400                                      N00.getOperand(0), N00.getOperand(1)),
27401                          DAG.getConstant(1, dl, VT));
27402     }
27403   }
27404
27405   if (N0.getOpcode() == ISD::TRUNCATE &&
27406       N0.hasOneUse() &&
27407       N0.getOperand(0).hasOneUse()) {
27408     SDValue N00 = N0.getOperand(0);
27409     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27410       return DAG.getNode(ISD::AND, dl, VT,
27411                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27412                                      N00.getOperand(0), N00.getOperand(1)),
27413                          DAG.getConstant(1, dl, VT));
27414     }
27415   }
27416
27417   if (VT.is256BitVector())
27418     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27419       return R;
27420
27421   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
27422   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
27423   // This exposes the zext to the udivrem lowering, so that it directly extends
27424   // from AH (which we otherwise need to do contortions to access).
27425   if (N0.getOpcode() == ISD::UDIVREM &&
27426       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
27427       (VT == MVT::i32 || VT == MVT::i64)) {
27428     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27429     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
27430                             N0.getOperand(0), N0.getOperand(1));
27431     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27432     return R.getValue(1);
27433   }
27434
27435   return SDValue();
27436 }
27437
27438 // Optimize x == -y --> x+y == 0
27439 //          x != -y --> x+y != 0
27440 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
27441                                       const X86Subtarget* Subtarget) {
27442   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
27443   SDValue LHS = N->getOperand(0);
27444   SDValue RHS = N->getOperand(1);
27445   EVT VT = N->getValueType(0);
27446   SDLoc DL(N);
27447
27448   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
27449     if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
27450       SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
27451                                  LHS.getOperand(1));
27452       return DAG.getSetCC(DL, N->getValueType(0), addV,
27453                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27454     }
27455   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
27456     if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
27457       SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
27458                                  RHS.getOperand(1));
27459       return DAG.getSetCC(DL, N->getValueType(0), addV,
27460                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27461     }
27462
27463   if (VT.getScalarType() == MVT::i1 &&
27464       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
27465     bool IsSEXT0 =
27466         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27467         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27468     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27469
27470     if (!IsSEXT0 || !IsVZero1) {
27471       // Swap the operands and update the condition code.
27472       std::swap(LHS, RHS);
27473       CC = ISD::getSetCCSwappedOperands(CC);
27474
27475       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27476                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27477       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27478     }
27479
27480     if (IsSEXT0 && IsVZero1) {
27481       assert(VT == LHS.getOperand(0).getValueType() &&
27482              "Uexpected operand type");
27483       if (CC == ISD::SETGT)
27484         return DAG.getConstant(0, DL, VT);
27485       if (CC == ISD::SETLE)
27486         return DAG.getConstant(1, DL, VT);
27487       if (CC == ISD::SETEQ || CC == ISD::SETGE)
27488         return DAG.getNOT(DL, LHS.getOperand(0), VT);
27489
27490       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
27491              "Unexpected condition code!");
27492       return LHS.getOperand(0);
27493     }
27494   }
27495
27496   return SDValue();
27497 }
27498
27499 static SDValue PerformGatherScatterCombine(SDNode *N, SelectionDAG &DAG) {
27500   SDLoc DL(N);
27501   // Gather and Scatter instructions use k-registers for masks. The type of
27502   // the masks is v*i1. So the mask will be truncated anyway.
27503   // The SIGN_EXTEND_INREG my be dropped.
27504   SDValue Mask = N->getOperand(2);
27505   if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
27506     SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
27507     NewOps[2] = Mask.getOperand(0);
27508     DAG.UpdateNodeOperands(N, NewOps);
27509   }
27510   return SDValue();
27511 }
27512
27513 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
27514 // as "sbb reg,reg", since it can be extended without zext and produces
27515 // an all-ones bit which is more useful than 0/1 in some cases.
27516 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
27517                                MVT VT) {
27518   if (VT == MVT::i8)
27519     return DAG.getNode(ISD::AND, DL, VT,
27520                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27521                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
27522                                    EFLAGS),
27523                        DAG.getConstant(1, DL, VT));
27524   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
27525   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
27526                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27527                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
27528                                  EFLAGS));
27529 }
27530
27531 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
27532 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
27533                                    TargetLowering::DAGCombinerInfo &DCI,
27534                                    const X86Subtarget *Subtarget) {
27535   SDLoc DL(N);
27536   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
27537   SDValue EFLAGS = N->getOperand(1);
27538
27539   if (CC == X86::COND_A) {
27540     // Try to convert COND_A into COND_B in an attempt to facilitate
27541     // materializing "setb reg".
27542     //
27543     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
27544     // cannot take an immediate as its first operand.
27545     //
27546     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
27547         EFLAGS.getValueType().isInteger() &&
27548         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
27549       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
27550                                    EFLAGS.getNode()->getVTList(),
27551                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
27552       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
27553       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
27554     }
27555   }
27556
27557   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
27558   // a zext and produces an all-ones bit which is more useful than 0/1 in some
27559   // cases.
27560   if (CC == X86::COND_B)
27561     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
27562
27563   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27564     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27565     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
27566   }
27567
27568   return SDValue();
27569 }
27570
27571 // Optimize branch condition evaluation.
27572 //
27573 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
27574                                     TargetLowering::DAGCombinerInfo &DCI,
27575                                     const X86Subtarget *Subtarget) {
27576   SDLoc DL(N);
27577   SDValue Chain = N->getOperand(0);
27578   SDValue Dest = N->getOperand(1);
27579   SDValue EFLAGS = N->getOperand(3);
27580   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
27581
27582   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27583     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27584     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
27585                        Flags);
27586   }
27587
27588   return SDValue();
27589 }
27590
27591 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
27592                                                          SelectionDAG &DAG) {
27593   // Take advantage of vector comparisons producing 0 or -1 in each lane to
27594   // optimize away operation when it's from a constant.
27595   //
27596   // The general transformation is:
27597   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
27598   //       AND(VECTOR_CMP(x,y), constant2)
27599   //    constant2 = UNARYOP(constant)
27600
27601   // Early exit if this isn't a vector operation, the operand of the
27602   // unary operation isn't a bitwise AND, or if the sizes of the operations
27603   // aren't the same.
27604   EVT VT = N->getValueType(0);
27605   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27606       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27607       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27608     return SDValue();
27609
27610   // Now check that the other operand of the AND is a constant. We could
27611   // make the transformation for non-constant splats as well, but it's unclear
27612   // that would be a benefit as it would not eliminate any operations, just
27613   // perform one more step in scalar code before moving to the vector unit.
27614   if (BuildVectorSDNode *BV =
27615           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27616     // Bail out if the vector isn't a constant.
27617     if (!BV->isConstant())
27618       return SDValue();
27619
27620     // Everything checks out. Build up the new and improved node.
27621     SDLoc DL(N);
27622     EVT IntVT = BV->getValueType(0);
27623     // Create a new constant of the appropriate type for the transformed
27624     // DAG.
27625     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27626     // The AND node needs bitcasts to/from an integer vector type around it.
27627     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27628     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27629                                  N->getOperand(0)->getOperand(0), MaskConst);
27630     SDValue Res = DAG.getBitcast(VT, NewAnd);
27631     return Res;
27632   }
27633
27634   return SDValue();
27635 }
27636
27637 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27638                                         const X86Subtarget *Subtarget) {
27639   SDValue Op0 = N->getOperand(0);
27640   EVT VT = N->getValueType(0);
27641   EVT InVT = Op0.getValueType();
27642   EVT InSVT = InVT.getScalarType();
27643   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27644
27645   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27646   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27647   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27648     SDLoc dl(N);
27649     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27650                                  InVT.getVectorNumElements());
27651     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27652
27653     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27654       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27655
27656     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27657   }
27658
27659   return SDValue();
27660 }
27661
27662 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27663                                         const X86Subtarget *Subtarget) {
27664   // First try to optimize away the conversion entirely when it's
27665   // conditionally from a constant. Vectors only.
27666   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27667     return Res;
27668
27669   // Now move on to more general possibilities.
27670   SDValue Op0 = N->getOperand(0);
27671   EVT VT = N->getValueType(0);
27672   EVT InVT = Op0.getValueType();
27673   EVT InSVT = InVT.getScalarType();
27674
27675   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27676   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27677   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27678     SDLoc dl(N);
27679     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27680                                  InVT.getVectorNumElements());
27681     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27682     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27683   }
27684
27685   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27686   // a 32-bit target where SSE doesn't support i64->FP operations.
27687   if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27688     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27689     EVT LdVT = Ld->getValueType(0);
27690
27691     // This transformation is not supported if the result type is f16
27692     if (VT == MVT::f16)
27693       return SDValue();
27694
27695     if (!Ld->isVolatile() && !VT.isVector() &&
27696         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27697         !Subtarget->is64Bit() && LdVT == MVT::i64) {
27698       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27699           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27700       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27701       return FILDChain;
27702     }
27703   }
27704   return SDValue();
27705 }
27706
27707 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27708 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27709                                  X86TargetLowering::DAGCombinerInfo &DCI) {
27710   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27711   // the result is either zero or one (depending on the input carry bit).
27712   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27713   if (X86::isZeroNode(N->getOperand(0)) &&
27714       X86::isZeroNode(N->getOperand(1)) &&
27715       // We don't have a good way to replace an EFLAGS use, so only do this when
27716       // dead right now.
27717       SDValue(N, 1).use_empty()) {
27718     SDLoc DL(N);
27719     EVT VT = N->getValueType(0);
27720     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27721     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27722                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27723                                            DAG.getConstant(X86::COND_B, DL,
27724                                                            MVT::i8),
27725                                            N->getOperand(2)),
27726                                DAG.getConstant(1, DL, VT));
27727     return DCI.CombineTo(N, Res1, CarryOut);
27728   }
27729
27730   return SDValue();
27731 }
27732
27733 // fold (add Y, (sete  X, 0)) -> adc  0, Y
27734 //      (add Y, (setne X, 0)) -> sbb -1, Y
27735 //      (sub (sete  X, 0), Y) -> sbb  0, Y
27736 //      (sub (setne X, 0), Y) -> adc -1, Y
27737 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27738   SDLoc DL(N);
27739
27740   // Look through ZExts.
27741   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27742   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27743     return SDValue();
27744
27745   SDValue SetCC = Ext.getOperand(0);
27746   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27747     return SDValue();
27748
27749   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27750   if (CC != X86::COND_E && CC != X86::COND_NE)
27751     return SDValue();
27752
27753   SDValue Cmp = SetCC.getOperand(1);
27754   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27755       !X86::isZeroNode(Cmp.getOperand(1)) ||
27756       !Cmp.getOperand(0).getValueType().isInteger())
27757     return SDValue();
27758
27759   SDValue CmpOp0 = Cmp.getOperand(0);
27760   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27761                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
27762
27763   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27764   if (CC == X86::COND_NE)
27765     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27766                        DL, OtherVal.getValueType(), OtherVal,
27767                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27768                        NewCmp);
27769   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27770                      DL, OtherVal.getValueType(), OtherVal,
27771                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27772 }
27773
27774 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27775 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27776                                  const X86Subtarget *Subtarget) {
27777   EVT VT = N->getValueType(0);
27778   SDValue Op0 = N->getOperand(0);
27779   SDValue Op1 = N->getOperand(1);
27780
27781   // Try to synthesize horizontal adds from adds of shuffles.
27782   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27783        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27784       isHorizontalBinOp(Op0, Op1, true))
27785     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27786
27787   return OptimizeConditionalInDecrement(N, DAG);
27788 }
27789
27790 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27791                                  const X86Subtarget *Subtarget) {
27792   SDValue Op0 = N->getOperand(0);
27793   SDValue Op1 = N->getOperand(1);
27794
27795   // X86 can't encode an immediate LHS of a sub. See if we can push the
27796   // negation into a preceding instruction.
27797   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27798     // If the RHS of the sub is a XOR with one use and a constant, invert the
27799     // immediate. Then add one to the LHS of the sub so we can turn
27800     // X-Y -> X+~Y+1, saving one register.
27801     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27802         isa<ConstantSDNode>(Op1.getOperand(1))) {
27803       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27804       EVT VT = Op0.getValueType();
27805       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27806                                    Op1.getOperand(0),
27807                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
27808       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27809                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27810     }
27811   }
27812
27813   // Try to synthesize horizontal adds from adds of shuffles.
27814   EVT VT = N->getValueType(0);
27815   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27816        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27817       isHorizontalBinOp(Op0, Op1, true))
27818     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27819
27820   return OptimizeConditionalInDecrement(N, DAG);
27821 }
27822
27823 /// performVZEXTCombine - Performs build vector combines
27824 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27825                                    TargetLowering::DAGCombinerInfo &DCI,
27826                                    const X86Subtarget *Subtarget) {
27827   SDLoc DL(N);
27828   MVT VT = N->getSimpleValueType(0);
27829   SDValue Op = N->getOperand(0);
27830   MVT OpVT = Op.getSimpleValueType();
27831   MVT OpEltVT = OpVT.getVectorElementType();
27832   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27833
27834   // (vzext (bitcast (vzext (x)) -> (vzext x)
27835   SDValue V = Op;
27836   while (V.getOpcode() == ISD::BITCAST)
27837     V = V.getOperand(0);
27838
27839   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27840     MVT InnerVT = V.getSimpleValueType();
27841     MVT InnerEltVT = InnerVT.getVectorElementType();
27842
27843     // If the element sizes match exactly, we can just do one larger vzext. This
27844     // is always an exact type match as vzext operates on integer types.
27845     if (OpEltVT == InnerEltVT) {
27846       assert(OpVT == InnerVT && "Types must match for vzext!");
27847       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27848     }
27849
27850     // The only other way we can combine them is if only a single element of the
27851     // inner vzext is used in the input to the outer vzext.
27852     if (InnerEltVT.getSizeInBits() < InputBits)
27853       return SDValue();
27854
27855     // In this case, the inner vzext is completely dead because we're going to
27856     // only look at bits inside of the low element. Just do the outer vzext on
27857     // a bitcast of the input to the inner.
27858     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27859   }
27860
27861   // Check if we can bypass extracting and re-inserting an element of an input
27862   // vector. Essentially:
27863   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27864   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27865       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27866       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27867     SDValue ExtractedV = V.getOperand(0);
27868     SDValue OrigV = ExtractedV.getOperand(0);
27869     if (isNullConstant(ExtractedV.getOperand(1))) {
27870         MVT OrigVT = OrigV.getSimpleValueType();
27871         // Extract a subvector if necessary...
27872         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27873           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27874           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
27875                                     OrigVT.getVectorNumElements() / Ratio);
27876           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
27877                               DAG.getIntPtrConstant(0, DL));
27878         }
27879         Op = DAG.getBitcast(OpVT, OrigV);
27880         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
27881       }
27882   }
27883
27884   return SDValue();
27885 }
27886
27887 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
27888                                              DAGCombinerInfo &DCI) const {
27889   SelectionDAG &DAG = DCI.DAG;
27890   switch (N->getOpcode()) {
27891   default: break;
27892   case ISD::EXTRACT_VECTOR_ELT:
27893     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
27894   case ISD::VSELECT:
27895   case ISD::SELECT:
27896   case X86ISD::SHRUNKBLEND:
27897     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
27898   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
27899   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
27900   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
27901   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
27902   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
27903   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
27904   case ISD::SHL:
27905   case ISD::SRA:
27906   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
27907   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
27908   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
27909   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
27910   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
27911   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
27912   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
27913   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
27914   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
27915   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
27916   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
27917   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
27918   case ISD::FNEG:           return PerformFNEGCombine(N, DAG, Subtarget);
27919   case ISD::TRUNCATE:       return PerformTRUNCATECombine(N, DAG, Subtarget);
27920   case X86ISD::FXOR:
27921   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
27922   case X86ISD::FMIN:
27923   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
27924   case ISD::FMINNUM:
27925   case ISD::FMAXNUM:        return performFMinNumFMaxNumCombine(N, DAG,
27926                                                                 Subtarget);
27927   case X86ISD::FAND:        return PerformFANDCombine(N, DAG, Subtarget);
27928   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG, Subtarget);
27929   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
27930   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
27931   case ISD::ANY_EXTEND:
27932   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
27933   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
27934   case ISD::SIGN_EXTEND_INREG:
27935     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
27936   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
27937   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
27938   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
27939   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
27940   case X86ISD::SHUFP:       // Handle all target specific shuffles
27941   case X86ISD::PALIGNR:
27942   case X86ISD::BLENDI:
27943   case X86ISD::UNPCKH:
27944   case X86ISD::UNPCKL:
27945   case X86ISD::MOVHLPS:
27946   case X86ISD::MOVLHPS:
27947   case X86ISD::PSHUFB:
27948   case X86ISD::PSHUFD:
27949   case X86ISD::PSHUFHW:
27950   case X86ISD::PSHUFLW:
27951   case X86ISD::MOVSS:
27952   case X86ISD::MOVSD:
27953   case X86ISD::VPERMILPI:
27954   case X86ISD::VPERM2X128:
27955   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
27956   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
27957   case ISD::MGATHER:
27958   case ISD::MSCATTER:       return PerformGatherScatterCombine(N, DAG);
27959   }
27960
27961   return SDValue();
27962 }
27963
27964 /// isTypeDesirableForOp - Return true if the target has native support for
27965 /// the specified value type and it is 'desirable' to use the type for the
27966 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
27967 /// instruction encodings are longer and some i16 instructions are slow.
27968 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
27969   if (!isTypeLegal(VT))
27970     return false;
27971   if (VT != MVT::i16)
27972     return true;
27973
27974   switch (Opc) {
27975   default:
27976     return true;
27977   case ISD::LOAD:
27978   case ISD::SIGN_EXTEND:
27979   case ISD::ZERO_EXTEND:
27980   case ISD::ANY_EXTEND:
27981   case ISD::SHL:
27982   case ISD::SRL:
27983   case ISD::SUB:
27984   case ISD::ADD:
27985   case ISD::MUL:
27986   case ISD::AND:
27987   case ISD::OR:
27988   case ISD::XOR:
27989     return false;
27990   }
27991 }
27992
27993 /// This function checks if any of the users of EFLAGS copies the EFLAGS. We
27994 /// know that the code that lowers COPY of EFLAGS has to use the stack, and if
27995 /// we don't adjust the stack we clobber the first frame index.
27996 /// See X86InstrInfo::copyPhysReg.
27997 bool X86TargetLowering::hasCopyImplyingStackAdjustment(
27998     MachineFunction *MF) const {
27999   const MachineRegisterInfo &MRI = MF->getRegInfo();
28000
28001   return any_of(MRI.reg_instructions(X86::EFLAGS),
28002                 [](const MachineInstr &RI) { return RI.isCopy(); });
28003 }
28004
28005 /// IsDesirableToPromoteOp - This method query the target whether it is
28006 /// beneficial for dag combiner to promote the specified node. If true, it
28007 /// should return the desired promotion type by reference.
28008 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
28009   EVT VT = Op.getValueType();
28010   if (VT != MVT::i16)
28011     return false;
28012
28013   bool Promote = false;
28014   bool Commute = false;
28015   switch (Op.getOpcode()) {
28016   default: break;
28017   case ISD::LOAD: {
28018     LoadSDNode *LD = cast<LoadSDNode>(Op);
28019     // If the non-extending load has a single use and it's not live out, then it
28020     // might be folded.
28021     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
28022                                                      Op.hasOneUse()*/) {
28023       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
28024              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
28025         // The only case where we'd want to promote LOAD (rather then it being
28026         // promoted as an operand is when it's only use is liveout.
28027         if (UI->getOpcode() != ISD::CopyToReg)
28028           return false;
28029       }
28030     }
28031     Promote = true;
28032     break;
28033   }
28034   case ISD::SIGN_EXTEND:
28035   case ISD::ZERO_EXTEND:
28036   case ISD::ANY_EXTEND:
28037     Promote = true;
28038     break;
28039   case ISD::SHL:
28040   case ISD::SRL: {
28041     SDValue N0 = Op.getOperand(0);
28042     // Look out for (store (shl (load), x)).
28043     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
28044       return false;
28045     Promote = true;
28046     break;
28047   }
28048   case ISD::ADD:
28049   case ISD::MUL:
28050   case ISD::AND:
28051   case ISD::OR:
28052   case ISD::XOR:
28053     Commute = true;
28054     // fallthrough
28055   case ISD::SUB: {
28056     SDValue N0 = Op.getOperand(0);
28057     SDValue N1 = Op.getOperand(1);
28058     if (!Commute && MayFoldLoad(N1))
28059       return false;
28060     // Avoid disabling potential load folding opportunities.
28061     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
28062       return false;
28063     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
28064       return false;
28065     Promote = true;
28066   }
28067   }
28068
28069   PVT = MVT::i32;
28070   return Promote;
28071 }
28072
28073 //===----------------------------------------------------------------------===//
28074 //                           X86 Inline Assembly Support
28075 //===----------------------------------------------------------------------===//
28076
28077 // Helper to match a string separated by whitespace.
28078 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
28079   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
28080
28081   for (StringRef Piece : Pieces) {
28082     if (!S.startswith(Piece)) // Check if the piece matches.
28083       return false;
28084
28085     S = S.substr(Piece.size());
28086     StringRef::size_type Pos = S.find_first_not_of(" \t");
28087     if (Pos == 0) // We matched a prefix.
28088       return false;
28089
28090     S = S.substr(Pos);
28091   }
28092
28093   return S.empty();
28094 }
28095
28096 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
28097
28098   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
28099     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
28100         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
28101         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
28102
28103       if (AsmPieces.size() == 3)
28104         return true;
28105       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
28106         return true;
28107     }
28108   }
28109   return false;
28110 }
28111
28112 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
28113   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
28114
28115   std::string AsmStr = IA->getAsmString();
28116
28117   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
28118   if (!Ty || Ty->getBitWidth() % 16 != 0)
28119     return false;
28120
28121   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
28122   SmallVector<StringRef, 4> AsmPieces;
28123   SplitString(AsmStr, AsmPieces, ";\n");
28124
28125   switch (AsmPieces.size()) {
28126   default: return false;
28127   case 1:
28128     // FIXME: this should verify that we are targeting a 486 or better.  If not,
28129     // we will turn this bswap into something that will be lowered to logical
28130     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
28131     // lower so don't worry about this.
28132     // bswap $0
28133     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
28134         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
28135         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
28136         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
28137         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
28138         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
28139       // No need to check constraints, nothing other than the equivalent of
28140       // "=r,0" would be valid here.
28141       return IntrinsicLowering::LowerToByteSwap(CI);
28142     }
28143
28144     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
28145     if (CI->getType()->isIntegerTy(16) &&
28146         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28147         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
28148          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
28149       AsmPieces.clear();
28150       StringRef ConstraintsStr = IA->getConstraintString();
28151       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28152       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28153       if (clobbersFlagRegisters(AsmPieces))
28154         return IntrinsicLowering::LowerToByteSwap(CI);
28155     }
28156     break;
28157   case 3:
28158     if (CI->getType()->isIntegerTy(32) &&
28159         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28160         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
28161         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
28162         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
28163       AsmPieces.clear();
28164       StringRef ConstraintsStr = IA->getConstraintString();
28165       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28166       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28167       if (clobbersFlagRegisters(AsmPieces))
28168         return IntrinsicLowering::LowerToByteSwap(CI);
28169     }
28170
28171     if (CI->getType()->isIntegerTy(64)) {
28172       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
28173       if (Constraints.size() >= 2 &&
28174           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
28175           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
28176         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
28177         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
28178             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
28179             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
28180           return IntrinsicLowering::LowerToByteSwap(CI);
28181       }
28182     }
28183     break;
28184   }
28185   return false;
28186 }
28187
28188 /// getConstraintType - Given a constraint letter, return the type of
28189 /// constraint it is for this target.
28190 X86TargetLowering::ConstraintType
28191 X86TargetLowering::getConstraintType(StringRef Constraint) const {
28192   if (Constraint.size() == 1) {
28193     switch (Constraint[0]) {
28194     case 'R':
28195     case 'q':
28196     case 'Q':
28197     case 'f':
28198     case 't':
28199     case 'u':
28200     case 'y':
28201     case 'x':
28202     case 'Y':
28203     case 'l':
28204       return C_RegisterClass;
28205     case 'a':
28206     case 'b':
28207     case 'c':
28208     case 'd':
28209     case 'S':
28210     case 'D':
28211     case 'A':
28212       return C_Register;
28213     case 'I':
28214     case 'J':
28215     case 'K':
28216     case 'L':
28217     case 'M':
28218     case 'N':
28219     case 'G':
28220     case 'C':
28221     case 'e':
28222     case 'Z':
28223       return C_Other;
28224     default:
28225       break;
28226     }
28227   }
28228   return TargetLowering::getConstraintType(Constraint);
28229 }
28230
28231 /// Examine constraint type and operand type and determine a weight value.
28232 /// This object must already have been set up with the operand type
28233 /// and the current alternative constraint selected.
28234 TargetLowering::ConstraintWeight
28235   X86TargetLowering::getSingleConstraintMatchWeight(
28236     AsmOperandInfo &info, const char *constraint) const {
28237   ConstraintWeight weight = CW_Invalid;
28238   Value *CallOperandVal = info.CallOperandVal;
28239     // If we don't have a value, we can't do a match,
28240     // but allow it at the lowest weight.
28241   if (!CallOperandVal)
28242     return CW_Default;
28243   Type *type = CallOperandVal->getType();
28244   // Look at the constraint type.
28245   switch (*constraint) {
28246   default:
28247     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
28248   case 'R':
28249   case 'q':
28250   case 'Q':
28251   case 'a':
28252   case 'b':
28253   case 'c':
28254   case 'd':
28255   case 'S':
28256   case 'D':
28257   case 'A':
28258     if (CallOperandVal->getType()->isIntegerTy())
28259       weight = CW_SpecificReg;
28260     break;
28261   case 'f':
28262   case 't':
28263   case 'u':
28264     if (type->isFloatingPointTy())
28265       weight = CW_SpecificReg;
28266     break;
28267   case 'y':
28268     if (type->isX86_MMXTy() && Subtarget->hasMMX())
28269       weight = CW_SpecificReg;
28270     break;
28271   case 'x':
28272   case 'Y':
28273     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
28274         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
28275       weight = CW_Register;
28276     break;
28277   case 'I':
28278     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
28279       if (C->getZExtValue() <= 31)
28280         weight = CW_Constant;
28281     }
28282     break;
28283   case 'J':
28284     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28285       if (C->getZExtValue() <= 63)
28286         weight = CW_Constant;
28287     }
28288     break;
28289   case 'K':
28290     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28291       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
28292         weight = CW_Constant;
28293     }
28294     break;
28295   case 'L':
28296     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28297       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
28298         weight = CW_Constant;
28299     }
28300     break;
28301   case 'M':
28302     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28303       if (C->getZExtValue() <= 3)
28304         weight = CW_Constant;
28305     }
28306     break;
28307   case 'N':
28308     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28309       if (C->getZExtValue() <= 0xff)
28310         weight = CW_Constant;
28311     }
28312     break;
28313   case 'G':
28314   case 'C':
28315     if (isa<ConstantFP>(CallOperandVal)) {
28316       weight = CW_Constant;
28317     }
28318     break;
28319   case 'e':
28320     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28321       if ((C->getSExtValue() >= -0x80000000LL) &&
28322           (C->getSExtValue() <= 0x7fffffffLL))
28323         weight = CW_Constant;
28324     }
28325     break;
28326   case 'Z':
28327     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28328       if (C->getZExtValue() <= 0xffffffff)
28329         weight = CW_Constant;
28330     }
28331     break;
28332   }
28333   return weight;
28334 }
28335
28336 /// LowerXConstraint - try to replace an X constraint, which matches anything,
28337 /// with another that has more specific requirements based on the type of the
28338 /// corresponding operand.
28339 const char *X86TargetLowering::
28340 LowerXConstraint(EVT ConstraintVT) const {
28341   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
28342   // 'f' like normal targets.
28343   if (ConstraintVT.isFloatingPoint()) {
28344     if (Subtarget->hasSSE2())
28345       return "Y";
28346     if (Subtarget->hasSSE1())
28347       return "x";
28348   }
28349
28350   return TargetLowering::LowerXConstraint(ConstraintVT);
28351 }
28352
28353 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
28354 /// vector.  If it is invalid, don't add anything to Ops.
28355 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
28356                                                      std::string &Constraint,
28357                                                      std::vector<SDValue>&Ops,
28358                                                      SelectionDAG &DAG) const {
28359   SDValue Result;
28360
28361   // Only support length 1 constraints for now.
28362   if (Constraint.length() > 1) return;
28363
28364   char ConstraintLetter = Constraint[0];
28365   switch (ConstraintLetter) {
28366   default: break;
28367   case 'I':
28368     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28369       if (C->getZExtValue() <= 31) {
28370         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28371                                        Op.getValueType());
28372         break;
28373       }
28374     }
28375     return;
28376   case 'J':
28377     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28378       if (C->getZExtValue() <= 63) {
28379         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28380                                        Op.getValueType());
28381         break;
28382       }
28383     }
28384     return;
28385   case 'K':
28386     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28387       if (isInt<8>(C->getSExtValue())) {
28388         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28389                                        Op.getValueType());
28390         break;
28391       }
28392     }
28393     return;
28394   case 'L':
28395     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28396       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
28397           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
28398         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
28399                                        Op.getValueType());
28400         break;
28401       }
28402     }
28403     return;
28404   case 'M':
28405     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28406       if (C->getZExtValue() <= 3) {
28407         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28408                                        Op.getValueType());
28409         break;
28410       }
28411     }
28412     return;
28413   case 'N':
28414     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28415       if (C->getZExtValue() <= 255) {
28416         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28417                                        Op.getValueType());
28418         break;
28419       }
28420     }
28421     return;
28422   case 'O':
28423     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28424       if (C->getZExtValue() <= 127) {
28425         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28426                                        Op.getValueType());
28427         break;
28428       }
28429     }
28430     return;
28431   case 'e': {
28432     // 32-bit signed value
28433     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28434       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28435                                            C->getSExtValue())) {
28436         // Widen to 64 bits here to get it sign extended.
28437         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
28438         break;
28439       }
28440     // FIXME gcc accepts some relocatable values here too, but only in certain
28441     // memory models; it's complicated.
28442     }
28443     return;
28444   }
28445   case 'Z': {
28446     // 32-bit unsigned value
28447     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28448       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28449                                            C->getZExtValue())) {
28450         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28451                                        Op.getValueType());
28452         break;
28453       }
28454     }
28455     // FIXME gcc accepts some relocatable values here too, but only in certain
28456     // memory models; it's complicated.
28457     return;
28458   }
28459   case 'i': {
28460     // Literal immediates are always ok.
28461     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
28462       // Widen to 64 bits here to get it sign extended.
28463       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
28464       break;
28465     }
28466
28467     // In any sort of PIC mode addresses need to be computed at runtime by
28468     // adding in a register or some sort of table lookup.  These can't
28469     // be used as immediates.
28470     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
28471       return;
28472
28473     // If we are in non-pic codegen mode, we allow the address of a global (with
28474     // an optional displacement) to be used with 'i'.
28475     GlobalAddressSDNode *GA = nullptr;
28476     int64_t Offset = 0;
28477
28478     // Match either (GA), (GA+C), (GA+C1+C2), etc.
28479     while (1) {
28480       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
28481         Offset += GA->getOffset();
28482         break;
28483       } else if (Op.getOpcode() == ISD::ADD) {
28484         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28485           Offset += C->getZExtValue();
28486           Op = Op.getOperand(0);
28487           continue;
28488         }
28489       } else if (Op.getOpcode() == ISD::SUB) {
28490         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28491           Offset += -C->getZExtValue();
28492           Op = Op.getOperand(0);
28493           continue;
28494         }
28495       }
28496
28497       // Otherwise, this isn't something we can handle, reject it.
28498       return;
28499     }
28500
28501     const GlobalValue *GV = GA->getGlobal();
28502     // If we require an extra load to get this address, as in PIC mode, we
28503     // can't accept it.
28504     if (isGlobalStubReference(
28505             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
28506       return;
28507
28508     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
28509                                         GA->getValueType(0), Offset);
28510     break;
28511   }
28512   }
28513
28514   if (Result.getNode()) {
28515     Ops.push_back(Result);
28516     return;
28517   }
28518   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
28519 }
28520
28521 std::pair<unsigned, const TargetRegisterClass *>
28522 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
28523                                                 StringRef Constraint,
28524                                                 MVT VT) const {
28525   // First, see if this is a constraint that directly corresponds to an LLVM
28526   // register class.
28527   if (Constraint.size() == 1) {
28528     // GCC Constraint Letters
28529     switch (Constraint[0]) {
28530     default: break;
28531       // TODO: Slight differences here in allocation order and leaving
28532       // RIP in the class. Do they matter any more here than they do
28533       // in the normal allocation?
28534     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
28535       if (Subtarget->is64Bit()) {
28536         if (VT == MVT::i32 || VT == MVT::f32)
28537           return std::make_pair(0U, &X86::GR32RegClass);
28538         if (VT == MVT::i16)
28539           return std::make_pair(0U, &X86::GR16RegClass);
28540         if (VT == MVT::i8 || VT == MVT::i1)
28541           return std::make_pair(0U, &X86::GR8RegClass);
28542         if (VT == MVT::i64 || VT == MVT::f64)
28543           return std::make_pair(0U, &X86::GR64RegClass);
28544         break;
28545       }
28546       // 32-bit fallthrough
28547     case 'Q':   // Q_REGS
28548       if (VT == MVT::i32 || VT == MVT::f32)
28549         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
28550       if (VT == MVT::i16)
28551         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
28552       if (VT == MVT::i8 || VT == MVT::i1)
28553         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
28554       if (VT == MVT::i64)
28555         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
28556       break;
28557     case 'r':   // GENERAL_REGS
28558     case 'l':   // INDEX_REGS
28559       if (VT == MVT::i8 || VT == MVT::i1)
28560         return std::make_pair(0U, &X86::GR8RegClass);
28561       if (VT == MVT::i16)
28562         return std::make_pair(0U, &X86::GR16RegClass);
28563       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
28564         return std::make_pair(0U, &X86::GR32RegClass);
28565       return std::make_pair(0U, &X86::GR64RegClass);
28566     case 'R':   // LEGACY_REGS
28567       if (VT == MVT::i8 || VT == MVT::i1)
28568         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
28569       if (VT == MVT::i16)
28570         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
28571       if (VT == MVT::i32 || !Subtarget->is64Bit())
28572         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
28573       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
28574     case 'f':  // FP Stack registers.
28575       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
28576       // value to the correct fpstack register class.
28577       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
28578         return std::make_pair(0U, &X86::RFP32RegClass);
28579       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
28580         return std::make_pair(0U, &X86::RFP64RegClass);
28581       return std::make_pair(0U, &X86::RFP80RegClass);
28582     case 'y':   // MMX_REGS if MMX allowed.
28583       if (!Subtarget->hasMMX()) break;
28584       return std::make_pair(0U, &X86::VR64RegClass);
28585     case 'Y':   // SSE_REGS if SSE2 allowed
28586       if (!Subtarget->hasSSE2()) break;
28587       // FALL THROUGH.
28588     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
28589       if (!Subtarget->hasSSE1()) break;
28590
28591       switch (VT.SimpleTy) {
28592       default: break;
28593       // Scalar SSE types.
28594       case MVT::f32:
28595       case MVT::i32:
28596         return std::make_pair(0U, &X86::FR32RegClass);
28597       case MVT::f64:
28598       case MVT::i64:
28599         return std::make_pair(0U, &X86::FR64RegClass);
28600       // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28601       // Vector types.
28602       case MVT::v16i8:
28603       case MVT::v8i16:
28604       case MVT::v4i32:
28605       case MVT::v2i64:
28606       case MVT::v4f32:
28607       case MVT::v2f64:
28608         return std::make_pair(0U, &X86::VR128RegClass);
28609       // AVX types.
28610       case MVT::v32i8:
28611       case MVT::v16i16:
28612       case MVT::v8i32:
28613       case MVT::v4i64:
28614       case MVT::v8f32:
28615       case MVT::v4f64:
28616         return std::make_pair(0U, &X86::VR256RegClass);
28617       case MVT::v8f64:
28618       case MVT::v16f32:
28619       case MVT::v16i32:
28620       case MVT::v8i64:
28621         return std::make_pair(0U, &X86::VR512RegClass);
28622       }
28623       break;
28624     }
28625   }
28626
28627   // Use the default implementation in TargetLowering to convert the register
28628   // constraint into a member of a register class.
28629   std::pair<unsigned, const TargetRegisterClass*> Res;
28630   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28631
28632   // Not found as a standard register?
28633   if (!Res.second) {
28634     // Map st(0) -> st(7) -> ST0
28635     if (Constraint.size() == 7 && Constraint[0] == '{' &&
28636         tolower(Constraint[1]) == 's' &&
28637         tolower(Constraint[2]) == 't' &&
28638         Constraint[3] == '(' &&
28639         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28640         Constraint[5] == ')' &&
28641         Constraint[6] == '}') {
28642
28643       Res.first = X86::FP0+Constraint[4]-'0';
28644       Res.second = &X86::RFP80RegClass;
28645       return Res;
28646     }
28647
28648     // GCC allows "st(0)" to be called just plain "st".
28649     if (StringRef("{st}").equals_lower(Constraint)) {
28650       Res.first = X86::FP0;
28651       Res.second = &X86::RFP80RegClass;
28652       return Res;
28653     }
28654
28655     // flags -> EFLAGS
28656     if (StringRef("{flags}").equals_lower(Constraint)) {
28657       Res.first = X86::EFLAGS;
28658       Res.second = &X86::CCRRegClass;
28659       return Res;
28660     }
28661
28662     // 'A' means EAX + EDX.
28663     if (Constraint == "A") {
28664       Res.first = X86::EAX;
28665       Res.second = &X86::GR32_ADRegClass;
28666       return Res;
28667     }
28668     return Res;
28669   }
28670
28671   // Otherwise, check to see if this is a register class of the wrong value
28672   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28673   // turn into {ax},{dx}.
28674   // MVT::Other is used to specify clobber names.
28675   if (Res.second->hasType(VT) || VT == MVT::Other)
28676     return Res;   // Correct type already, nothing to do.
28677
28678   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28679   // return "eax". This should even work for things like getting 64bit integer
28680   // registers when given an f64 type.
28681   const TargetRegisterClass *Class = Res.second;
28682   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28683       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28684     unsigned Size = VT.getSizeInBits();
28685     if (Size == 1) Size = 8;
28686     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
28687     if (DestReg > 0) {
28688       Res.first = DestReg;
28689       Res.second = Size == 8 ? &X86::GR8RegClass
28690                  : Size == 16 ? &X86::GR16RegClass
28691                  : Size == 32 ? &X86::GR32RegClass
28692                  : &X86::GR64RegClass;
28693       assert(Res.second->contains(Res.first) && "Register in register class");
28694     } else {
28695       // No register found/type mismatch.
28696       Res.first = 0;
28697       Res.second = nullptr;
28698     }
28699   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28700              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28701              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28702              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28703              Class == &X86::VR512RegClass) {
28704     // Handle references to XMM physical registers that got mapped into the
28705     // wrong class.  This can happen with constraints like {xmm0} where the
28706     // target independent register mapper will just pick the first match it can
28707     // find, ignoring the required type.
28708
28709     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28710     if (VT == MVT::f32 || VT == MVT::i32)
28711       Res.second = &X86::FR32RegClass;
28712     else if (VT == MVT::f64 || VT == MVT::i64)
28713       Res.second = &X86::FR64RegClass;
28714     else if (X86::VR128RegClass.hasType(VT))
28715       Res.second = &X86::VR128RegClass;
28716     else if (X86::VR256RegClass.hasType(VT))
28717       Res.second = &X86::VR256RegClass;
28718     else if (X86::VR512RegClass.hasType(VT))
28719       Res.second = &X86::VR512RegClass;
28720     else {
28721       // Type mismatch and not a clobber: Return an error;
28722       Res.first = 0;
28723       Res.second = nullptr;
28724     }
28725   }
28726
28727   return Res;
28728 }
28729
28730 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28731                                             const AddrMode &AM, Type *Ty,
28732                                             unsigned AS) const {
28733   // Scaling factors are not free at all.
28734   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28735   // will take 2 allocations in the out of order engine instead of 1
28736   // for plain addressing mode, i.e. inst (reg1).
28737   // E.g.,
28738   // vaddps (%rsi,%drx), %ymm0, %ymm1
28739   // Requires two allocations (one for the load, one for the computation)
28740   // whereas:
28741   // vaddps (%rsi), %ymm0, %ymm1
28742   // Requires just 1 allocation, i.e., freeing allocations for other operations
28743   // and having less micro operations to execute.
28744   //
28745   // For some X86 architectures, this is even worse because for instance for
28746   // stores, the complex addressing mode forces the instruction to use the
28747   // "load" ports instead of the dedicated "store" port.
28748   // E.g., on Haswell:
28749   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28750   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28751   if (isLegalAddressingMode(DL, AM, Ty, AS))
28752     // Scale represents reg2 * scale, thus account for 1
28753     // as soon as we use a second register.
28754     return AM.Scale != 0;
28755   return -1;
28756 }
28757
28758 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28759   // Integer division on x86 is expensive. However, when aggressively optimizing
28760   // for code size, we prefer to use a div instruction, as it is usually smaller
28761   // than the alternative sequence.
28762   // The exception to this is vector division. Since x86 doesn't have vector
28763   // integer division, leaving the division as-is is a loss even in terms of
28764   // size, because it will have to be scalarized, while the alternative code
28765   // sequence can be performed in vector form.
28766   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28767                                    Attribute::MinSize);
28768   return OptSize && !VT.isVector();
28769 }