[X86][SSE} Add INSERTPS as a target shuffle
[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::INSERTPS:
3911   case X86ISD::PALIGNR:
3912   case X86ISD::MOVLHPS:
3913   case X86ISD::MOVLHPD:
3914   case X86ISD::MOVHLPS:
3915   case X86ISD::MOVLPS:
3916   case X86ISD::MOVLPD:
3917   case X86ISD::MOVSHDUP:
3918   case X86ISD::MOVSLDUP:
3919   case X86ISD::MOVDDUP:
3920   case X86ISD::MOVSS:
3921   case X86ISD::MOVSD:
3922   case X86ISD::UNPCKL:
3923   case X86ISD::UNPCKH:
3924   case X86ISD::VPERMILPI:
3925   case X86ISD::VPERM2X128:
3926   case X86ISD::VPERMI:
3927   case X86ISD::VPERMV:
3928   case X86ISD::VPERMV3:
3929     return true;
3930   }
3931 }
3932
3933 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3934                                     SDValue V1, unsigned TargetMask,
3935                                     SelectionDAG &DAG) {
3936   switch(Opc) {
3937   default: llvm_unreachable("Unknown x86 shuffle node");
3938   case X86ISD::PSHUFD:
3939   case X86ISD::PSHUFHW:
3940   case X86ISD::PSHUFLW:
3941   case X86ISD::VPERMILPI:
3942   case X86ISD::VPERMI:
3943     return DAG.getNode(Opc, dl, VT, V1,
3944                        DAG.getConstant(TargetMask, dl, MVT::i8));
3945   }
3946 }
3947
3948 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3949                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3950   switch(Opc) {
3951   default: llvm_unreachable("Unknown x86 shuffle node");
3952   case X86ISD::MOVLHPS:
3953   case X86ISD::MOVLHPD:
3954   case X86ISD::MOVHLPS:
3955   case X86ISD::MOVLPS:
3956   case X86ISD::MOVLPD:
3957   case X86ISD::MOVSS:
3958   case X86ISD::MOVSD:
3959   case X86ISD::UNPCKL:
3960   case X86ISD::UNPCKH:
3961     return DAG.getNode(Opc, dl, VT, V1, V2);
3962   }
3963 }
3964
3965 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3966   MachineFunction &MF = DAG.getMachineFunction();
3967   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3968   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3969   int ReturnAddrIndex = FuncInfo->getRAIndex();
3970
3971   if (ReturnAddrIndex == 0) {
3972     // Set up a frame object for the return address.
3973     unsigned SlotSize = RegInfo->getSlotSize();
3974     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3975                                                            -(int64_t)SlotSize,
3976                                                            false);
3977     FuncInfo->setRAIndex(ReturnAddrIndex);
3978   }
3979
3980   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3981 }
3982
3983 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3984                                        bool hasSymbolicDisplacement) {
3985   // Offset should fit into 32 bit immediate field.
3986   if (!isInt<32>(Offset))
3987     return false;
3988
3989   // If we don't have a symbolic displacement - we don't have any extra
3990   // restrictions.
3991   if (!hasSymbolicDisplacement)
3992     return true;
3993
3994   // FIXME: Some tweaks might be needed for medium code model.
3995   if (M != CodeModel::Small && M != CodeModel::Kernel)
3996     return false;
3997
3998   // For small code model we assume that latest object is 16MB before end of 31
3999   // bits boundary. We may also accept pretty large negative constants knowing
4000   // that all objects are in the positive half of address space.
4001   if (M == CodeModel::Small && Offset < 16*1024*1024)
4002     return true;
4003
4004   // For kernel code model we know that all object resist in the negative half
4005   // of 32bits address space. We may not accept negative offsets, since they may
4006   // be just off and we may accept pretty large positive ones.
4007   if (M == CodeModel::Kernel && Offset >= 0)
4008     return true;
4009
4010   return false;
4011 }
4012
4013 /// Determines whether the callee is required to pop its own arguments.
4014 /// Callee pop is necessary to support tail calls.
4015 bool X86::isCalleePop(CallingConv::ID CallingConv,
4016                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4017   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4018   // can guarantee TCO.
4019   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4020     return true;
4021
4022   switch (CallingConv) {
4023   default:
4024     return false;
4025   case CallingConv::X86_StdCall:
4026   case CallingConv::X86_FastCall:
4027   case CallingConv::X86_ThisCall:
4028   case CallingConv::X86_VectorCall:
4029     return !is64Bit;
4030   }
4031 }
4032
4033 /// \brief Return true if the condition is an unsigned comparison operation.
4034 static bool isX86CCUnsigned(unsigned X86CC) {
4035   switch (X86CC) {
4036   default: llvm_unreachable("Invalid integer condition!");
4037   case X86::COND_E:     return true;
4038   case X86::COND_G:     return false;
4039   case X86::COND_GE:    return false;
4040   case X86::COND_L:     return false;
4041   case X86::COND_LE:    return false;
4042   case X86::COND_NE:    return true;
4043   case X86::COND_B:     return true;
4044   case X86::COND_A:     return true;
4045   case X86::COND_BE:    return true;
4046   case X86::COND_AE:    return true;
4047   }
4048 }
4049
4050 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4051   switch (SetCCOpcode) {
4052   default: llvm_unreachable("Invalid integer condition!");
4053   case ISD::SETEQ:  return X86::COND_E;
4054   case ISD::SETGT:  return X86::COND_G;
4055   case ISD::SETGE:  return X86::COND_GE;
4056   case ISD::SETLT:  return X86::COND_L;
4057   case ISD::SETLE:  return X86::COND_LE;
4058   case ISD::SETNE:  return X86::COND_NE;
4059   case ISD::SETULT: return X86::COND_B;
4060   case ISD::SETUGT: return X86::COND_A;
4061   case ISD::SETULE: return X86::COND_BE;
4062   case ISD::SETUGE: return X86::COND_AE;
4063   }
4064 }
4065
4066 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4067 /// condition code, returning the condition code and the LHS/RHS of the
4068 /// comparison to make.
4069 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4070                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4071   if (!isFP) {
4072     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4073       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4074         // X > -1   -> X == 0, jump !sign.
4075         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4076         return X86::COND_NS;
4077       }
4078       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4079         // X < 0   -> X == 0, jump on sign.
4080         return X86::COND_S;
4081       }
4082       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4083         // X < 1   -> X <= 0
4084         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4085         return X86::COND_LE;
4086       }
4087     }
4088
4089     return TranslateIntegerX86CC(SetCCOpcode);
4090   }
4091
4092   // First determine if it is required or is profitable to flip the operands.
4093
4094   // If LHS is a foldable load, but RHS is not, flip the condition.
4095   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4096       !ISD::isNON_EXTLoad(RHS.getNode())) {
4097     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4098     std::swap(LHS, RHS);
4099   }
4100
4101   switch (SetCCOpcode) {
4102   default: break;
4103   case ISD::SETOLT:
4104   case ISD::SETOLE:
4105   case ISD::SETUGT:
4106   case ISD::SETUGE:
4107     std::swap(LHS, RHS);
4108     break;
4109   }
4110
4111   // On a floating point condition, the flags are set as follows:
4112   // ZF  PF  CF   op
4113   //  0 | 0 | 0 | X > Y
4114   //  0 | 0 | 1 | X < Y
4115   //  1 | 0 | 0 | X == Y
4116   //  1 | 1 | 1 | unordered
4117   switch (SetCCOpcode) {
4118   default: llvm_unreachable("Condcode should be pre-legalized away");
4119   case ISD::SETUEQ:
4120   case ISD::SETEQ:   return X86::COND_E;
4121   case ISD::SETOLT:              // flipped
4122   case ISD::SETOGT:
4123   case ISD::SETGT:   return X86::COND_A;
4124   case ISD::SETOLE:              // flipped
4125   case ISD::SETOGE:
4126   case ISD::SETGE:   return X86::COND_AE;
4127   case ISD::SETUGT:              // flipped
4128   case ISD::SETULT:
4129   case ISD::SETLT:   return X86::COND_B;
4130   case ISD::SETUGE:              // flipped
4131   case ISD::SETULE:
4132   case ISD::SETLE:   return X86::COND_BE;
4133   case ISD::SETONE:
4134   case ISD::SETNE:   return X86::COND_NE;
4135   case ISD::SETUO:   return X86::COND_P;
4136   case ISD::SETO:    return X86::COND_NP;
4137   case ISD::SETOEQ:
4138   case ISD::SETUNE:  return X86::COND_INVALID;
4139   }
4140 }
4141
4142 /// Is there a floating point cmov for the specific X86 condition code?
4143 /// Current x86 isa includes the following FP cmov instructions:
4144 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4145 static bool hasFPCMov(unsigned X86CC) {
4146   switch (X86CC) {
4147   default:
4148     return false;
4149   case X86::COND_B:
4150   case X86::COND_BE:
4151   case X86::COND_E:
4152   case X86::COND_P:
4153   case X86::COND_A:
4154   case X86::COND_AE:
4155   case X86::COND_NE:
4156   case X86::COND_NP:
4157     return true;
4158   }
4159 }
4160
4161 /// Returns true if the target can instruction select the
4162 /// specified FP immediate natively. If false, the legalizer will
4163 /// materialize the FP immediate as a load from a constant pool.
4164 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4165   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4166     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4167       return true;
4168   }
4169   return false;
4170 }
4171
4172 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4173                                               ISD::LoadExtType ExtTy,
4174                                               EVT NewVT) const {
4175   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4176   // relocation target a movq or addq instruction: don't let the load shrink.
4177   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4178   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4179     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4180       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4181   return true;
4182 }
4183
4184 /// \brief Returns true if it is beneficial to convert a load of a constant
4185 /// to just the constant itself.
4186 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4187                                                           Type *Ty) const {
4188   assert(Ty->isIntegerTy());
4189
4190   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4191   if (BitSize == 0 || BitSize > 64)
4192     return false;
4193   return true;
4194 }
4195
4196 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4197                                                 unsigned Index) const {
4198   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4199     return false;
4200
4201   return (Index == 0 || Index == ResVT.getVectorNumElements());
4202 }
4203
4204 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4205   // Speculate cttz only if we can directly use TZCNT.
4206   return Subtarget->hasBMI();
4207 }
4208
4209 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4210   // Speculate ctlz only if we can directly use LZCNT.
4211   return Subtarget->hasLZCNT();
4212 }
4213
4214 /// Return true if every element in Mask, beginning
4215 /// from position Pos and ending in Pos+Size is undef.
4216 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4217   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4218     if (0 <= Mask[i])
4219       return false;
4220   return true;
4221 }
4222
4223 /// Return true if Val is undef or if its value falls within the
4224 /// specified range (L, H].
4225 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4226   return (Val < 0) || (Val >= Low && Val < Hi);
4227 }
4228
4229 /// Val is either less than zero (undef) or equal to the specified value.
4230 static bool isUndefOrEqual(int Val, int CmpVal) {
4231   return (Val < 0 || Val == CmpVal);
4232 }
4233
4234 /// Return true if every element in Mask, beginning
4235 /// from position Pos and ending in Pos+Size, falls within the specified
4236 /// sequential range (Low, Low+Size]. or is undef.
4237 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4238                                        unsigned Pos, unsigned Size, int Low) {
4239   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4240     if (!isUndefOrEqual(Mask[i], Low))
4241       return false;
4242   return true;
4243 }
4244
4245 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4246 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4247 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4248   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4249   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4250     return false;
4251
4252   // The index should be aligned on a vecWidth-bit boundary.
4253   uint64_t Index =
4254     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4255
4256   MVT VT = N->getSimpleValueType(0);
4257   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4258   bool Result = (Index * ElSize) % vecWidth == 0;
4259
4260   return Result;
4261 }
4262
4263 /// Return true if the specified INSERT_SUBVECTOR
4264 /// operand specifies a subvector insert that is suitable for input to
4265 /// insertion of 128 or 256-bit subvectors
4266 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4267   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4268   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4269     return false;
4270   // The index should be aligned on a vecWidth-bit boundary.
4271   uint64_t Index =
4272     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4273
4274   MVT VT = N->getSimpleValueType(0);
4275   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4276   bool Result = (Index * ElSize) % vecWidth == 0;
4277
4278   return Result;
4279 }
4280
4281 bool X86::isVINSERT128Index(SDNode *N) {
4282   return isVINSERTIndex(N, 128);
4283 }
4284
4285 bool X86::isVINSERT256Index(SDNode *N) {
4286   return isVINSERTIndex(N, 256);
4287 }
4288
4289 bool X86::isVEXTRACT128Index(SDNode *N) {
4290   return isVEXTRACTIndex(N, 128);
4291 }
4292
4293 bool X86::isVEXTRACT256Index(SDNode *N) {
4294   return isVEXTRACTIndex(N, 256);
4295 }
4296
4297 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4298   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4299   assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4300          "Illegal extract subvector for VEXTRACT");
4301
4302   uint64_t Index =
4303     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4304
4305   MVT VecVT = N->getOperand(0).getSimpleValueType();
4306   MVT ElVT = VecVT.getVectorElementType();
4307
4308   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4309   return Index / NumElemsPerChunk;
4310 }
4311
4312 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4313   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4314   assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4315          "Illegal insert subvector for VINSERT");
4316
4317   uint64_t Index =
4318     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4319
4320   MVT VecVT = N->getSimpleValueType(0);
4321   MVT ElVT = VecVT.getVectorElementType();
4322
4323   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4324   return Index / NumElemsPerChunk;
4325 }
4326
4327 /// Return the appropriate immediate to extract the specified
4328 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4329 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4330   return getExtractVEXTRACTImmediate(N, 128);
4331 }
4332
4333 /// Return the appropriate immediate to extract the specified
4334 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4335 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4336   return getExtractVEXTRACTImmediate(N, 256);
4337 }
4338
4339 /// Return the appropriate immediate to insert at the specified
4340 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4341 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4342   return getInsertVINSERTImmediate(N, 128);
4343 }
4344
4345 /// Return the appropriate immediate to insert at the specified
4346 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4347 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4348   return getInsertVINSERTImmediate(N, 256);
4349 }
4350
4351 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4352 bool X86::isZeroNode(SDValue Elt) {
4353   return isNullConstant(Elt) || isNullFPConstant(Elt);
4354 }
4355
4356 // Build a vector of constants
4357 // Use an UNDEF node if MaskElt == -1.
4358 // Spilt 64-bit constants in the 32-bit mode.
4359 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4360                               SelectionDAG &DAG,
4361                               SDLoc dl, bool IsMask = false) {
4362
4363   SmallVector<SDValue, 32>  Ops;
4364   bool Split = false;
4365
4366   MVT ConstVecVT = VT;
4367   unsigned NumElts = VT.getVectorNumElements();
4368   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4369   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4370     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4371     Split = true;
4372   }
4373
4374   MVT EltVT = ConstVecVT.getVectorElementType();
4375   for (unsigned i = 0; i < NumElts; ++i) {
4376     bool IsUndef = Values[i] < 0 && IsMask;
4377     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4378       DAG.getConstant(Values[i], dl, EltVT);
4379     Ops.push_back(OpNode);
4380     if (Split)
4381       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4382                     DAG.getConstant(0, dl, EltVT));
4383   }
4384   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4385   if (Split)
4386     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4387   return ConstsNode;
4388 }
4389
4390 /// Returns a vector of specified type with all zero elements.
4391 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4392                              SelectionDAG &DAG, SDLoc dl) {
4393   assert(VT.isVector() && "Expected a vector type");
4394
4395   // Always build SSE zero vectors as <4 x i32> bitcasted
4396   // to their dest type. This ensures they get CSE'd.
4397   SDValue Vec;
4398   if (VT.is128BitVector()) {  // SSE
4399     if (Subtarget->hasSSE2()) {  // SSE2
4400       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4401       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4402     } else { // SSE1
4403       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4404       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4405     }
4406   } else if (VT.is256BitVector()) { // AVX
4407     if (Subtarget->hasInt256()) { // AVX2
4408       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4409       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4410       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4411     } else {
4412       // 256-bit logic and arithmetic instructions in AVX are all
4413       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4414       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4415       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4416       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4417     }
4418   } else if (VT.is512BitVector()) { // AVX-512
4419       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4420       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4421                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4422       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4423   } else if (VT.getVectorElementType() == MVT::i1) {
4424
4425     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4426             && "Unexpected vector type");
4427     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4428             && "Unexpected vector type");
4429     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4430     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4431     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4432   } else
4433     llvm_unreachable("Unexpected vector type");
4434
4435   return DAG.getBitcast(VT, Vec);
4436 }
4437
4438 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4439                                 SelectionDAG &DAG, SDLoc dl,
4440                                 unsigned vectorWidth) {
4441   assert((vectorWidth == 128 || vectorWidth == 256) &&
4442          "Unsupported vector width");
4443   EVT VT = Vec.getValueType();
4444   EVT ElVT = VT.getVectorElementType();
4445   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4446   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4447                                   VT.getVectorNumElements()/Factor);
4448
4449   // Extract from UNDEF is UNDEF.
4450   if (Vec.getOpcode() == ISD::UNDEF)
4451     return DAG.getUNDEF(ResultVT);
4452
4453   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4454   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4455   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4456
4457   // This is the index of the first element of the vectorWidth-bit chunk
4458   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4459   IdxVal &= ~(ElemsPerChunk - 1);
4460
4461   // If the input is a buildvector just emit a smaller one.
4462   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4463     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4464                        makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4465
4466   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4467   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4468 }
4469
4470 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4471 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4472 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4473 /// instructions or a simple subregister reference. Idx is an index in the
4474 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4475 /// lowering EXTRACT_VECTOR_ELT operations easier.
4476 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4477                                    SelectionDAG &DAG, SDLoc dl) {
4478   assert((Vec.getValueType().is256BitVector() ||
4479           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4480   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4481 }
4482
4483 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4484 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4485                                    SelectionDAG &DAG, SDLoc dl) {
4486   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4487   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4488 }
4489
4490 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4491                                unsigned IdxVal, SelectionDAG &DAG,
4492                                SDLoc dl, unsigned vectorWidth) {
4493   assert((vectorWidth == 128 || vectorWidth == 256) &&
4494          "Unsupported vector width");
4495   // Inserting UNDEF is Result
4496   if (Vec.getOpcode() == ISD::UNDEF)
4497     return Result;
4498   EVT VT = Vec.getValueType();
4499   EVT ElVT = VT.getVectorElementType();
4500   EVT ResultVT = Result.getValueType();
4501
4502   // Insert the relevant vectorWidth bits.
4503   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4504   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4505
4506   // This is the index of the first element of the vectorWidth-bit chunk
4507   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4508   IdxVal &= ~(ElemsPerChunk - 1);
4509
4510   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4511   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4512 }
4513
4514 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4515 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4516 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4517 /// simple superregister reference.  Idx is an index in the 128 bits
4518 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4519 /// lowering INSERT_VECTOR_ELT operations easier.
4520 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4521                                   SelectionDAG &DAG, SDLoc dl) {
4522   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4523
4524   // For insertion into the zero index (low half) of a 256-bit vector, it is
4525   // more efficient to generate a blend with immediate instead of an insert*128.
4526   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4527   // extend the subvector to the size of the result vector. Make sure that
4528   // we are not recursing on that node by checking for undef here.
4529   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4530       Result.getOpcode() != ISD::UNDEF) {
4531     EVT ResultVT = Result.getValueType();
4532     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4533     SDValue Undef = DAG.getUNDEF(ResultVT);
4534     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4535                                  Vec, ZeroIndex);
4536
4537     // The blend instruction, and therefore its mask, depend on the data type.
4538     MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4539     if (ScalarType.isFloatingPoint()) {
4540       // Choose either vblendps (float) or vblendpd (double).
4541       unsigned ScalarSize = ScalarType.getSizeInBits();
4542       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4543       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4544       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4545       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4546     }
4547
4548     const X86Subtarget &Subtarget =
4549     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4550
4551     // AVX2 is needed for 256-bit integer blend support.
4552     // Integers must be cast to 32-bit because there is only vpblendd;
4553     // vpblendw can't be used for this because it has a handicapped mask.
4554
4555     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4556     // is still more efficient than using the wrong domain vinsertf128 that
4557     // will be created by InsertSubVector().
4558     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4559
4560     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4561     Result = DAG.getBitcast(CastVT, Result);
4562     Vec256 = DAG.getBitcast(CastVT, Vec256);
4563     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4564     return DAG.getBitcast(ResultVT, Vec256);
4565   }
4566
4567   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4568 }
4569
4570 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4571                                   SelectionDAG &DAG, SDLoc dl) {
4572   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4573   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4574 }
4575
4576 /// Insert i1-subvector to i1-vector.
4577 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4578
4579   SDLoc dl(Op);
4580   SDValue Vec = Op.getOperand(0);
4581   SDValue SubVec = Op.getOperand(1);
4582   SDValue Idx = Op.getOperand(2);
4583
4584   if (!isa<ConstantSDNode>(Idx))
4585     return SDValue();
4586
4587   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4588   if (IdxVal == 0  && Vec.isUndef()) // the operation is legal
4589     return Op;
4590
4591   MVT OpVT = Op.getSimpleValueType();
4592   MVT SubVecVT = SubVec.getSimpleValueType();
4593   unsigned NumElems = OpVT.getVectorNumElements();
4594   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4595
4596   assert(IdxVal + SubVecNumElems <= NumElems &&
4597          IdxVal % SubVecVT.getSizeInBits() == 0 &&
4598          "Unexpected index value in INSERT_SUBVECTOR");
4599
4600   // There are 3 possible cases:
4601   // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4602   // 2. Subvector should be inserted in the upper part
4603   //    (IdxVal + SubVecNumElems == NumElems)
4604   // 3. Subvector should be inserted in the middle (for example v2i1
4605   //    to v16i1, index 2)
4606
4607   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4608   SDValue Undef = DAG.getUNDEF(OpVT);
4609   SDValue WideSubVec =
4610     DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4611   if (Vec.isUndef())
4612     return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4613       DAG.getConstant(IdxVal, dl, MVT::i8));
4614
4615   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4616     unsigned ShiftLeft = NumElems - SubVecNumElems;
4617     unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4618     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4619       DAG.getConstant(ShiftLeft, dl, MVT::i8));
4620     return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4621       DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4622   }
4623
4624   if (IdxVal == 0) {
4625     // Zero lower bits of the Vec
4626     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4627     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4628     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4629     // Merge them together
4630     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4631   }
4632
4633   // Simple case when we put subvector in the upper part
4634   if (IdxVal + SubVecNumElems == NumElems) {
4635     // Zero upper bits of the Vec
4636     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4637                         DAG.getConstant(IdxVal, dl, MVT::i8));
4638     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4639     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4640     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4641     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4642   }
4643   // Subvector should be inserted in the middle - use shuffle
4644   SmallVector<int, 64> Mask;
4645   for (unsigned i = 0; i < NumElems; ++i)
4646     Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4647                     i : i + NumElems);
4648   return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4649 }
4650
4651 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4652 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4653 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4654 /// large BUILD_VECTORS.
4655 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4656                                    unsigned NumElems, SelectionDAG &DAG,
4657                                    SDLoc dl) {
4658   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4659   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4660 }
4661
4662 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4663                                    unsigned NumElems, SelectionDAG &DAG,
4664                                    SDLoc dl) {
4665   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4666   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4667 }
4668
4669 /// Returns a vector of specified type with all bits set.
4670 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4671 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4672 /// Then bitcast to their original type, ensuring they get CSE'd.
4673 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4674                              SelectionDAG &DAG, SDLoc dl) {
4675   assert(VT.isVector() && "Expected a vector type");
4676
4677   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4678   SDValue Vec;
4679   if (VT.is512BitVector()) {
4680     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4681                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4682     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4683   } else if (VT.is256BitVector()) {
4684     if (Subtarget->hasInt256()) { // AVX2
4685       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4686       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4687     } else { // AVX
4688       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4689       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4690     }
4691   } else if (VT.is128BitVector()) {
4692     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4693   } else
4694     llvm_unreachable("Unexpected vector type");
4695
4696   return DAG.getBitcast(VT, Vec);
4697 }
4698
4699 /// Returns a vector_shuffle node for an unpackl operation.
4700 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4701                           SDValue V2) {
4702   unsigned NumElems = VT.getVectorNumElements();
4703   SmallVector<int, 8> Mask;
4704   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4705     Mask.push_back(i);
4706     Mask.push_back(i + NumElems);
4707   }
4708   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4709 }
4710
4711 /// Returns a vector_shuffle node for an unpackh operation.
4712 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4713                           SDValue V2) {
4714   unsigned NumElems = VT.getVectorNumElements();
4715   SmallVector<int, 8> Mask;
4716   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4717     Mask.push_back(i + Half);
4718     Mask.push_back(i + NumElems + Half);
4719   }
4720   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4721 }
4722
4723 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4724 /// This produces a shuffle where the low element of V2 is swizzled into the
4725 /// zero/undef vector, landing at element Idx.
4726 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4727 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4728                                            bool IsZero,
4729                                            const X86Subtarget *Subtarget,
4730                                            SelectionDAG &DAG) {
4731   MVT VT = V2.getSimpleValueType();
4732   SDValue V1 = IsZero
4733     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4734   unsigned NumElems = VT.getVectorNumElements();
4735   SmallVector<int, 16> MaskVec;
4736   for (unsigned i = 0; i != NumElems; ++i)
4737     // If this is the insertion idx, put the low elt of V2 here.
4738     MaskVec.push_back(i == Idx ? NumElems : i);
4739   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4740 }
4741
4742 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4743 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4744 /// uses one source. Note that this will set IsUnary for shuffles which use a
4745 /// single input multiple times, and in those cases it will
4746 /// adjust the mask to only have indices within that single input.
4747 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
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::INSERTPS:
4765     ImmN = N->getOperand(N->getNumOperands()-1);
4766     DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4767     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4768     break;
4769   case X86ISD::UNPCKH:
4770     DecodeUNPCKHMask(VT, Mask);
4771     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4772     break;
4773   case X86ISD::UNPCKL:
4774     DecodeUNPCKLMask(VT, Mask);
4775     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4776     break;
4777   case X86ISD::MOVHLPS:
4778     DecodeMOVHLPSMask(NumElems, Mask);
4779     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4780     break;
4781   case X86ISD::MOVLHPS:
4782     DecodeMOVLHPSMask(NumElems, Mask);
4783     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4784     break;
4785   case X86ISD::PALIGNR:
4786     ImmN = N->getOperand(N->getNumOperands()-1);
4787     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4788     break;
4789   case X86ISD::PSHUFD:
4790   case X86ISD::VPERMILPI:
4791     ImmN = N->getOperand(N->getNumOperands()-1);
4792     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4793     IsUnary = true;
4794     break;
4795   case X86ISD::PSHUFHW:
4796     ImmN = N->getOperand(N->getNumOperands()-1);
4797     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4798     IsUnary = true;
4799     break;
4800   case X86ISD::PSHUFLW:
4801     ImmN = N->getOperand(N->getNumOperands()-1);
4802     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4803     IsUnary = true;
4804     break;
4805   case X86ISD::PSHUFB: {
4806     IsUnary = true;
4807     SDValue MaskNode = N->getOperand(1);
4808     while (MaskNode->getOpcode() == ISD::BITCAST)
4809       MaskNode = MaskNode->getOperand(0);
4810
4811     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4812       // If we have a build-vector, then things are easy.
4813       MVT VT = MaskNode.getSimpleValueType();
4814       assert(VT.isVector() &&
4815              "Can't produce a non-vector with a build_vector!");
4816       if (!VT.isInteger())
4817         return false;
4818
4819       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4820
4821       SmallVector<uint64_t, 32> RawMask;
4822       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4823         SDValue Op = MaskNode->getOperand(i);
4824         if (Op->getOpcode() == ISD::UNDEF) {
4825           RawMask.push_back((uint64_t)SM_SentinelUndef);
4826           continue;
4827         }
4828         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4829         if (!CN)
4830           return false;
4831         APInt MaskElement = CN->getAPIntValue();
4832
4833         // We now have to decode the element which could be any integer size and
4834         // extract each byte of it.
4835         for (int j = 0; j < NumBytesPerElement; ++j) {
4836           // Note that this is x86 and so always little endian: the low byte is
4837           // the first byte of the mask.
4838           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4839           MaskElement = MaskElement.lshr(8);
4840         }
4841       }
4842       DecodePSHUFBMask(RawMask, Mask);
4843       break;
4844     }
4845
4846     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4847     if (!MaskLoad)
4848       return false;
4849
4850     SDValue Ptr = MaskLoad->getBasePtr();
4851     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4852         Ptr->getOpcode() == X86ISD::WrapperRIP)
4853       Ptr = Ptr->getOperand(0);
4854
4855     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4856     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4857       return false;
4858
4859     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4860       DecodePSHUFBMask(C, Mask);
4861       break;
4862     }
4863
4864     return false;
4865   }
4866   case X86ISD::VPERMI:
4867     ImmN = N->getOperand(N->getNumOperands()-1);
4868     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4869     IsUnary = true;
4870     break;
4871   case X86ISD::MOVSS:
4872   case X86ISD::MOVSD:
4873     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4874     break;
4875   case X86ISD::VPERM2X128:
4876     ImmN = N->getOperand(N->getNumOperands()-1);
4877     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4878     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4879     break;
4880   case X86ISD::MOVSLDUP:
4881     DecodeMOVSLDUPMask(VT, Mask);
4882     IsUnary = true;
4883     break;
4884   case X86ISD::MOVSHDUP:
4885     DecodeMOVSHDUPMask(VT, Mask);
4886     IsUnary = true;
4887     break;
4888   case X86ISD::MOVDDUP:
4889     DecodeMOVDDUPMask(VT, Mask);
4890     IsUnary = true;
4891     break;
4892   case X86ISD::MOVLHPD:
4893   case X86ISD::MOVLPD:
4894   case X86ISD::MOVLPS:
4895     // Not yet implemented
4896     return false;
4897   case X86ISD::VPERMV: {
4898     IsUnary = true;
4899     SDValue MaskNode = N->getOperand(0);
4900     while (MaskNode->getOpcode() == ISD::BITCAST)
4901       MaskNode = MaskNode->getOperand(0);
4902
4903     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4904     SmallVector<uint64_t, 32> RawMask;
4905     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4906       // If we have a build-vector, then things are easy.
4907       assert(MaskNode.getSimpleValueType().isInteger() &&
4908              MaskNode.getSimpleValueType().getVectorNumElements() ==
4909              VT.getVectorNumElements());
4910
4911       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4912         SDValue Op = MaskNode->getOperand(i);
4913         if (Op->getOpcode() == ISD::UNDEF)
4914           RawMask.push_back((uint64_t)SM_SentinelUndef);
4915         else if (isa<ConstantSDNode>(Op)) {
4916           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4917           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4918         } else
4919           return false;
4920       }
4921       DecodeVPERMVMask(RawMask, Mask);
4922       break;
4923     }
4924     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4925       unsigned NumEltsInMask = MaskNode->getNumOperands();
4926       MaskNode = MaskNode->getOperand(0);
4927       if (auto *CN = dyn_cast<ConstantSDNode>(MaskNode)) {
4928         APInt MaskEltValue = CN->getAPIntValue();
4929         for (unsigned i = 0; i < NumEltsInMask; ++i)
4930           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4931         DecodeVPERMVMask(RawMask, Mask);
4932         break;
4933       }
4934       // It may be a scalar load
4935     }
4936
4937     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4938     if (!MaskLoad)
4939       return false;
4940
4941     SDValue Ptr = MaskLoad->getBasePtr();
4942     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4943         Ptr->getOpcode() == X86ISD::WrapperRIP)
4944       Ptr = Ptr->getOperand(0);
4945
4946     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4947     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4948       return false;
4949
4950     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4951       DecodeVPERMVMask(C, VT, Mask);
4952       break;
4953     }
4954     return false;
4955   }
4956   case X86ISD::VPERMV3: {
4957     IsUnary = false;
4958     SDValue MaskNode = N->getOperand(1);
4959     while (MaskNode->getOpcode() == ISD::BITCAST)
4960       MaskNode = MaskNode->getOperand(1);
4961
4962     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4963       // If we have a build-vector, then things are easy.
4964       assert(MaskNode.getSimpleValueType().isInteger() &&
4965              MaskNode.getSimpleValueType().getVectorNumElements() ==
4966              VT.getVectorNumElements());
4967
4968       SmallVector<uint64_t, 32> RawMask;
4969       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4970
4971       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4972         SDValue Op = MaskNode->getOperand(i);
4973         if (Op->getOpcode() == ISD::UNDEF)
4974           RawMask.push_back((uint64_t)SM_SentinelUndef);
4975         else {
4976           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4977           if (!CN)
4978             return false;
4979           APInt MaskElement = CN->getAPIntValue();
4980           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4981         }
4982       }
4983       DecodeVPERMV3Mask(RawMask, Mask);
4984       break;
4985     }
4986
4987     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4988     if (!MaskLoad)
4989       return false;
4990
4991     SDValue Ptr = MaskLoad->getBasePtr();
4992     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4993         Ptr->getOpcode() == X86ISD::WrapperRIP)
4994       Ptr = Ptr->getOperand(0);
4995
4996     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4997     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4998       return false;
4999
5000     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5001       DecodeVPERMV3Mask(C, VT, Mask);
5002       break;
5003     }
5004     return false;
5005   }
5006   default: llvm_unreachable("unknown target shuffle node");
5007   }
5008
5009   // Empty mask indicates the decode failed.
5010   if (Mask.empty())
5011     return false;
5012
5013   // Check if we're getting a shuffle mask with zero'd elements.
5014   if (!AllowSentinelZero)
5015     if (std::any_of(Mask.begin(), Mask.end(),
5016                     [](int M){ return M == SM_SentinelZero; }))
5017       return false;
5018
5019   // If we have a fake unary shuffle, the shuffle mask is spread across two
5020   // inputs that are actually the same node. Re-map the mask to always point
5021   // into the first input.
5022   if (IsFakeUnary)
5023     for (int &M : Mask)
5024       if (M >= (int)Mask.size())
5025         M -= Mask.size();
5026
5027   return true;
5028 }
5029
5030 /// Returns the scalar element that will make up the ith
5031 /// element of the result of the vector shuffle.
5032 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5033                                    unsigned Depth) {
5034   if (Depth == 6)
5035     return SDValue();  // Limit search depth.
5036
5037   SDValue V = SDValue(N, 0);
5038   EVT VT = V.getValueType();
5039   unsigned Opcode = V.getOpcode();
5040
5041   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5042   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5043     int Elt = SV->getMaskElt(Index);
5044
5045     if (Elt < 0)
5046       return DAG.getUNDEF(VT.getVectorElementType());
5047
5048     unsigned NumElems = VT.getVectorNumElements();
5049     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5050                                          : SV->getOperand(1);
5051     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5052   }
5053
5054   // Recurse into target specific vector shuffles to find scalars.
5055   if (isTargetShuffle(Opcode)) {
5056     MVT ShufVT = V.getSimpleValueType();
5057     int NumElems = (int)ShufVT.getVectorNumElements();
5058     SmallVector<int, 16> ShuffleMask;
5059     bool IsUnary;
5060
5061     if (!getTargetShuffleMask(N, ShufVT, false, ShuffleMask, IsUnary))
5062       return SDValue();
5063
5064     int Elt = ShuffleMask[Index];
5065     if (Elt == SM_SentinelUndef)
5066       return DAG.getUNDEF(ShufVT.getVectorElementType());
5067
5068     assert(0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range");
5069     SDValue NewV = (Elt < NumElems) ? N->getOperand(0) : N->getOperand(1);
5070     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5071                                Depth+1);
5072   }
5073
5074   // Actual nodes that may contain scalar elements
5075   if (Opcode == ISD::BITCAST) {
5076     V = V.getOperand(0);
5077     EVT SrcVT = V.getValueType();
5078     unsigned NumElems = VT.getVectorNumElements();
5079
5080     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5081       return SDValue();
5082   }
5083
5084   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5085     return (Index == 0) ? V.getOperand(0)
5086                         : DAG.getUNDEF(VT.getVectorElementType());
5087
5088   if (V.getOpcode() == ISD::BUILD_VECTOR)
5089     return V.getOperand(Index);
5090
5091   return SDValue();
5092 }
5093
5094 /// Custom lower build_vector of v16i8.
5095 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5096                                        unsigned NumNonZero, unsigned NumZero,
5097                                        SelectionDAG &DAG,
5098                                        const X86Subtarget* Subtarget,
5099                                        const TargetLowering &TLI) {
5100   if (NumNonZero > 8)
5101     return SDValue();
5102
5103   SDLoc dl(Op);
5104   SDValue V;
5105   bool First = true;
5106
5107   // SSE4.1 - use PINSRB to insert each byte directly.
5108   if (Subtarget->hasSSE41()) {
5109     for (unsigned i = 0; i < 16; ++i) {
5110       bool isNonZero = (NonZeros & (1 << i)) != 0;
5111       if (isNonZero) {
5112         if (First) {
5113           if (NumZero)
5114             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5115           else
5116             V = DAG.getUNDEF(MVT::v16i8);
5117           First = false;
5118         }
5119         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5120                         MVT::v16i8, V, Op.getOperand(i),
5121                         DAG.getIntPtrConstant(i, dl));
5122       }
5123     }
5124
5125     return V;
5126   }
5127
5128   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5129   for (unsigned i = 0; i < 16; ++i) {
5130     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5131     if (ThisIsNonZero && First) {
5132       if (NumZero)
5133         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5134       else
5135         V = DAG.getUNDEF(MVT::v8i16);
5136       First = false;
5137     }
5138
5139     if ((i & 1) != 0) {
5140       SDValue ThisElt, LastElt;
5141       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5142       if (LastIsNonZero) {
5143         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5144                               MVT::i16, Op.getOperand(i-1));
5145       }
5146       if (ThisIsNonZero) {
5147         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5148         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5149                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
5150         if (LastIsNonZero)
5151           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5152       } else
5153         ThisElt = LastElt;
5154
5155       if (ThisElt.getNode())
5156         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5157                         DAG.getIntPtrConstant(i/2, dl));
5158     }
5159   }
5160
5161   return DAG.getBitcast(MVT::v16i8, V);
5162 }
5163
5164 /// Custom lower build_vector of v8i16.
5165 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5166                                      unsigned NumNonZero, unsigned NumZero,
5167                                      SelectionDAG &DAG,
5168                                      const X86Subtarget* Subtarget,
5169                                      const TargetLowering &TLI) {
5170   if (NumNonZero > 4)
5171     return SDValue();
5172
5173   SDLoc dl(Op);
5174   SDValue V;
5175   bool First = true;
5176   for (unsigned i = 0; i < 8; ++i) {
5177     bool isNonZero = (NonZeros & (1 << i)) != 0;
5178     if (isNonZero) {
5179       if (First) {
5180         if (NumZero)
5181           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5182         else
5183           V = DAG.getUNDEF(MVT::v8i16);
5184         First = false;
5185       }
5186       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5187                       MVT::v8i16, V, Op.getOperand(i),
5188                       DAG.getIntPtrConstant(i, dl));
5189     }
5190   }
5191
5192   return V;
5193 }
5194
5195 /// Custom lower build_vector of v4i32 or v4f32.
5196 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5197                                      const X86Subtarget *Subtarget,
5198                                      const TargetLowering &TLI) {
5199   // Find all zeroable elements.
5200   std::bitset<4> Zeroable;
5201   for (int i=0; i < 4; ++i) {
5202     SDValue Elt = Op->getOperand(i);
5203     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5204   }
5205   assert(Zeroable.size() - Zeroable.count() > 1 &&
5206          "We expect at least two non-zero elements!");
5207
5208   // We only know how to deal with build_vector nodes where elements are either
5209   // zeroable or extract_vector_elt with constant index.
5210   SDValue FirstNonZero;
5211   unsigned FirstNonZeroIdx;
5212   for (unsigned i=0; i < 4; ++i) {
5213     if (Zeroable[i])
5214       continue;
5215     SDValue Elt = Op->getOperand(i);
5216     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5217         !isa<ConstantSDNode>(Elt.getOperand(1)))
5218       return SDValue();
5219     // Make sure that this node is extracting from a 128-bit vector.
5220     MVT VT = Elt.getOperand(0).getSimpleValueType();
5221     if (!VT.is128BitVector())
5222       return SDValue();
5223     if (!FirstNonZero.getNode()) {
5224       FirstNonZero = Elt;
5225       FirstNonZeroIdx = i;
5226     }
5227   }
5228
5229   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5230   SDValue V1 = FirstNonZero.getOperand(0);
5231   MVT VT = V1.getSimpleValueType();
5232
5233   // See if this build_vector can be lowered as a blend with zero.
5234   SDValue Elt;
5235   unsigned EltMaskIdx, EltIdx;
5236   int Mask[4];
5237   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5238     if (Zeroable[EltIdx]) {
5239       // The zero vector will be on the right hand side.
5240       Mask[EltIdx] = EltIdx+4;
5241       continue;
5242     }
5243
5244     Elt = Op->getOperand(EltIdx);
5245     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5246     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5247     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5248       break;
5249     Mask[EltIdx] = EltIdx;
5250   }
5251
5252   if (EltIdx == 4) {
5253     // Let the shuffle legalizer deal with blend operations.
5254     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5255     if (V1.getSimpleValueType() != VT)
5256       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5257     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5258   }
5259
5260   // See if we can lower this build_vector to a INSERTPS.
5261   if (!Subtarget->hasSSE41())
5262     return SDValue();
5263
5264   SDValue V2 = Elt.getOperand(0);
5265   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5266     V1 = SDValue();
5267
5268   bool CanFold = true;
5269   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5270     if (Zeroable[i])
5271       continue;
5272
5273     SDValue Current = Op->getOperand(i);
5274     SDValue SrcVector = Current->getOperand(0);
5275     if (!V1.getNode())
5276       V1 = SrcVector;
5277     CanFold = SrcVector == V1 &&
5278       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5279   }
5280
5281   if (!CanFold)
5282     return SDValue();
5283
5284   assert(V1.getNode() && "Expected at least two non-zero elements!");
5285   if (V1.getSimpleValueType() != MVT::v4f32)
5286     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5287   if (V2.getSimpleValueType() != MVT::v4f32)
5288     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5289
5290   // Ok, we can emit an INSERTPS instruction.
5291   unsigned ZMask = Zeroable.to_ulong();
5292
5293   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5294   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5295   SDLoc DL(Op);
5296   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5297                                DAG.getIntPtrConstant(InsertPSMask, DL));
5298   return DAG.getBitcast(VT, Result);
5299 }
5300
5301 /// Return a vector logical shift node.
5302 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5303                          unsigned NumBits, SelectionDAG &DAG,
5304                          const TargetLowering &TLI, SDLoc dl) {
5305   assert(VT.is128BitVector() && "Unknown type for VShift");
5306   MVT ShVT = MVT::v2i64;
5307   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5308   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5309   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5310   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5311   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5312   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5313 }
5314
5315 static SDValue
5316 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5317
5318   // Check if the scalar load can be widened into a vector load. And if
5319   // the address is "base + cst" see if the cst can be "absorbed" into
5320   // the shuffle mask.
5321   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5322     SDValue Ptr = LD->getBasePtr();
5323     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5324       return SDValue();
5325     EVT PVT = LD->getValueType(0);
5326     if (PVT != MVT::i32 && PVT != MVT::f32)
5327       return SDValue();
5328
5329     int FI = -1;
5330     int64_t Offset = 0;
5331     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5332       FI = FINode->getIndex();
5333       Offset = 0;
5334     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5335                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5336       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5337       Offset = Ptr.getConstantOperandVal(1);
5338       Ptr = Ptr.getOperand(0);
5339     } else {
5340       return SDValue();
5341     }
5342
5343     // FIXME: 256-bit vector instructions don't require a strict alignment,
5344     // improve this code to support it better.
5345     unsigned RequiredAlign = VT.getSizeInBits()/8;
5346     SDValue Chain = LD->getChain();
5347     // Make sure the stack object alignment is at least 16 or 32.
5348     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5349     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5350       if (MFI->isFixedObjectIndex(FI)) {
5351         // Can't change the alignment. FIXME: It's possible to compute
5352         // the exact stack offset and reference FI + adjust offset instead.
5353         // If someone *really* cares about this. That's the way to implement it.
5354         return SDValue();
5355       } else {
5356         MFI->setObjectAlignment(FI, RequiredAlign);
5357       }
5358     }
5359
5360     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5361     // Ptr + (Offset & ~15).
5362     if (Offset < 0)
5363       return SDValue();
5364     if ((Offset % RequiredAlign) & 3)
5365       return SDValue();
5366     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5367     if (StartOffset) {
5368       SDLoc DL(Ptr);
5369       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5370                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5371     }
5372
5373     int EltNo = (Offset - StartOffset) >> 2;
5374     unsigned NumElems = VT.getVectorNumElements();
5375
5376     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5377     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5378                              LD->getPointerInfo().getWithOffset(StartOffset),
5379                              false, false, false, 0);
5380
5381     SmallVector<int, 8> Mask(NumElems, EltNo);
5382
5383     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5384   }
5385
5386   return SDValue();
5387 }
5388
5389 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5390 /// elements can be replaced by a single large load which has the same value as
5391 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5392 ///
5393 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5394 ///
5395 /// FIXME: we'd also like to handle the case where the last elements are zero
5396 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5397 /// There's even a handy isZeroNode for that purpose.
5398 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5399                                         SDLoc &DL, SelectionDAG &DAG,
5400                                         bool isAfterLegalize) {
5401   unsigned NumElems = Elts.size();
5402
5403   LoadSDNode *LDBase = nullptr;
5404   unsigned LastLoadedElt = -1U;
5405
5406   // For each element in the initializer, see if we've found a load or an undef.
5407   // If we don't find an initial load element, or later load elements are
5408   // non-consecutive, bail out.
5409   for (unsigned i = 0; i < NumElems; ++i) {
5410     SDValue Elt = Elts[i];
5411     // Look through a bitcast.
5412     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5413       Elt = Elt.getOperand(0);
5414     if (!Elt.getNode() ||
5415         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5416       return SDValue();
5417     if (!LDBase) {
5418       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5419         return SDValue();
5420       LDBase = cast<LoadSDNode>(Elt.getNode());
5421       LastLoadedElt = i;
5422       continue;
5423     }
5424     if (Elt.getOpcode() == ISD::UNDEF)
5425       continue;
5426
5427     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5428     EVT LdVT = Elt.getValueType();
5429     // Each loaded element must be the correct fractional portion of the
5430     // requested vector load.
5431     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5432       return SDValue();
5433     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5434       return SDValue();
5435     LastLoadedElt = i;
5436   }
5437
5438   // If we have found an entire vector of loads and undefs, then return a large
5439   // load of the entire vector width starting at the base pointer.  If we found
5440   // consecutive loads for the low half, generate a vzext_load node.
5441   if (LastLoadedElt == NumElems - 1) {
5442     assert(LDBase && "Did not find base load for merging consecutive loads");
5443     EVT EltVT = LDBase->getValueType(0);
5444     // Ensure that the input vector size for the merged loads matches the
5445     // cumulative size of the input elements.
5446     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5447       return SDValue();
5448
5449     if (isAfterLegalize &&
5450         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5451       return SDValue();
5452
5453     SDValue NewLd = SDValue();
5454
5455     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5456                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5457                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5458                         LDBase->getAlignment());
5459
5460     if (LDBase->hasAnyUseOfValue(1)) {
5461       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5462                                      SDValue(LDBase, 1),
5463                                      SDValue(NewLd.getNode(), 1));
5464       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5465       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5466                              SDValue(NewLd.getNode(), 1));
5467     }
5468
5469     return NewLd;
5470   }
5471
5472   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5473   //of a v4i32 / v4f32. It's probably worth generalizing.
5474   EVT EltVT = VT.getVectorElementType();
5475   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5476       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5477     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5478     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5479     SDValue ResNode =
5480         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5481                                 LDBase->getPointerInfo(),
5482                                 LDBase->getAlignment(),
5483                                 false/*isVolatile*/, true/*ReadMem*/,
5484                                 false/*WriteMem*/);
5485
5486     // Make sure the newly-created LOAD is in the same position as LDBase in
5487     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5488     // update uses of LDBase's output chain to use the TokenFactor.
5489     if (LDBase->hasAnyUseOfValue(1)) {
5490       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5491                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5492       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5493       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5494                              SDValue(ResNode.getNode(), 1));
5495     }
5496
5497     return DAG.getBitcast(VT, ResNode);
5498   }
5499   return SDValue();
5500 }
5501
5502 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5503 /// to generate a splat value for the following cases:
5504 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5505 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5506 /// a scalar load, or a constant.
5507 /// The VBROADCAST node is returned when a pattern is found,
5508 /// or SDValue() otherwise.
5509 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5510                                     SelectionDAG &DAG) {
5511   // VBROADCAST requires AVX.
5512   // TODO: Splats could be generated for non-AVX CPUs using SSE
5513   // instructions, but there's less potential gain for only 128-bit vectors.
5514   if (!Subtarget->hasAVX())
5515     return SDValue();
5516
5517   MVT VT = Op.getSimpleValueType();
5518   SDLoc dl(Op);
5519
5520   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5521          "Unsupported vector type for broadcast.");
5522
5523   SDValue Ld;
5524   bool ConstSplatVal;
5525
5526   switch (Op.getOpcode()) {
5527     default:
5528       // Unknown pattern found.
5529       return SDValue();
5530
5531     case ISD::BUILD_VECTOR: {
5532       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5533       BitVector UndefElements;
5534       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5535
5536       // We need a splat of a single value to use broadcast, and it doesn't
5537       // make any sense if the value is only in one element of the vector.
5538       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5539         return SDValue();
5540
5541       Ld = Splat;
5542       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5543                        Ld.getOpcode() == ISD::ConstantFP);
5544
5545       // Make sure that all of the users of a non-constant load are from the
5546       // BUILD_VECTOR node.
5547       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5548         return SDValue();
5549       break;
5550     }
5551
5552     case ISD::VECTOR_SHUFFLE: {
5553       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5554
5555       // Shuffles must have a splat mask where the first element is
5556       // broadcasted.
5557       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5558         return SDValue();
5559
5560       SDValue Sc = Op.getOperand(0);
5561       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5562           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5563
5564         if (!Subtarget->hasInt256())
5565           return SDValue();
5566
5567         // Use the register form of the broadcast instruction available on AVX2.
5568         if (VT.getSizeInBits() >= 256)
5569           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5570         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5571       }
5572
5573       Ld = Sc.getOperand(0);
5574       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5575                        Ld.getOpcode() == ISD::ConstantFP);
5576
5577       // The scalar_to_vector node and the suspected
5578       // load node must have exactly one user.
5579       // Constants may have multiple users.
5580
5581       // AVX-512 has register version of the broadcast
5582       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5583         Ld.getValueType().getSizeInBits() >= 32;
5584       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5585           !hasRegVer))
5586         return SDValue();
5587       break;
5588     }
5589   }
5590
5591   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5592   bool IsGE256 = (VT.getSizeInBits() >= 256);
5593
5594   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5595   // instruction to save 8 or more bytes of constant pool data.
5596   // TODO: If multiple splats are generated to load the same constant,
5597   // it may be detrimental to overall size. There needs to be a way to detect
5598   // that condition to know if this is truly a size win.
5599   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5600
5601   // Handle broadcasting a single constant scalar from the constant pool
5602   // into a vector.
5603   // On Sandybridge (no AVX2), it is still better to load a constant vector
5604   // from the constant pool and not to broadcast it from a scalar.
5605   // But override that restriction when optimizing for size.
5606   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5607   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5608     EVT CVT = Ld.getValueType();
5609     assert(!CVT.isVector() && "Must not broadcast a vector type");
5610
5611     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5612     // For size optimization, also splat v2f64 and v2i64, and for size opt
5613     // with AVX2, also splat i8 and i16.
5614     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5615     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5616         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5617       const Constant *C = nullptr;
5618       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5619         C = CI->getConstantIntValue();
5620       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5621         C = CF->getConstantFPValue();
5622
5623       assert(C && "Invalid constant type");
5624
5625       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5626       SDValue CP =
5627           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5628       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5629       Ld = DAG.getLoad(
5630           CVT, dl, DAG.getEntryNode(), CP,
5631           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5632           false, false, Alignment);
5633
5634       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5635     }
5636   }
5637
5638   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5639
5640   // Handle AVX2 in-register broadcasts.
5641   if (!IsLoad && Subtarget->hasInt256() &&
5642       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5643     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5644
5645   // The scalar source must be a normal load.
5646   if (!IsLoad)
5647     return SDValue();
5648
5649   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5650       (Subtarget->hasVLX() && ScalarSize == 64))
5651     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5652
5653   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5654   // double since there is no vbroadcastsd xmm
5655   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5656     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5657       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5658   }
5659
5660   // Unsupported broadcast.
5661   return SDValue();
5662 }
5663
5664 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5665 /// underlying vector and index.
5666 ///
5667 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5668 /// index.
5669 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5670                                          SDValue ExtIdx) {
5671   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5672   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5673     return Idx;
5674
5675   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5676   // lowered this:
5677   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5678   // to:
5679   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5680   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5681   //                           undef)
5682   //                       Constant<0>)
5683   // In this case the vector is the extract_subvector expression and the index
5684   // is 2, as specified by the shuffle.
5685   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5686   SDValue ShuffleVec = SVOp->getOperand(0);
5687   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5688   assert(ShuffleVecVT.getVectorElementType() ==
5689          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5690
5691   int ShuffleIdx = SVOp->getMaskElt(Idx);
5692   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5693     ExtractedFromVec = ShuffleVec;
5694     return ShuffleIdx;
5695   }
5696   return Idx;
5697 }
5698
5699 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5700   MVT VT = Op.getSimpleValueType();
5701
5702   // Skip if insert_vec_elt is not supported.
5703   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5704   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5705     return SDValue();
5706
5707   SDLoc DL(Op);
5708   unsigned NumElems = Op.getNumOperands();
5709
5710   SDValue VecIn1;
5711   SDValue VecIn2;
5712   SmallVector<unsigned, 4> InsertIndices;
5713   SmallVector<int, 8> Mask(NumElems, -1);
5714
5715   for (unsigned i = 0; i != NumElems; ++i) {
5716     unsigned Opc = Op.getOperand(i).getOpcode();
5717
5718     if (Opc == ISD::UNDEF)
5719       continue;
5720
5721     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5722       // Quit if more than 1 elements need inserting.
5723       if (InsertIndices.size() > 1)
5724         return SDValue();
5725
5726       InsertIndices.push_back(i);
5727       continue;
5728     }
5729
5730     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5731     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5732     // Quit if non-constant index.
5733     if (!isa<ConstantSDNode>(ExtIdx))
5734       return SDValue();
5735     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5736
5737     // Quit if extracted from vector of different type.
5738     if (ExtractedFromVec.getValueType() != VT)
5739       return SDValue();
5740
5741     if (!VecIn1.getNode())
5742       VecIn1 = ExtractedFromVec;
5743     else if (VecIn1 != ExtractedFromVec) {
5744       if (!VecIn2.getNode())
5745         VecIn2 = ExtractedFromVec;
5746       else if (VecIn2 != ExtractedFromVec)
5747         // Quit if more than 2 vectors to shuffle
5748         return SDValue();
5749     }
5750
5751     if (ExtractedFromVec == VecIn1)
5752       Mask[i] = Idx;
5753     else if (ExtractedFromVec == VecIn2)
5754       Mask[i] = Idx + NumElems;
5755   }
5756
5757   if (!VecIn1.getNode())
5758     return SDValue();
5759
5760   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5761   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5762   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5763     unsigned Idx = InsertIndices[i];
5764     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5765                      DAG.getIntPtrConstant(Idx, DL));
5766   }
5767
5768   return NV;
5769 }
5770
5771 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5772   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5773          Op.getScalarValueSizeInBits() == 1 &&
5774          "Can not convert non-constant vector");
5775   uint64_t Immediate = 0;
5776   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5777     SDValue In = Op.getOperand(idx);
5778     if (In.getOpcode() != ISD::UNDEF)
5779       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5780   }
5781   SDLoc dl(Op);
5782   MVT VT =
5783    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5784   return DAG.getConstant(Immediate, dl, VT);
5785 }
5786 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5787 SDValue
5788 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5789
5790   MVT VT = Op.getSimpleValueType();
5791   assert((VT.getVectorElementType() == MVT::i1) &&
5792          "Unexpected type in LowerBUILD_VECTORvXi1!");
5793
5794   SDLoc dl(Op);
5795   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5796     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5797     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5798     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5799   }
5800
5801   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5802     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5803     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5804     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5805   }
5806
5807   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5808     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5809     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5810       return DAG.getBitcast(VT, Imm);
5811     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5812     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5813                         DAG.getIntPtrConstant(0, dl));
5814   }
5815
5816   // Vector has one or more non-const elements
5817   uint64_t Immediate = 0;
5818   SmallVector<unsigned, 16> NonConstIdx;
5819   bool IsSplat = true;
5820   bool HasConstElts = false;
5821   int SplatIdx = -1;
5822   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5823     SDValue In = Op.getOperand(idx);
5824     if (In.getOpcode() == ISD::UNDEF)
5825       continue;
5826     if (!isa<ConstantSDNode>(In))
5827       NonConstIdx.push_back(idx);
5828     else {
5829       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5830       HasConstElts = true;
5831     }
5832     if (SplatIdx == -1)
5833       SplatIdx = idx;
5834     else if (In != Op.getOperand(SplatIdx))
5835       IsSplat = false;
5836   }
5837
5838   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5839   if (IsSplat)
5840     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5841                        DAG.getConstant(1, dl, VT),
5842                        DAG.getConstant(0, dl, VT));
5843
5844   // insert elements one by one
5845   SDValue DstVec;
5846   SDValue Imm;
5847   if (Immediate) {
5848     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5849     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5850   }
5851   else if (HasConstElts)
5852     Imm = DAG.getConstant(0, dl, VT);
5853   else
5854     Imm = DAG.getUNDEF(VT);
5855   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5856     DstVec = DAG.getBitcast(VT, Imm);
5857   else {
5858     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5859     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5860                          DAG.getIntPtrConstant(0, dl));
5861   }
5862
5863   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5864     unsigned InsertIdx = NonConstIdx[i];
5865     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5866                          Op.getOperand(InsertIdx),
5867                          DAG.getIntPtrConstant(InsertIdx, dl));
5868   }
5869   return DstVec;
5870 }
5871
5872 /// \brief Return true if \p N implements a horizontal binop and return the
5873 /// operands for the horizontal binop into V0 and V1.
5874 ///
5875 /// This is a helper function of LowerToHorizontalOp().
5876 /// This function checks that the build_vector \p N in input implements a
5877 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5878 /// operation to match.
5879 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5880 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5881 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5882 /// arithmetic sub.
5883 ///
5884 /// This function only analyzes elements of \p N whose indices are
5885 /// in range [BaseIdx, LastIdx).
5886 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5887                               SelectionDAG &DAG,
5888                               unsigned BaseIdx, unsigned LastIdx,
5889                               SDValue &V0, SDValue &V1) {
5890   EVT VT = N->getValueType(0);
5891
5892   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5893   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5894          "Invalid Vector in input!");
5895
5896   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5897   bool CanFold = true;
5898   unsigned ExpectedVExtractIdx = BaseIdx;
5899   unsigned NumElts = LastIdx - BaseIdx;
5900   V0 = DAG.getUNDEF(VT);
5901   V1 = DAG.getUNDEF(VT);
5902
5903   // Check if N implements a horizontal binop.
5904   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5905     SDValue Op = N->getOperand(i + BaseIdx);
5906
5907     // Skip UNDEFs.
5908     if (Op->getOpcode() == ISD::UNDEF) {
5909       // Update the expected vector extract index.
5910       if (i * 2 == NumElts)
5911         ExpectedVExtractIdx = BaseIdx;
5912       ExpectedVExtractIdx += 2;
5913       continue;
5914     }
5915
5916     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5917
5918     if (!CanFold)
5919       break;
5920
5921     SDValue Op0 = Op.getOperand(0);
5922     SDValue Op1 = Op.getOperand(1);
5923
5924     // Try to match the following pattern:
5925     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5926     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5927         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5928         Op0.getOperand(0) == Op1.getOperand(0) &&
5929         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5930         isa<ConstantSDNode>(Op1.getOperand(1)));
5931     if (!CanFold)
5932       break;
5933
5934     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5935     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5936
5937     if (i * 2 < NumElts) {
5938       if (V0.getOpcode() == ISD::UNDEF) {
5939         V0 = Op0.getOperand(0);
5940         if (V0.getValueType() != VT)
5941           return false;
5942       }
5943     } else {
5944       if (V1.getOpcode() == ISD::UNDEF) {
5945         V1 = Op0.getOperand(0);
5946         if (V1.getValueType() != VT)
5947           return false;
5948       }
5949       if (i * 2 == NumElts)
5950         ExpectedVExtractIdx = BaseIdx;
5951     }
5952
5953     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5954     if (I0 == ExpectedVExtractIdx)
5955       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5956     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5957       // Try to match the following dag sequence:
5958       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5959       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5960     } else
5961       CanFold = false;
5962
5963     ExpectedVExtractIdx += 2;
5964   }
5965
5966   return CanFold;
5967 }
5968
5969 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5970 /// a concat_vector.
5971 ///
5972 /// This is a helper function of LowerToHorizontalOp().
5973 /// This function expects two 256-bit vectors called V0 and V1.
5974 /// At first, each vector is split into two separate 128-bit vectors.
5975 /// Then, the resulting 128-bit vectors are used to implement two
5976 /// horizontal binary operations.
5977 ///
5978 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5979 ///
5980 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5981 /// the two new horizontal binop.
5982 /// When Mode is set, the first horizontal binop dag node would take as input
5983 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5984 /// horizontal binop dag node would take as input the lower 128-bit of V1
5985 /// and the upper 128-bit of V1.
5986 ///   Example:
5987 ///     HADD V0_LO, V0_HI
5988 ///     HADD V1_LO, V1_HI
5989 ///
5990 /// Otherwise, the first horizontal binop dag node takes as input the lower
5991 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5992 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5993 ///   Example:
5994 ///     HADD V0_LO, V1_LO
5995 ///     HADD V0_HI, V1_HI
5996 ///
5997 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5998 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5999 /// the upper 128-bits of the result.
6000 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6001                                      SDLoc DL, SelectionDAG &DAG,
6002                                      unsigned X86Opcode, bool Mode,
6003                                      bool isUndefLO, bool isUndefHI) {
6004   EVT VT = V0.getValueType();
6005   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6006          "Invalid nodes in input!");
6007
6008   unsigned NumElts = VT.getVectorNumElements();
6009   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6010   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6011   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6012   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6013   EVT NewVT = V0_LO.getValueType();
6014
6015   SDValue LO = DAG.getUNDEF(NewVT);
6016   SDValue HI = DAG.getUNDEF(NewVT);
6017
6018   if (Mode) {
6019     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6020     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6021       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6022     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6023       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6024   } else {
6025     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6026     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6027                        V1_LO->getOpcode() != ISD::UNDEF))
6028       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6029
6030     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6031                        V1_HI->getOpcode() != ISD::UNDEF))
6032       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6033   }
6034
6035   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6036 }
6037
6038 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6039 /// node.
6040 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6041                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6042   MVT VT = BV->getSimpleValueType(0);
6043   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6044       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6045     return SDValue();
6046
6047   SDLoc DL(BV);
6048   unsigned NumElts = VT.getVectorNumElements();
6049   SDValue InVec0 = DAG.getUNDEF(VT);
6050   SDValue InVec1 = DAG.getUNDEF(VT);
6051
6052   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6053           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6054
6055   // Odd-numbered elements in the input build vector are obtained from
6056   // adding two integer/float elements.
6057   // Even-numbered elements in the input build vector are obtained from
6058   // subtracting two integer/float elements.
6059   unsigned ExpectedOpcode = ISD::FSUB;
6060   unsigned NextExpectedOpcode = ISD::FADD;
6061   bool AddFound = false;
6062   bool SubFound = false;
6063
6064   for (unsigned i = 0, e = NumElts; i != e; ++i) {
6065     SDValue Op = BV->getOperand(i);
6066
6067     // Skip 'undef' values.
6068     unsigned Opcode = Op.getOpcode();
6069     if (Opcode == ISD::UNDEF) {
6070       std::swap(ExpectedOpcode, NextExpectedOpcode);
6071       continue;
6072     }
6073
6074     // Early exit if we found an unexpected opcode.
6075     if (Opcode != ExpectedOpcode)
6076       return SDValue();
6077
6078     SDValue Op0 = Op.getOperand(0);
6079     SDValue Op1 = Op.getOperand(1);
6080
6081     // Try to match the following pattern:
6082     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6083     // Early exit if we cannot match that sequence.
6084     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6085         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6086         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6087         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6088         Op0.getOperand(1) != Op1.getOperand(1))
6089       return SDValue();
6090
6091     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6092     if (I0 != i)
6093       return SDValue();
6094
6095     // We found a valid add/sub node. Update the information accordingly.
6096     if (i & 1)
6097       AddFound = true;
6098     else
6099       SubFound = true;
6100
6101     // Update InVec0 and InVec1.
6102     if (InVec0.getOpcode() == ISD::UNDEF) {
6103       InVec0 = Op0.getOperand(0);
6104       if (InVec0.getSimpleValueType() != VT)
6105         return SDValue();
6106     }
6107     if (InVec1.getOpcode() == ISD::UNDEF) {
6108       InVec1 = Op1.getOperand(0);
6109       if (InVec1.getSimpleValueType() != VT)
6110         return SDValue();
6111     }
6112
6113     // Make sure that operands in input to each add/sub node always
6114     // come from a same pair of vectors.
6115     if (InVec0 != Op0.getOperand(0)) {
6116       if (ExpectedOpcode == ISD::FSUB)
6117         return SDValue();
6118
6119       // FADD is commutable. Try to commute the operands
6120       // and then test again.
6121       std::swap(Op0, Op1);
6122       if (InVec0 != Op0.getOperand(0))
6123         return SDValue();
6124     }
6125
6126     if (InVec1 != Op1.getOperand(0))
6127       return SDValue();
6128
6129     // Update the pair of expected opcodes.
6130     std::swap(ExpectedOpcode, NextExpectedOpcode);
6131   }
6132
6133   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6134   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6135       InVec1.getOpcode() != ISD::UNDEF)
6136     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6137
6138   return SDValue();
6139 }
6140
6141 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6142 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6143                                    const X86Subtarget *Subtarget,
6144                                    SelectionDAG &DAG) {
6145   MVT VT = BV->getSimpleValueType(0);
6146   unsigned NumElts = VT.getVectorNumElements();
6147   unsigned NumUndefsLO = 0;
6148   unsigned NumUndefsHI = 0;
6149   unsigned Half = NumElts/2;
6150
6151   // Count the number of UNDEF operands in the build_vector in input.
6152   for (unsigned i = 0, e = Half; i != e; ++i)
6153     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6154       NumUndefsLO++;
6155
6156   for (unsigned i = Half, e = NumElts; i != e; ++i)
6157     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6158       NumUndefsHI++;
6159
6160   // Early exit if this is either a build_vector of all UNDEFs or all the
6161   // operands but one are UNDEF.
6162   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6163     return SDValue();
6164
6165   SDLoc DL(BV);
6166   SDValue InVec0, InVec1;
6167   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6168     // Try to match an SSE3 float HADD/HSUB.
6169     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6170       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6171
6172     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6173       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6174   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6175     // Try to match an SSSE3 integer HADD/HSUB.
6176     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6177       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6178
6179     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6180       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6181   }
6182
6183   if (!Subtarget->hasAVX())
6184     return SDValue();
6185
6186   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6187     // Try to match an AVX horizontal add/sub of packed single/double
6188     // precision floating point values from 256-bit vectors.
6189     SDValue InVec2, InVec3;
6190     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6191         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6192         ((InVec0.getOpcode() == ISD::UNDEF ||
6193           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6194         ((InVec1.getOpcode() == ISD::UNDEF ||
6195           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6196       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6197
6198     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6199         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6200         ((InVec0.getOpcode() == ISD::UNDEF ||
6201           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6202         ((InVec1.getOpcode() == ISD::UNDEF ||
6203           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6204       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6205   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6206     // Try to match an AVX2 horizontal add/sub of signed integers.
6207     SDValue InVec2, InVec3;
6208     unsigned X86Opcode;
6209     bool CanFold = true;
6210
6211     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6212         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6213         ((InVec0.getOpcode() == ISD::UNDEF ||
6214           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6215         ((InVec1.getOpcode() == ISD::UNDEF ||
6216           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6217       X86Opcode = X86ISD::HADD;
6218     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6219         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6220         ((InVec0.getOpcode() == ISD::UNDEF ||
6221           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6222         ((InVec1.getOpcode() == ISD::UNDEF ||
6223           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6224       X86Opcode = X86ISD::HSUB;
6225     else
6226       CanFold = false;
6227
6228     if (CanFold) {
6229       // Fold this build_vector into a single horizontal add/sub.
6230       // Do this only if the target has AVX2.
6231       if (Subtarget->hasAVX2())
6232         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6233
6234       // Do not try to expand this build_vector into a pair of horizontal
6235       // add/sub if we can emit a pair of scalar add/sub.
6236       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6237         return SDValue();
6238
6239       // Convert this build_vector into a pair of horizontal binop followed by
6240       // a concat vector.
6241       bool isUndefLO = NumUndefsLO == Half;
6242       bool isUndefHI = NumUndefsHI == Half;
6243       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6244                                    isUndefLO, isUndefHI);
6245     }
6246   }
6247
6248   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6249        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6250     unsigned X86Opcode;
6251     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6252       X86Opcode = X86ISD::HADD;
6253     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6254       X86Opcode = X86ISD::HSUB;
6255     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6256       X86Opcode = X86ISD::FHADD;
6257     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6258       X86Opcode = X86ISD::FHSUB;
6259     else
6260       return SDValue();
6261
6262     // Don't try to expand this build_vector into a pair of horizontal add/sub
6263     // if we can simply emit a pair of scalar add/sub.
6264     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6265       return SDValue();
6266
6267     // Convert this build_vector into two horizontal add/sub followed by
6268     // a concat vector.
6269     bool isUndefLO = NumUndefsLO == Half;
6270     bool isUndefHI = NumUndefsHI == Half;
6271     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6272                                  isUndefLO, isUndefHI);
6273   }
6274
6275   return SDValue();
6276 }
6277
6278 SDValue
6279 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6280   SDLoc dl(Op);
6281
6282   MVT VT = Op.getSimpleValueType();
6283   MVT ExtVT = VT.getVectorElementType();
6284   unsigned NumElems = Op.getNumOperands();
6285
6286   // Generate vectors for predicate vectors.
6287   if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6288     return LowerBUILD_VECTORvXi1(Op, DAG);
6289
6290   // Vectors containing all zeros can be matched by pxor and xorps later
6291   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6292     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6293     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6294     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6295       return Op;
6296
6297     return getZeroVector(VT, Subtarget, DAG, dl);
6298   }
6299
6300   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6301   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6302   // vpcmpeqd on 256-bit vectors.
6303   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6304     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6305       return Op;
6306
6307     if (!VT.is512BitVector())
6308       return getOnesVector(VT, Subtarget, DAG, dl);
6309   }
6310
6311   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6312   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6313     return AddSub;
6314   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6315     return HorizontalOp;
6316   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6317     return Broadcast;
6318
6319   unsigned EVTBits = ExtVT.getSizeInBits();
6320
6321   unsigned NumZero  = 0;
6322   unsigned NumNonZero = 0;
6323   uint64_t NonZeros = 0;
6324   bool IsAllConstants = true;
6325   SmallSet<SDValue, 8> Values;
6326   for (unsigned i = 0; i < NumElems; ++i) {
6327     SDValue Elt = Op.getOperand(i);
6328     if (Elt.getOpcode() == ISD::UNDEF)
6329       continue;
6330     Values.insert(Elt);
6331     if (Elt.getOpcode() != ISD::Constant &&
6332         Elt.getOpcode() != ISD::ConstantFP)
6333       IsAllConstants = false;
6334     if (X86::isZeroNode(Elt))
6335       NumZero++;
6336     else {
6337       assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6338       NonZeros |= ((uint64_t)1 << i);
6339       NumNonZero++;
6340     }
6341   }
6342
6343   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6344   if (NumNonZero == 0)
6345     return DAG.getUNDEF(VT);
6346
6347   // Special case for single non-zero, non-undef, element.
6348   if (NumNonZero == 1) {
6349     unsigned Idx = countTrailingZeros(NonZeros);
6350     SDValue Item = Op.getOperand(Idx);
6351
6352     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6353     // the value are obviously zero, truncate the value to i32 and do the
6354     // insertion that way.  Only do this if the value is non-constant or if the
6355     // value is a constant being inserted into element 0.  It is cheaper to do
6356     // a constant pool load than it is to do a movd + shuffle.
6357     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6358         (!IsAllConstants || Idx == 0)) {
6359       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6360         // Handle SSE only.
6361         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6362         MVT VecVT = MVT::v4i32;
6363
6364         // Truncate the value (which may itself be a constant) to i32, and
6365         // convert it to a vector with movd (S2V+shuffle to zero extend).
6366         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6367         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6368         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6369                                       Item, Idx * 2, true, Subtarget, DAG));
6370       }
6371     }
6372
6373     // If we have a constant or non-constant insertion into the low element of
6374     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6375     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6376     // depending on what the source datatype is.
6377     if (Idx == 0) {
6378       if (NumZero == 0)
6379         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6380
6381       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6382           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6383         if (VT.is512BitVector()) {
6384           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6385           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6386                              Item, DAG.getIntPtrConstant(0, dl));
6387         }
6388         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6389                "Expected an SSE value type!");
6390         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6391         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6392         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6393       }
6394
6395       // We can't directly insert an i8 or i16 into a vector, so zero extend
6396       // it to i32 first.
6397       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6398         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6399         if (VT.is256BitVector()) {
6400           if (Subtarget->hasAVX()) {
6401             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6402             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6403           } else {
6404             // Without AVX, we need to extend to a 128-bit vector and then
6405             // insert into the 256-bit vector.
6406             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6407             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6408             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6409           }
6410         } else {
6411           assert(VT.is128BitVector() && "Expected an SSE value type!");
6412           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6413           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6414         }
6415         return DAG.getBitcast(VT, Item);
6416       }
6417     }
6418
6419     // Is it a vector logical left shift?
6420     if (NumElems == 2 && Idx == 1 &&
6421         X86::isZeroNode(Op.getOperand(0)) &&
6422         !X86::isZeroNode(Op.getOperand(1))) {
6423       unsigned NumBits = VT.getSizeInBits();
6424       return getVShift(true, VT,
6425                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6426                                    VT, Op.getOperand(1)),
6427                        NumBits/2, DAG, *this, dl);
6428     }
6429
6430     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6431       return SDValue();
6432
6433     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6434     // is a non-constant being inserted into an element other than the low one,
6435     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6436     // movd/movss) to move this into the low element, then shuffle it into
6437     // place.
6438     if (EVTBits == 32) {
6439       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6440       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6441     }
6442   }
6443
6444   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6445   if (Values.size() == 1) {
6446     if (EVTBits == 32) {
6447       // Instead of a shuffle like this:
6448       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6449       // Check if it's possible to issue this instead.
6450       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6451       unsigned Idx = countTrailingZeros(NonZeros);
6452       SDValue Item = Op.getOperand(Idx);
6453       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6454         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6455     }
6456     return SDValue();
6457   }
6458
6459   // A vector full of immediates; various special cases are already
6460   // handled, so this is best done with a single constant-pool load.
6461   if (IsAllConstants)
6462     return SDValue();
6463
6464   // For AVX-length vectors, see if we can use a vector load to get all of the
6465   // elements, otherwise build the individual 128-bit pieces and use
6466   // shuffles to put them in place.
6467   if (VT.is256BitVector() || VT.is512BitVector()) {
6468     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6469
6470     // Check for a build vector of consecutive loads.
6471     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6472       return LD;
6473
6474     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6475
6476     // Build both the lower and upper subvector.
6477     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6478                                 makeArrayRef(&V[0], NumElems/2));
6479     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6480                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6481
6482     // Recreate the wider vector with the lower and upper part.
6483     if (VT.is256BitVector())
6484       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6485     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6486   }
6487
6488   // Let legalizer expand 2-wide build_vectors.
6489   if (EVTBits == 64) {
6490     if (NumNonZero == 1) {
6491       // One half is zero or undef.
6492       unsigned Idx = countTrailingZeros(NonZeros);
6493       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6494                                Op.getOperand(Idx));
6495       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6496     }
6497     return SDValue();
6498   }
6499
6500   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6501   if (EVTBits == 8 && NumElems == 16)
6502     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6503                                           DAG, Subtarget, *this))
6504       return V;
6505
6506   if (EVTBits == 16 && NumElems == 8)
6507     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6508                                           DAG, Subtarget, *this))
6509       return V;
6510
6511   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6512   if (EVTBits == 32 && NumElems == 4)
6513     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6514       return V;
6515
6516   // If element VT is == 32 bits, turn it into a number of shuffles.
6517   SmallVector<SDValue, 8> V(NumElems);
6518   if (NumElems == 4 && NumZero > 0) {
6519     for (unsigned i = 0; i < 4; ++i) {
6520       bool isZero = !(NonZeros & (1ULL << i));
6521       if (isZero)
6522         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6523       else
6524         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6525     }
6526
6527     for (unsigned i = 0; i < 2; ++i) {
6528       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6529         default: break;
6530         case 0:
6531           V[i] = V[i*2];  // Must be a zero vector.
6532           break;
6533         case 1:
6534           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6535           break;
6536         case 2:
6537           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6538           break;
6539         case 3:
6540           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6541           break;
6542       }
6543     }
6544
6545     bool Reverse1 = (NonZeros & 0x3) == 2;
6546     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6547     int MaskVec[] = {
6548       Reverse1 ? 1 : 0,
6549       Reverse1 ? 0 : 1,
6550       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6551       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6552     };
6553     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6554   }
6555
6556   if (Values.size() > 1 && VT.is128BitVector()) {
6557     // Check for a build vector of consecutive loads.
6558     for (unsigned i = 0; i < NumElems; ++i)
6559       V[i] = Op.getOperand(i);
6560
6561     // Check for elements which are consecutive loads.
6562     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6563       return LD;
6564
6565     // Check for a build vector from mostly shuffle plus few inserting.
6566     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6567       return Sh;
6568
6569     // For SSE 4.1, use insertps to put the high elements into the low element.
6570     if (Subtarget->hasSSE41()) {
6571       SDValue Result;
6572       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6573         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6574       else
6575         Result = DAG.getUNDEF(VT);
6576
6577       for (unsigned i = 1; i < NumElems; ++i) {
6578         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6579         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6580                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6581       }
6582       return Result;
6583     }
6584
6585     // Otherwise, expand into a number of unpckl*, start by extending each of
6586     // our (non-undef) elements to the full vector width with the element in the
6587     // bottom slot of the vector (which generates no code for SSE).
6588     for (unsigned i = 0; i < NumElems; ++i) {
6589       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6590         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6591       else
6592         V[i] = DAG.getUNDEF(VT);
6593     }
6594
6595     // Next, we iteratively mix elements, e.g. for v4f32:
6596     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6597     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6598     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6599     unsigned EltStride = NumElems >> 1;
6600     while (EltStride != 0) {
6601       for (unsigned i = 0; i < EltStride; ++i) {
6602         // If V[i+EltStride] is undef and this is the first round of mixing,
6603         // then it is safe to just drop this shuffle: V[i] is already in the
6604         // right place, the one element (since it's the first round) being
6605         // inserted as undef can be dropped.  This isn't safe for successive
6606         // rounds because they will permute elements within both vectors.
6607         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6608             EltStride == NumElems/2)
6609           continue;
6610
6611         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6612       }
6613       EltStride >>= 1;
6614     }
6615     return V[0];
6616   }
6617   return SDValue();
6618 }
6619
6620 // 256-bit AVX can use the vinsertf128 instruction
6621 // to create 256-bit vectors from two other 128-bit ones.
6622 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6623   SDLoc dl(Op);
6624   MVT ResVT = Op.getSimpleValueType();
6625
6626   assert((ResVT.is256BitVector() ||
6627           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6628
6629   SDValue V1 = Op.getOperand(0);
6630   SDValue V2 = Op.getOperand(1);
6631   unsigned NumElems = ResVT.getVectorNumElements();
6632   if (ResVT.is256BitVector())
6633     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6634
6635   if (Op.getNumOperands() == 4) {
6636     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6637                                   ResVT.getVectorNumElements()/2);
6638     SDValue V3 = Op.getOperand(2);
6639     SDValue V4 = Op.getOperand(3);
6640     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6641       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6642   }
6643   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6644 }
6645
6646 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6647                                        const X86Subtarget *Subtarget,
6648                                        SelectionDAG & DAG) {
6649   SDLoc dl(Op);
6650   MVT ResVT = Op.getSimpleValueType();
6651   unsigned NumOfOperands = Op.getNumOperands();
6652
6653   assert(isPowerOf2_32(NumOfOperands) &&
6654          "Unexpected number of operands in CONCAT_VECTORS");
6655
6656   SDValue Undef = DAG.getUNDEF(ResVT);
6657   if (NumOfOperands > 2) {
6658     // Specialize the cases when all, or all but one, of the operands are undef.
6659     unsigned NumOfDefinedOps = 0;
6660     unsigned OpIdx = 0;
6661     for (unsigned i = 0; i < NumOfOperands; i++)
6662       if (!Op.getOperand(i).isUndef()) {
6663         NumOfDefinedOps++;
6664         OpIdx = i;
6665       }
6666     if (NumOfDefinedOps == 0)
6667       return Undef;
6668     if (NumOfDefinedOps == 1) {
6669       unsigned SubVecNumElts =
6670         Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6671       SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6672       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6673                          Op.getOperand(OpIdx), IdxVal);
6674     }
6675
6676     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6677                                   ResVT.getVectorNumElements()/2);
6678     SmallVector<SDValue, 2> Ops;
6679     for (unsigned i = 0; i < NumOfOperands/2; i++)
6680       Ops.push_back(Op.getOperand(i));
6681     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6682     Ops.clear();
6683     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6684       Ops.push_back(Op.getOperand(i));
6685     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6686     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6687   }
6688
6689   // 2 operands
6690   SDValue V1 = Op.getOperand(0);
6691   SDValue V2 = Op.getOperand(1);
6692   unsigned NumElems = ResVT.getVectorNumElements();
6693   assert(V1.getValueType() == V2.getValueType() &&
6694          V1.getValueType().getVectorNumElements() == NumElems/2 &&
6695          "Unexpected operands in CONCAT_VECTORS");
6696
6697   if (ResVT.getSizeInBits() >= 16)
6698     return Op; // The operation is legal with KUNPCK
6699
6700   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6701   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6702   SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6703   if (IsZeroV1 && IsZeroV2)
6704     return ZeroVec;
6705
6706   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6707   if (V2.isUndef())
6708     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6709   if (IsZeroV2)
6710     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6711
6712   SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6713   if (V1.isUndef())
6714     V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6715
6716   if (IsZeroV1)
6717     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6718
6719   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6720   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6721 }
6722
6723 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6724                                    const X86Subtarget *Subtarget,
6725                                    SelectionDAG &DAG) {
6726   MVT VT = Op.getSimpleValueType();
6727   if (VT.getVectorElementType() == MVT::i1)
6728     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6729
6730   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6731          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6732           Op.getNumOperands() == 4)));
6733
6734   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6735   // from two other 128-bit ones.
6736
6737   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6738   return LowerAVXCONCAT_VECTORS(Op, DAG);
6739 }
6740
6741 //===----------------------------------------------------------------------===//
6742 // Vector shuffle lowering
6743 //
6744 // This is an experimental code path for lowering vector shuffles on x86. It is
6745 // designed to handle arbitrary vector shuffles and blends, gracefully
6746 // degrading performance as necessary. It works hard to recognize idiomatic
6747 // shuffles and lower them to optimal instruction patterns without leaving
6748 // a framework that allows reasonably efficient handling of all vector shuffle
6749 // patterns.
6750 //===----------------------------------------------------------------------===//
6751
6752 /// \brief Tiny helper function to identify a no-op mask.
6753 ///
6754 /// This is a somewhat boring predicate function. It checks whether the mask
6755 /// array input, which is assumed to be a single-input shuffle mask of the kind
6756 /// used by the X86 shuffle instructions (not a fully general
6757 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6758 /// in-place shuffle are 'no-op's.
6759 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6760   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6761     if (Mask[i] != -1 && Mask[i] != i)
6762       return false;
6763   return true;
6764 }
6765
6766 /// \brief Helper function to classify a mask as a single-input mask.
6767 ///
6768 /// This isn't a generic single-input test because in the vector shuffle
6769 /// lowering we canonicalize single inputs to be the first input operand. This
6770 /// means we can more quickly test for a single input by only checking whether
6771 /// an input from the second operand exists. We also assume that the size of
6772 /// mask corresponds to the size of the input vectors which isn't true in the
6773 /// fully general case.
6774 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6775   for (int M : Mask)
6776     if (M >= (int)Mask.size())
6777       return false;
6778   return true;
6779 }
6780
6781 /// \brief Test whether there are elements crossing 128-bit lanes in this
6782 /// shuffle mask.
6783 ///
6784 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6785 /// and we routinely test for these.
6786 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6787   int LaneSize = 128 / VT.getScalarSizeInBits();
6788   int Size = Mask.size();
6789   for (int i = 0; i < Size; ++i)
6790     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6791       return true;
6792   return false;
6793 }
6794
6795 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6796 ///
6797 /// This checks a shuffle mask to see if it is performing the same
6798 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6799 /// that it is also not lane-crossing. It may however involve a blend from the
6800 /// same lane of a second vector.
6801 ///
6802 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6803 /// non-trivial to compute in the face of undef lanes. The representation is
6804 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6805 /// entries from both V1 and V2 inputs to the wider mask.
6806 static bool
6807 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6808                                 SmallVectorImpl<int> &RepeatedMask) {
6809   int LaneSize = 128 / VT.getScalarSizeInBits();
6810   RepeatedMask.resize(LaneSize, -1);
6811   int Size = Mask.size();
6812   for (int i = 0; i < Size; ++i) {
6813     if (Mask[i] < 0)
6814       continue;
6815     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6816       // This entry crosses lanes, so there is no way to model this shuffle.
6817       return false;
6818
6819     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6820     if (RepeatedMask[i % LaneSize] == -1)
6821       // This is the first non-undef entry in this slot of a 128-bit lane.
6822       RepeatedMask[i % LaneSize] =
6823           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6824     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6825       // Found a mismatch with the repeated mask.
6826       return false;
6827   }
6828   return true;
6829 }
6830
6831 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6832 /// arguments.
6833 ///
6834 /// This is a fast way to test a shuffle mask against a fixed pattern:
6835 ///
6836 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6837 ///
6838 /// It returns true if the mask is exactly as wide as the argument list, and
6839 /// each element of the mask is either -1 (signifying undef) or the value given
6840 /// in the argument.
6841 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6842                                 ArrayRef<int> ExpectedMask) {
6843   if (Mask.size() != ExpectedMask.size())
6844     return false;
6845
6846   int Size = Mask.size();
6847
6848   // If the values are build vectors, we can look through them to find
6849   // equivalent inputs that make the shuffles equivalent.
6850   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6851   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6852
6853   for (int i = 0; i < Size; ++i)
6854     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6855       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6856       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6857       if (!MaskBV || !ExpectedBV ||
6858           MaskBV->getOperand(Mask[i] % Size) !=
6859               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6860         return false;
6861     }
6862
6863   return true;
6864 }
6865
6866 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6867 ///
6868 /// This helper function produces an 8-bit shuffle immediate corresponding to
6869 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6870 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6871 /// example.
6872 ///
6873 /// NB: We rely heavily on "undef" masks preserving the input lane.
6874 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6875                                           SelectionDAG &DAG) {
6876   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6877   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6878   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6879   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6880   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6881
6882   unsigned Imm = 0;
6883   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6884   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6885   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6886   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6887   return DAG.getConstant(Imm, DL, MVT::i8);
6888 }
6889
6890 /// \brief Compute whether each element of a shuffle is zeroable.
6891 ///
6892 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6893 /// Either it is an undef element in the shuffle mask, the element of the input
6894 /// referenced is undef, or the element of the input referenced is known to be
6895 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6896 /// as many lanes with this technique as possible to simplify the remaining
6897 /// shuffle.
6898 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6899                                                      SDValue V1, SDValue V2) {
6900   SmallBitVector Zeroable(Mask.size(), false);
6901
6902   while (V1.getOpcode() == ISD::BITCAST)
6903     V1 = V1->getOperand(0);
6904   while (V2.getOpcode() == ISD::BITCAST)
6905     V2 = V2->getOperand(0);
6906
6907   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6908   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6909
6910   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6911     int M = Mask[i];
6912     // Handle the easy cases.
6913     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6914       Zeroable[i] = true;
6915       continue;
6916     }
6917
6918     // If this is an index into a build_vector node (which has the same number
6919     // of elements), dig out the input value and use it.
6920     SDValue V = M < Size ? V1 : V2;
6921     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6922       continue;
6923
6924     SDValue Input = V.getOperand(M % Size);
6925     // The UNDEF opcode check really should be dead code here, but not quite
6926     // worth asserting on (it isn't invalid, just unexpected).
6927     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6928       Zeroable[i] = true;
6929   }
6930
6931   return Zeroable;
6932 }
6933
6934 // X86 has dedicated unpack instructions that can handle specific blend
6935 // operations: UNPCKH and UNPCKL.
6936 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6937                                            SDValue V1, SDValue V2,
6938                                            SelectionDAG &DAG) {
6939   int NumElts = VT.getVectorNumElements();
6940   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6941   SmallVector<int, 8> Unpckl;
6942   SmallVector<int, 8> Unpckh;
6943
6944   for (int i = 0; i < NumElts; ++i) {
6945     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6946     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6947     int HiPos = LoPos + NumEltsInLane / 2;
6948     Unpckl.push_back(LoPos);
6949     Unpckh.push_back(HiPos);
6950   }
6951
6952   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6953     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6954   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6955     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6956
6957   // Commute and try again.
6958   ShuffleVectorSDNode::commuteMask(Unpckl);
6959   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6960     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6961
6962   ShuffleVectorSDNode::commuteMask(Unpckh);
6963   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6964     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6965
6966   return SDValue();
6967 }
6968
6969 /// \brief Try to emit a bitmask instruction for a shuffle.
6970 ///
6971 /// This handles cases where we can model a blend exactly as a bitmask due to
6972 /// one of the inputs being zeroable.
6973 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6974                                            SDValue V2, ArrayRef<int> Mask,
6975                                            SelectionDAG &DAG) {
6976   MVT EltVT = VT.getVectorElementType();
6977   int NumEltBits = EltVT.getSizeInBits();
6978   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6979   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6980   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6981                                     IntEltVT);
6982   if (EltVT.isFloatingPoint()) {
6983     Zero = DAG.getBitcast(EltVT, Zero);
6984     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6985   }
6986   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6987   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6988   SDValue V;
6989   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6990     if (Zeroable[i])
6991       continue;
6992     if (Mask[i] % Size != i)
6993       return SDValue(); // Not a blend.
6994     if (!V)
6995       V = Mask[i] < Size ? V1 : V2;
6996     else if (V != (Mask[i] < Size ? V1 : V2))
6997       return SDValue(); // Can only let one input through the mask.
6998
6999     VMaskOps[i] = AllOnes;
7000   }
7001   if (!V)
7002     return SDValue(); // No non-zeroable elements!
7003
7004   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
7005   V = DAG.getNode(VT.isFloatingPoint()
7006                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7007                   DL, VT, V, VMask);
7008   return V;
7009 }
7010
7011 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7012 ///
7013 /// This is used as a fallback approach when first class blend instructions are
7014 /// unavailable. Currently it is only suitable for integer vectors, but could
7015 /// be generalized for floating point vectors if desirable.
7016 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
7017                                             SDValue V2, ArrayRef<int> Mask,
7018                                             SelectionDAG &DAG) {
7019   assert(VT.isInteger() && "Only supports integer vector types!");
7020   MVT EltVT = VT.getVectorElementType();
7021   int NumEltBits = EltVT.getSizeInBits();
7022   SDValue Zero = DAG.getConstant(0, DL, EltVT);
7023   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7024                                     EltVT);
7025   SmallVector<SDValue, 16> MaskOps;
7026   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7027     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
7028       return SDValue(); // Shuffled input!
7029     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7030   }
7031
7032   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
7033   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7034   // We have to cast V2 around.
7035   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7036   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7037                                       DAG.getBitcast(MaskVT, V1Mask),
7038                                       DAG.getBitcast(MaskVT, V2)));
7039   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7040 }
7041
7042 /// \brief Try to emit a blend instruction for a shuffle.
7043 ///
7044 /// This doesn't do any checks for the availability of instructions for blending
7045 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7046 /// be matched in the backend with the type given. What it does check for is
7047 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7048 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7049                                          SDValue V2, ArrayRef<int> Original,
7050                                          const X86Subtarget *Subtarget,
7051                                          SelectionDAG &DAG) {
7052   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7053   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7054   SmallVector<int, 8> Mask(Original.begin(), Original.end());
7055   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7056   bool ForceV1Zero = false, ForceV2Zero = false;
7057
7058   // Attempt to generate the binary blend mask. If an input is zero then
7059   // we can use any lane.
7060   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7061   unsigned BlendMask = 0;
7062   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7063     int M = Mask[i];
7064     if (M < 0)
7065       continue;
7066     if (M == i)
7067       continue;
7068     if (M == i + Size) {
7069       BlendMask |= 1u << i;
7070       continue;
7071     }
7072     if (Zeroable[i]) {
7073       if (V1IsZero) {
7074         ForceV1Zero = true;
7075         Mask[i] = i;
7076         continue;
7077       }
7078       if (V2IsZero) {
7079         ForceV2Zero = true;
7080         BlendMask |= 1u << i;
7081         Mask[i] = i + Size;
7082         continue;
7083       }
7084     }
7085     return SDValue(); // Shuffled input!
7086   }
7087
7088   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7089   if (ForceV1Zero)
7090     V1 = getZeroVector(VT, Subtarget, DAG, DL);
7091   if (ForceV2Zero)
7092     V2 = getZeroVector(VT, Subtarget, DAG, DL);
7093
7094   auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7095     unsigned ScaledMask = 0;
7096     for (int i = 0; i != Size; ++i)
7097       if (BlendMask & (1u << i))
7098         for (int j = 0; j != Scale; ++j)
7099           ScaledMask |= 1u << (i * Scale + j);
7100     return ScaledMask;
7101   };
7102
7103   switch (VT.SimpleTy) {
7104   case MVT::v2f64:
7105   case MVT::v4f32:
7106   case MVT::v4f64:
7107   case MVT::v8f32:
7108     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7109                        DAG.getConstant(BlendMask, DL, MVT::i8));
7110
7111   case MVT::v4i64:
7112   case MVT::v8i32:
7113     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7114     // FALLTHROUGH
7115   case MVT::v2i64:
7116   case MVT::v4i32:
7117     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7118     // that instruction.
7119     if (Subtarget->hasAVX2()) {
7120       // Scale the blend by the number of 32-bit dwords per element.
7121       int Scale =  VT.getScalarSizeInBits() / 32;
7122       BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7123       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7124       V1 = DAG.getBitcast(BlendVT, V1);
7125       V2 = DAG.getBitcast(BlendVT, V2);
7126       return DAG.getBitcast(
7127           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7128                           DAG.getConstant(BlendMask, DL, MVT::i8)));
7129     }
7130     // FALLTHROUGH
7131   case MVT::v8i16: {
7132     // For integer shuffles we need to expand the mask and cast the inputs to
7133     // v8i16s prior to blending.
7134     int Scale = 8 / VT.getVectorNumElements();
7135     BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7136     V1 = DAG.getBitcast(MVT::v8i16, V1);
7137     V2 = DAG.getBitcast(MVT::v8i16, V2);
7138     return DAG.getBitcast(VT,
7139                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7140                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
7141   }
7142
7143   case MVT::v16i16: {
7144     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7145     SmallVector<int, 8> RepeatedMask;
7146     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7147       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7148       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7149       BlendMask = 0;
7150       for (int i = 0; i < 8; ++i)
7151         if (RepeatedMask[i] >= 16)
7152           BlendMask |= 1u << i;
7153       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7154                          DAG.getConstant(BlendMask, DL, MVT::i8));
7155     }
7156   }
7157     // FALLTHROUGH
7158   case MVT::v16i8:
7159   case MVT::v32i8: {
7160     assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7161            "256-bit byte-blends require AVX2 support!");
7162
7163     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7164     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7165       return Masked;
7166
7167     // Scale the blend by the number of bytes per element.
7168     int Scale = VT.getScalarSizeInBits() / 8;
7169
7170     // This form of blend is always done on bytes. Compute the byte vector
7171     // type.
7172     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7173
7174     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7175     // mix of LLVM's code generator and the x86 backend. We tell the code
7176     // generator that boolean values in the elements of an x86 vector register
7177     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7178     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7179     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7180     // of the element (the remaining are ignored) and 0 in that high bit would
7181     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7182     // the LLVM model for boolean values in vector elements gets the relevant
7183     // bit set, it is set backwards and over constrained relative to x86's
7184     // actual model.
7185     SmallVector<SDValue, 32> VSELECTMask;
7186     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7187       for (int j = 0; j < Scale; ++j)
7188         VSELECTMask.push_back(
7189             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7190                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7191                                           MVT::i8));
7192
7193     V1 = DAG.getBitcast(BlendVT, V1);
7194     V2 = DAG.getBitcast(BlendVT, V2);
7195     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7196                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7197                                                       BlendVT, VSELECTMask),
7198                                           V1, V2));
7199   }
7200
7201   default:
7202     llvm_unreachable("Not a supported integer vector type!");
7203   }
7204 }
7205
7206 /// \brief Try to lower as a blend of elements from two inputs followed by
7207 /// a single-input permutation.
7208 ///
7209 /// This matches the pattern where we can blend elements from two inputs and
7210 /// then reduce the shuffle to a single-input permutation.
7211 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7212                                                    SDValue V2,
7213                                                    ArrayRef<int> Mask,
7214                                                    SelectionDAG &DAG) {
7215   // We build up the blend mask while checking whether a blend is a viable way
7216   // to reduce the shuffle.
7217   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7218   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7219
7220   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7221     if (Mask[i] < 0)
7222       continue;
7223
7224     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7225
7226     if (BlendMask[Mask[i] % Size] == -1)
7227       BlendMask[Mask[i] % Size] = Mask[i];
7228     else if (BlendMask[Mask[i] % Size] != Mask[i])
7229       return SDValue(); // Can't blend in the needed input!
7230
7231     PermuteMask[i] = Mask[i] % Size;
7232   }
7233
7234   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7235   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7236 }
7237
7238 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7239 /// blends and permutes.
7240 ///
7241 /// This matches the extremely common pattern for handling combined
7242 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7243 /// operations. It will try to pick the best arrangement of shuffles and
7244 /// blends.
7245 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7246                                                           SDValue V1,
7247                                                           SDValue V2,
7248                                                           ArrayRef<int> Mask,
7249                                                           SelectionDAG &DAG) {
7250   // Shuffle the input elements into the desired positions in V1 and V2 and
7251   // blend them together.
7252   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7253   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7254   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7255   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7256     if (Mask[i] >= 0 && Mask[i] < Size) {
7257       V1Mask[i] = Mask[i];
7258       BlendMask[i] = i;
7259     } else if (Mask[i] >= Size) {
7260       V2Mask[i] = Mask[i] - Size;
7261       BlendMask[i] = i + Size;
7262     }
7263
7264   // Try to lower with the simpler initial blend strategy unless one of the
7265   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7266   // shuffle may be able to fold with a load or other benefit. However, when
7267   // we'll have to do 2x as many shuffles in order to achieve this, blending
7268   // first is a better strategy.
7269   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7270     if (SDValue BlendPerm =
7271             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7272       return BlendPerm;
7273
7274   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7275   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7276   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7277 }
7278
7279 /// \brief Try to lower a vector shuffle as a byte rotation.
7280 ///
7281 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7282 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7283 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7284 /// try to generically lower a vector shuffle through such an pattern. It
7285 /// does not check for the profitability of lowering either as PALIGNR or
7286 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7287 /// This matches shuffle vectors that look like:
7288 ///
7289 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7290 ///
7291 /// Essentially it concatenates V1 and V2, shifts right by some number of
7292 /// elements, and takes the low elements as the result. Note that while this is
7293 /// specified as a *right shift* because x86 is little-endian, it is a *left
7294 /// rotate* of the vector lanes.
7295 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7296                                               SDValue V2,
7297                                               ArrayRef<int> Mask,
7298                                               const X86Subtarget *Subtarget,
7299                                               SelectionDAG &DAG) {
7300   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7301
7302   int NumElts = Mask.size();
7303   int NumLanes = VT.getSizeInBits() / 128;
7304   int NumLaneElts = NumElts / NumLanes;
7305
7306   // We need to detect various ways of spelling a rotation:
7307   //   [11, 12, 13, 14, 15,  0,  1,  2]
7308   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7309   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7310   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7311   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7312   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7313   int Rotation = 0;
7314   SDValue Lo, Hi;
7315   for (int l = 0; l < NumElts; l += NumLaneElts) {
7316     for (int i = 0; i < NumLaneElts; ++i) {
7317       if (Mask[l + i] == -1)
7318         continue;
7319       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7320
7321       // Get the mod-Size index and lane correct it.
7322       int LaneIdx = (Mask[l + i] % NumElts) - l;
7323       // Make sure it was in this lane.
7324       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7325         return SDValue();
7326
7327       // Determine where a rotated vector would have started.
7328       int StartIdx = i - LaneIdx;
7329       if (StartIdx == 0)
7330         // The identity rotation isn't interesting, stop.
7331         return SDValue();
7332
7333       // If we found the tail of a vector the rotation must be the missing
7334       // front. If we found the head of a vector, it must be how much of the
7335       // head.
7336       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7337
7338       if (Rotation == 0)
7339         Rotation = CandidateRotation;
7340       else if (Rotation != CandidateRotation)
7341         // The rotations don't match, so we can't match this mask.
7342         return SDValue();
7343
7344       // Compute which value this mask is pointing at.
7345       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7346
7347       // Compute which of the two target values this index should be assigned
7348       // to. This reflects whether the high elements are remaining or the low
7349       // elements are remaining.
7350       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7351
7352       // Either set up this value if we've not encountered it before, or check
7353       // that it remains consistent.
7354       if (!TargetV)
7355         TargetV = MaskV;
7356       else if (TargetV != MaskV)
7357         // This may be a rotation, but it pulls from the inputs in some
7358         // unsupported interleaving.
7359         return SDValue();
7360     }
7361   }
7362
7363   // Check that we successfully analyzed the mask, and normalize the results.
7364   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7365   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7366   if (!Lo)
7367     Lo = Hi;
7368   else if (!Hi)
7369     Hi = Lo;
7370
7371   // The actual rotate instruction rotates bytes, so we need to scale the
7372   // rotation based on how many bytes are in the vector lane.
7373   int Scale = 16 / NumLaneElts;
7374
7375   // SSSE3 targets can use the palignr instruction.
7376   if (Subtarget->hasSSSE3()) {
7377     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7378     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7379     Lo = DAG.getBitcast(AlignVT, Lo);
7380     Hi = DAG.getBitcast(AlignVT, Hi);
7381
7382     return DAG.getBitcast(
7383         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7384                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7385   }
7386
7387   assert(VT.is128BitVector() &&
7388          "Rotate-based lowering only supports 128-bit lowering!");
7389   assert(Mask.size() <= 16 &&
7390          "Can shuffle at most 16 bytes in a 128-bit vector!");
7391
7392   // Default SSE2 implementation
7393   int LoByteShift = 16 - Rotation * Scale;
7394   int HiByteShift = Rotation * Scale;
7395
7396   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7397   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7398   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7399
7400   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7401                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7402   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7403                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7404   return DAG.getBitcast(VT,
7405                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7406 }
7407
7408 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7409 ///
7410 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7411 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7412 /// matches elements from one of the input vectors shuffled to the left or
7413 /// right with zeroable elements 'shifted in'. It handles both the strictly
7414 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7415 /// quad word lane.
7416 ///
7417 /// PSHL : (little-endian) left bit shift.
7418 /// [ zz, 0, zz,  2 ]
7419 /// [ -1, 4, zz, -1 ]
7420 /// PSRL : (little-endian) right bit shift.
7421 /// [  1, zz,  3, zz]
7422 /// [ -1, -1,  7, zz]
7423 /// PSLLDQ : (little-endian) left byte shift
7424 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7425 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7426 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7427 /// PSRLDQ : (little-endian) right byte shift
7428 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7429 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7430 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7431 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7432                                          SDValue V2, ArrayRef<int> Mask,
7433                                          SelectionDAG &DAG) {
7434   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7435
7436   int Size = Mask.size();
7437   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7438
7439   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7440     for (int i = 0; i < Size; i += Scale)
7441       for (int j = 0; j < Shift; ++j)
7442         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7443           return false;
7444
7445     return true;
7446   };
7447
7448   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7449     for (int i = 0; i != Size; i += Scale) {
7450       unsigned Pos = Left ? i + Shift : i;
7451       unsigned Low = Left ? i : i + Shift;
7452       unsigned Len = Scale - Shift;
7453       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7454                                       Low + (V == V1 ? 0 : Size)))
7455         return SDValue();
7456     }
7457
7458     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7459     bool ByteShift = ShiftEltBits > 64;
7460     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7461                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7462     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7463
7464     // Normalize the scale for byte shifts to still produce an i64 element
7465     // type.
7466     Scale = ByteShift ? Scale / 2 : Scale;
7467
7468     // We need to round trip through the appropriate type for the shift.
7469     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7470     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7471     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7472            "Illegal integer vector type");
7473     V = DAG.getBitcast(ShiftVT, V);
7474
7475     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7476                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7477     return DAG.getBitcast(VT, V);
7478   };
7479
7480   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7481   // keep doubling the size of the integer elements up to that. We can
7482   // then shift the elements of the integer vector by whole multiples of
7483   // their width within the elements of the larger integer vector. Test each
7484   // multiple to see if we can find a match with the moved element indices
7485   // and that the shifted in elements are all zeroable.
7486   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7487     for (int Shift = 1; Shift != Scale; ++Shift)
7488       for (bool Left : {true, false})
7489         if (CheckZeros(Shift, Scale, Left))
7490           for (SDValue V : {V1, V2})
7491             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7492               return Match;
7493
7494   // no match
7495   return SDValue();
7496 }
7497
7498 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7499 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7500                                            SDValue V2, ArrayRef<int> Mask,
7501                                            SelectionDAG &DAG) {
7502   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7503   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7504
7505   int Size = Mask.size();
7506   int HalfSize = Size / 2;
7507   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7508
7509   // Upper half must be undefined.
7510   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7511     return SDValue();
7512
7513   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7514   // Remainder of lower half result is zero and upper half is all undef.
7515   auto LowerAsEXTRQ = [&]() {
7516     // Determine the extraction length from the part of the
7517     // lower half that isn't zeroable.
7518     int Len = HalfSize;
7519     for (; Len > 0; --Len)
7520       if (!Zeroable[Len - 1])
7521         break;
7522     assert(Len > 0 && "Zeroable shuffle mask");
7523
7524     // Attempt to match first Len sequential elements from the lower half.
7525     SDValue Src;
7526     int Idx = -1;
7527     for (int i = 0; i != Len; ++i) {
7528       int M = Mask[i];
7529       if (M < 0)
7530         continue;
7531       SDValue &V = (M < Size ? V1 : V2);
7532       M = M % Size;
7533
7534       // The extracted elements must start at a valid index and all mask
7535       // elements must be in the lower half.
7536       if (i > M || M >= HalfSize)
7537         return SDValue();
7538
7539       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7540         Src = V;
7541         Idx = M - i;
7542         continue;
7543       }
7544       return SDValue();
7545     }
7546
7547     if (Idx < 0)
7548       return SDValue();
7549
7550     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7551     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7552     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7553     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7554                        DAG.getConstant(BitLen, DL, MVT::i8),
7555                        DAG.getConstant(BitIdx, DL, MVT::i8));
7556   };
7557
7558   if (SDValue ExtrQ = LowerAsEXTRQ())
7559     return ExtrQ;
7560
7561   // INSERTQ: Extract lowest Len elements from lower half of second source and
7562   // insert over first source, starting at Idx.
7563   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7564   auto LowerAsInsertQ = [&]() {
7565     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7566       SDValue Base;
7567
7568       // Attempt to match first source from mask before insertion point.
7569       if (isUndefInRange(Mask, 0, Idx)) {
7570         /* EMPTY */
7571       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7572         Base = V1;
7573       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7574         Base = V2;
7575       } else {
7576         continue;
7577       }
7578
7579       // Extend the extraction length looking to match both the insertion of
7580       // the second source and the remaining elements of the first.
7581       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7582         SDValue Insert;
7583         int Len = Hi - Idx;
7584
7585         // Match insertion.
7586         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7587           Insert = V1;
7588         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7589           Insert = V2;
7590         } else {
7591           continue;
7592         }
7593
7594         // Match the remaining elements of the lower half.
7595         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7596           /* EMPTY */
7597         } else if ((!Base || (Base == V1)) &&
7598                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7599           Base = V1;
7600         } else if ((!Base || (Base == V2)) &&
7601                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7602                                               Size + Hi)) {
7603           Base = V2;
7604         } else {
7605           continue;
7606         }
7607
7608         // We may not have a base (first source) - this can safely be undefined.
7609         if (!Base)
7610           Base = DAG.getUNDEF(VT);
7611
7612         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7613         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7614         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7615                            DAG.getConstant(BitLen, DL, MVT::i8),
7616                            DAG.getConstant(BitIdx, DL, MVT::i8));
7617       }
7618     }
7619
7620     return SDValue();
7621   };
7622
7623   if (SDValue InsertQ = LowerAsInsertQ())
7624     return InsertQ;
7625
7626   return SDValue();
7627 }
7628
7629 /// \brief Lower a vector shuffle as a zero or any extension.
7630 ///
7631 /// Given a specific number of elements, element bit width, and extension
7632 /// stride, produce either a zero or any extension based on the available
7633 /// features of the subtarget. The extended elements are consecutive and
7634 /// begin and can start from an offseted element index in the input; to
7635 /// avoid excess shuffling the offset must either being in the bottom lane
7636 /// or at the start of a higher lane. All extended elements must be from
7637 /// the same lane.
7638 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7639     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7640     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7641   assert(Scale > 1 && "Need a scale to extend.");
7642   int EltBits = VT.getScalarSizeInBits();
7643   int NumElements = VT.getVectorNumElements();
7644   int NumEltsPerLane = 128 / EltBits;
7645   int OffsetLane = Offset / NumEltsPerLane;
7646   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7647          "Only 8, 16, and 32 bit elements can be extended.");
7648   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7649   assert(0 <= Offset && "Extension offset must be positive.");
7650   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7651          "Extension offset must be in the first lane or start an upper lane.");
7652
7653   // Check that an index is in same lane as the base offset.
7654   auto SafeOffset = [&](int Idx) {
7655     return OffsetLane == (Idx / NumEltsPerLane);
7656   };
7657
7658   // Shift along an input so that the offset base moves to the first element.
7659   auto ShuffleOffset = [&](SDValue V) {
7660     if (!Offset)
7661       return V;
7662
7663     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7664     for (int i = 0; i * Scale < NumElements; ++i) {
7665       int SrcIdx = i + Offset;
7666       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7667     }
7668     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7669   };
7670
7671   // Found a valid zext mask! Try various lowering strategies based on the
7672   // input type and available ISA extensions.
7673   if (Subtarget->hasSSE41()) {
7674     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7675     // PUNPCK will catch this in a later shuffle match.
7676     if (Offset && Scale == 2 && VT.is128BitVector())
7677       return SDValue();
7678     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7679                                  NumElements / Scale);
7680     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7681     return DAG.getBitcast(VT, InputV);
7682   }
7683
7684   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7685
7686   // For any extends we can cheat for larger element sizes and use shuffle
7687   // instructions that can fold with a load and/or copy.
7688   if (AnyExt && EltBits == 32) {
7689     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7690                          -1};
7691     return DAG.getBitcast(
7692         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7693                         DAG.getBitcast(MVT::v4i32, InputV),
7694                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7695   }
7696   if (AnyExt && EltBits == 16 && Scale > 2) {
7697     int PSHUFDMask[4] = {Offset / 2, -1,
7698                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7699     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7700                          DAG.getBitcast(MVT::v4i32, InputV),
7701                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7702     int PSHUFWMask[4] = {1, -1, -1, -1};
7703     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7704     return DAG.getBitcast(
7705         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7706                         DAG.getBitcast(MVT::v8i16, InputV),
7707                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7708   }
7709
7710   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7711   // to 64-bits.
7712   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7713     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7714     assert(VT.is128BitVector() && "Unexpected vector width!");
7715
7716     int LoIdx = Offset * EltBits;
7717     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7718                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7719                                          DAG.getConstant(EltBits, DL, MVT::i8),
7720                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7721
7722     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7723         !SafeOffset(Offset + 1))
7724       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7725
7726     int HiIdx = (Offset + 1) * EltBits;
7727     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7728                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7729                                          DAG.getConstant(EltBits, DL, MVT::i8),
7730                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7731     return DAG.getNode(ISD::BITCAST, DL, VT,
7732                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7733   }
7734
7735   // If this would require more than 2 unpack instructions to expand, use
7736   // pshufb when available. We can only use more than 2 unpack instructions
7737   // when zero extending i8 elements which also makes it easier to use pshufb.
7738   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7739     assert(NumElements == 16 && "Unexpected byte vector width!");
7740     SDValue PSHUFBMask[16];
7741     for (int i = 0; i < 16; ++i) {
7742       int Idx = Offset + (i / Scale);
7743       PSHUFBMask[i] = DAG.getConstant(
7744           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7745     }
7746     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7747     return DAG.getBitcast(VT,
7748                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7749                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7750                                                   MVT::v16i8, PSHUFBMask)));
7751   }
7752
7753   // If we are extending from an offset, ensure we start on a boundary that
7754   // we can unpack from.
7755   int AlignToUnpack = Offset % (NumElements / Scale);
7756   if (AlignToUnpack) {
7757     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7758     for (int i = AlignToUnpack; i < NumElements; ++i)
7759       ShMask[i - AlignToUnpack] = i;
7760     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7761     Offset -= AlignToUnpack;
7762   }
7763
7764   // Otherwise emit a sequence of unpacks.
7765   do {
7766     unsigned UnpackLoHi = X86ISD::UNPCKL;
7767     if (Offset >= (NumElements / 2)) {
7768       UnpackLoHi = X86ISD::UNPCKH;
7769       Offset -= (NumElements / 2);
7770     }
7771
7772     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7773     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7774                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7775     InputV = DAG.getBitcast(InputVT, InputV);
7776     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7777     Scale /= 2;
7778     EltBits *= 2;
7779     NumElements /= 2;
7780   } while (Scale > 1);
7781   return DAG.getBitcast(VT, InputV);
7782 }
7783
7784 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7785 ///
7786 /// This routine will try to do everything in its power to cleverly lower
7787 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7788 /// check for the profitability of this lowering,  it tries to aggressively
7789 /// match this pattern. It will use all of the micro-architectural details it
7790 /// can to emit an efficient lowering. It handles both blends with all-zero
7791 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7792 /// masking out later).
7793 ///
7794 /// The reason we have dedicated lowering for zext-style shuffles is that they
7795 /// are both incredibly common and often quite performance sensitive.
7796 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7797     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7798     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7799   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7800
7801   int Bits = VT.getSizeInBits();
7802   int NumLanes = Bits / 128;
7803   int NumElements = VT.getVectorNumElements();
7804   int NumEltsPerLane = NumElements / NumLanes;
7805   assert(VT.getScalarSizeInBits() <= 32 &&
7806          "Exceeds 32-bit integer zero extension limit");
7807   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7808
7809   // Define a helper function to check a particular ext-scale and lower to it if
7810   // valid.
7811   auto Lower = [&](int Scale) -> SDValue {
7812     SDValue InputV;
7813     bool AnyExt = true;
7814     int Offset = 0;
7815     int Matches = 0;
7816     for (int i = 0; i < NumElements; ++i) {
7817       int M = Mask[i];
7818       if (M == -1)
7819         continue; // Valid anywhere but doesn't tell us anything.
7820       if (i % Scale != 0) {
7821         // Each of the extended elements need to be zeroable.
7822         if (!Zeroable[i])
7823           return SDValue();
7824
7825         // We no longer are in the anyext case.
7826         AnyExt = false;
7827         continue;
7828       }
7829
7830       // Each of the base elements needs to be consecutive indices into the
7831       // same input vector.
7832       SDValue V = M < NumElements ? V1 : V2;
7833       M = M % NumElements;
7834       if (!InputV) {
7835         InputV = V;
7836         Offset = M - (i / Scale);
7837       } else if (InputV != V)
7838         return SDValue(); // Flip-flopping inputs.
7839
7840       // Offset must start in the lowest 128-bit lane or at the start of an
7841       // upper lane.
7842       // FIXME: Is it ever worth allowing a negative base offset?
7843       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7844             (Offset % NumEltsPerLane) == 0))
7845         return SDValue();
7846
7847       // If we are offsetting, all referenced entries must come from the same
7848       // lane.
7849       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7850         return SDValue();
7851
7852       if ((M % NumElements) != (Offset + (i / Scale)))
7853         return SDValue(); // Non-consecutive strided elements.
7854       Matches++;
7855     }
7856
7857     // If we fail to find an input, we have a zero-shuffle which should always
7858     // have already been handled.
7859     // FIXME: Maybe handle this here in case during blending we end up with one?
7860     if (!InputV)
7861       return SDValue();
7862
7863     // If we are offsetting, don't extend if we only match a single input, we
7864     // can always do better by using a basic PSHUF or PUNPCK.
7865     if (Offset != 0 && Matches < 2)
7866       return SDValue();
7867
7868     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7869         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7870   };
7871
7872   // The widest scale possible for extending is to a 64-bit integer.
7873   assert(Bits % 64 == 0 &&
7874          "The number of bits in a vector must be divisible by 64 on x86!");
7875   int NumExtElements = Bits / 64;
7876
7877   // Each iteration, try extending the elements half as much, but into twice as
7878   // many elements.
7879   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7880     assert(NumElements % NumExtElements == 0 &&
7881            "The input vector size must be divisible by the extended size.");
7882     if (SDValue V = Lower(NumElements / NumExtElements))
7883       return V;
7884   }
7885
7886   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7887   if (Bits != 128)
7888     return SDValue();
7889
7890   // Returns one of the source operands if the shuffle can be reduced to a
7891   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7892   auto CanZExtLowHalf = [&]() {
7893     for (int i = NumElements / 2; i != NumElements; ++i)
7894       if (!Zeroable[i])
7895         return SDValue();
7896     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7897       return V1;
7898     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7899       return V2;
7900     return SDValue();
7901   };
7902
7903   if (SDValue V = CanZExtLowHalf()) {
7904     V = DAG.getBitcast(MVT::v2i64, V);
7905     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7906     return DAG.getBitcast(VT, V);
7907   }
7908
7909   // No viable ext lowering found.
7910   return SDValue();
7911 }
7912
7913 /// \brief Try to get a scalar value for a specific element of a vector.
7914 ///
7915 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7916 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7917                                               SelectionDAG &DAG) {
7918   MVT VT = V.getSimpleValueType();
7919   MVT EltVT = VT.getVectorElementType();
7920   while (V.getOpcode() == ISD::BITCAST)
7921     V = V.getOperand(0);
7922   // If the bitcasts shift the element size, we can't extract an equivalent
7923   // element from it.
7924   MVT NewVT = V.getSimpleValueType();
7925   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7926     return SDValue();
7927
7928   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7929       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7930     // Ensure the scalar operand is the same size as the destination.
7931     // FIXME: Add support for scalar truncation where possible.
7932     SDValue S = V.getOperand(Idx);
7933     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7934       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7935   }
7936
7937   return SDValue();
7938 }
7939
7940 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7941 ///
7942 /// This is particularly important because the set of instructions varies
7943 /// significantly based on whether the operand is a load or not.
7944 static bool isShuffleFoldableLoad(SDValue V) {
7945   while (V.getOpcode() == ISD::BITCAST)
7946     V = V.getOperand(0);
7947
7948   return ISD::isNON_EXTLoad(V.getNode());
7949 }
7950
7951 /// \brief Try to lower insertion of a single element into a zero vector.
7952 ///
7953 /// This is a common pattern that we have especially efficient patterns to lower
7954 /// across all subtarget feature sets.
7955 static SDValue lowerVectorShuffleAsElementInsertion(
7956     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7957     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7958   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7959   MVT ExtVT = VT;
7960   MVT EltVT = VT.getVectorElementType();
7961
7962   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7963                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7964                 Mask.begin();
7965   bool IsV1Zeroable = true;
7966   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7967     if (i != V2Index && !Zeroable[i]) {
7968       IsV1Zeroable = false;
7969       break;
7970     }
7971
7972   // Check for a single input from a SCALAR_TO_VECTOR node.
7973   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7974   // all the smarts here sunk into that routine. However, the current
7975   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7976   // vector shuffle lowering is dead.
7977   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7978                                                DAG);
7979   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7980     // We need to zext the scalar if it is smaller than an i32.
7981     V2S = DAG.getBitcast(EltVT, V2S);
7982     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7983       // Using zext to expand a narrow element won't work for non-zero
7984       // insertions.
7985       if (!IsV1Zeroable)
7986         return SDValue();
7987
7988       // Zero-extend directly to i32.
7989       ExtVT = MVT::v4i32;
7990       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7991     }
7992     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7993   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7994              EltVT == MVT::i16) {
7995     // Either not inserting from the low element of the input or the input
7996     // element size is too small to use VZEXT_MOVL to clear the high bits.
7997     return SDValue();
7998   }
7999
8000   if (!IsV1Zeroable) {
8001     // If V1 can't be treated as a zero vector we have fewer options to lower
8002     // this. We can't support integer vectors or non-zero targets cheaply, and
8003     // the V1 elements can't be permuted in any way.
8004     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8005     if (!VT.isFloatingPoint() || V2Index != 0)
8006       return SDValue();
8007     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8008     V1Mask[V2Index] = -1;
8009     if (!isNoopShuffleMask(V1Mask))
8010       return SDValue();
8011     // This is essentially a special case blend operation, but if we have
8012     // general purpose blend operations, they are always faster. Bail and let
8013     // the rest of the lowering handle these as blends.
8014     if (Subtarget->hasSSE41())
8015       return SDValue();
8016
8017     // Otherwise, use MOVSD or MOVSS.
8018     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8019            "Only two types of floating point element types to handle!");
8020     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8021                        ExtVT, V1, V2);
8022   }
8023
8024   // This lowering only works for the low element with floating point vectors.
8025   if (VT.isFloatingPoint() && V2Index != 0)
8026     return SDValue();
8027
8028   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8029   if (ExtVT != VT)
8030     V2 = DAG.getBitcast(VT, V2);
8031
8032   if (V2Index != 0) {
8033     // If we have 4 or fewer lanes we can cheaply shuffle the element into
8034     // the desired position. Otherwise it is more efficient to do a vector
8035     // shift left. We know that we can do a vector shift left because all
8036     // the inputs are zero.
8037     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8038       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8039       V2Shuffle[V2Index] = 0;
8040       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8041     } else {
8042       V2 = DAG.getBitcast(MVT::v2i64, V2);
8043       V2 = DAG.getNode(
8044           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8045           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8046                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8047                               DAG.getDataLayout(), VT)));
8048       V2 = DAG.getBitcast(VT, V2);
8049     }
8050   }
8051   return V2;
8052 }
8053
8054 /// \brief Try to lower broadcast of a single - truncated - integer element,
8055 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8056 ///
8057 /// This assumes we have AVX2.
8058 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
8059                                                   int BroadcastIdx,
8060                                                   const X86Subtarget *Subtarget,
8061                                                   SelectionDAG &DAG) {
8062   assert(Subtarget->hasAVX2() &&
8063          "We can only lower integer broadcasts with AVX2!");
8064
8065   EVT EltVT = VT.getVectorElementType();
8066   EVT V0VT = V0.getValueType();
8067
8068   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8069   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8070
8071   EVT V0EltVT = V0VT.getVectorElementType();
8072   if (!V0EltVT.isInteger())
8073     return SDValue();
8074
8075   const unsigned EltSize = EltVT.getSizeInBits();
8076   const unsigned V0EltSize = V0EltVT.getSizeInBits();
8077
8078   // This is only a truncation if the original element type is larger.
8079   if (V0EltSize <= EltSize)
8080     return SDValue();
8081
8082   assert(((V0EltSize % EltSize) == 0) &&
8083          "Scalar type sizes must all be powers of 2 on x86!");
8084
8085   const unsigned V0Opc = V0.getOpcode();
8086   const unsigned Scale = V0EltSize / EltSize;
8087   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8088
8089   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8090       V0Opc != ISD::BUILD_VECTOR)
8091     return SDValue();
8092
8093   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8094
8095   // If we're extracting non-least-significant bits, shift so we can truncate.
8096   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8097   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8098   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8099   if (const int OffsetIdx = BroadcastIdx % Scale)
8100     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8101             DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8102
8103   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8104                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8105 }
8106
8107 /// \brief Try to lower broadcast of a single element.
8108 ///
8109 /// For convenience, this code also bundles all of the subtarget feature set
8110 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8111 /// a convenient way to factor it out.
8112 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8113 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8114                                              ArrayRef<int> Mask,
8115                                              const X86Subtarget *Subtarget,
8116                                              SelectionDAG &DAG) {
8117   if (!Subtarget->hasAVX())
8118     return SDValue();
8119   if (VT.isInteger() && !Subtarget->hasAVX2())
8120     return SDValue();
8121
8122   // Check that the mask is a broadcast.
8123   int BroadcastIdx = -1;
8124   for (int M : Mask)
8125     if (M >= 0 && BroadcastIdx == -1)
8126       BroadcastIdx = M;
8127     else if (M >= 0 && M != BroadcastIdx)
8128       return SDValue();
8129
8130   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8131                                             "a sorted mask where the broadcast "
8132                                             "comes from V1.");
8133
8134   // Go up the chain of (vector) values to find a scalar load that we can
8135   // combine with the broadcast.
8136   for (;;) {
8137     switch (V.getOpcode()) {
8138     case ISD::CONCAT_VECTORS: {
8139       int OperandSize = Mask.size() / V.getNumOperands();
8140       V = V.getOperand(BroadcastIdx / OperandSize);
8141       BroadcastIdx %= OperandSize;
8142       continue;
8143     }
8144
8145     case ISD::INSERT_SUBVECTOR: {
8146       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8147       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8148       if (!ConstantIdx)
8149         break;
8150
8151       int BeginIdx = (int)ConstantIdx->getZExtValue();
8152       int EndIdx =
8153           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8154       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8155         BroadcastIdx -= BeginIdx;
8156         V = VInner;
8157       } else {
8158         V = VOuter;
8159       }
8160       continue;
8161     }
8162     }
8163     break;
8164   }
8165
8166   // Check if this is a broadcast of a scalar. We special case lowering
8167   // for scalars so that we can more effectively fold with loads.
8168   // First, look through bitcast: if the original value has a larger element
8169   // type than the shuffle, the broadcast element is in essence truncated.
8170   // Make that explicit to ease folding.
8171   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8172     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8173             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8174       return TruncBroadcast;
8175
8176   // Also check the simpler case, where we can directly reuse the scalar.
8177   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8178       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8179     V = V.getOperand(BroadcastIdx);
8180
8181     // If the scalar isn't a load, we can't broadcast from it in AVX1.
8182     // Only AVX2 has register broadcasts.
8183     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8184       return SDValue();
8185   } else if (MayFoldLoad(V) && !cast<LoadSDNode>(V)->isVolatile()) {
8186     // If we are broadcasting a load that is only used by the shuffle
8187     // then we can reduce the vector load to the broadcasted scalar load.
8188     LoadSDNode *Ld = cast<LoadSDNode>(V);
8189     SDValue BaseAddr = Ld->getOperand(1);
8190     EVT AddrVT = BaseAddr.getValueType();
8191     EVT SVT = VT.getScalarType();
8192     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8193     SDValue NewAddr = DAG.getNode(
8194         ISD::ADD, DL, AddrVT, BaseAddr,
8195         DAG.getConstant(Offset, DL, AddrVT));
8196     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8197                     DAG.getMachineFunction().getMachineMemOperand(
8198                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8199   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8200     // We can't broadcast from a vector register without AVX2, and we can only
8201     // broadcast from the zero-element of a vector register.
8202     return SDValue();
8203   }
8204
8205   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8206 }
8207
8208 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8209 // INSERTPS when the V1 elements are already in the correct locations
8210 // because otherwise we can just always use two SHUFPS instructions which
8211 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8212 // perform INSERTPS if a single V1 element is out of place and all V2
8213 // elements are zeroable.
8214 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8215                                             ArrayRef<int> Mask,
8216                                             SelectionDAG &DAG) {
8217   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8218   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8219   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8220   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8221
8222   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8223
8224   unsigned ZMask = 0;
8225   int V1DstIndex = -1;
8226   int V2DstIndex = -1;
8227   bool V1UsedInPlace = false;
8228
8229   for (int i = 0; i < 4; ++i) {
8230     // Synthesize a zero mask from the zeroable elements (includes undefs).
8231     if (Zeroable[i]) {
8232       ZMask |= 1 << i;
8233       continue;
8234     }
8235
8236     // Flag if we use any V1 inputs in place.
8237     if (i == Mask[i]) {
8238       V1UsedInPlace = true;
8239       continue;
8240     }
8241
8242     // We can only insert a single non-zeroable element.
8243     if (V1DstIndex != -1 || V2DstIndex != -1)
8244       return SDValue();
8245
8246     if (Mask[i] < 4) {
8247       // V1 input out of place for insertion.
8248       V1DstIndex = i;
8249     } else {
8250       // V2 input for insertion.
8251       V2DstIndex = i;
8252     }
8253   }
8254
8255   // Don't bother if we have no (non-zeroable) element for insertion.
8256   if (V1DstIndex == -1 && V2DstIndex == -1)
8257     return SDValue();
8258
8259   // Determine element insertion src/dst indices. The src index is from the
8260   // start of the inserted vector, not the start of the concatenated vector.
8261   unsigned V2SrcIndex = 0;
8262   if (V1DstIndex != -1) {
8263     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8264     // and don't use the original V2 at all.
8265     V2SrcIndex = Mask[V1DstIndex];
8266     V2DstIndex = V1DstIndex;
8267     V2 = V1;
8268   } else {
8269     V2SrcIndex = Mask[V2DstIndex] - 4;
8270   }
8271
8272   // If no V1 inputs are used in place, then the result is created only from
8273   // the zero mask and the V2 insertion - so remove V1 dependency.
8274   if (!V1UsedInPlace)
8275     V1 = DAG.getUNDEF(MVT::v4f32);
8276
8277   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8278   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8279
8280   // Insert the V2 element into the desired position.
8281   SDLoc DL(Op);
8282   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8283                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8284 }
8285
8286 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8287 /// UNPCK instruction.
8288 ///
8289 /// This specifically targets cases where we end up with alternating between
8290 /// the two inputs, and so can permute them into something that feeds a single
8291 /// UNPCK instruction. Note that this routine only targets integer vectors
8292 /// because for floating point vectors we have a generalized SHUFPS lowering
8293 /// strategy that handles everything that doesn't *exactly* match an unpack,
8294 /// making this clever lowering unnecessary.
8295 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8296                                                     SDValue V1, SDValue V2,
8297                                                     ArrayRef<int> Mask,
8298                                                     SelectionDAG &DAG) {
8299   assert(!VT.isFloatingPoint() &&
8300          "This routine only supports integer vectors.");
8301   assert(!isSingleInputShuffleMask(Mask) &&
8302          "This routine should only be used when blending two inputs.");
8303   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8304
8305   int Size = Mask.size();
8306
8307   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8308     return M >= 0 && M % Size < Size / 2;
8309   });
8310   int NumHiInputs = std::count_if(
8311       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8312
8313   bool UnpackLo = NumLoInputs >= NumHiInputs;
8314
8315   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8316     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8317     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8318
8319     for (int i = 0; i < Size; ++i) {
8320       if (Mask[i] < 0)
8321         continue;
8322
8323       // Each element of the unpack contains Scale elements from this mask.
8324       int UnpackIdx = i / Scale;
8325
8326       // We only handle the case where V1 feeds the first slots of the unpack.
8327       // We rely on canonicalization to ensure this is the case.
8328       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8329         return SDValue();
8330
8331       // Setup the mask for this input. The indexing is tricky as we have to
8332       // handle the unpack stride.
8333       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8334       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8335           Mask[i] % Size;
8336     }
8337
8338     // If we will have to shuffle both inputs to use the unpack, check whether
8339     // we can just unpack first and shuffle the result. If so, skip this unpack.
8340     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8341         !isNoopShuffleMask(V2Mask))
8342       return SDValue();
8343
8344     // Shuffle the inputs into place.
8345     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8346     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8347
8348     // Cast the inputs to the type we will use to unpack them.
8349     V1 = DAG.getBitcast(UnpackVT, V1);
8350     V2 = DAG.getBitcast(UnpackVT, V2);
8351
8352     // Unpack the inputs and cast the result back to the desired type.
8353     return DAG.getBitcast(
8354         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8355                         UnpackVT, V1, V2));
8356   };
8357
8358   // We try each unpack from the largest to the smallest to try and find one
8359   // that fits this mask.
8360   int OrigNumElements = VT.getVectorNumElements();
8361   int OrigScalarSize = VT.getScalarSizeInBits();
8362   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8363     int Scale = ScalarSize / OrigScalarSize;
8364     int NumElements = OrigNumElements / Scale;
8365     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8366     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8367       return Unpack;
8368   }
8369
8370   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8371   // initial unpack.
8372   if (NumLoInputs == 0 || NumHiInputs == 0) {
8373     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8374            "We have to have *some* inputs!");
8375     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8376
8377     // FIXME: We could consider the total complexity of the permute of each
8378     // possible unpacking. Or at the least we should consider how many
8379     // half-crossings are created.
8380     // FIXME: We could consider commuting the unpacks.
8381
8382     SmallVector<int, 32> PermMask;
8383     PermMask.assign(Size, -1);
8384     for (int i = 0; i < Size; ++i) {
8385       if (Mask[i] < 0)
8386         continue;
8387
8388       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8389
8390       PermMask[i] =
8391           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8392     }
8393     return DAG.getVectorShuffle(
8394         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8395                             DL, VT, V1, V2),
8396         DAG.getUNDEF(VT), PermMask);
8397   }
8398
8399   return SDValue();
8400 }
8401
8402 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8403 ///
8404 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8405 /// support for floating point shuffles but not integer shuffles. These
8406 /// instructions will incur a domain crossing penalty on some chips though so
8407 /// it is better to avoid lowering through this for integer vectors where
8408 /// possible.
8409 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8410                                        const X86Subtarget *Subtarget,
8411                                        SelectionDAG &DAG) {
8412   SDLoc DL(Op);
8413   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8414   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8415   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8416   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8417   ArrayRef<int> Mask = SVOp->getMask();
8418   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8419
8420   if (isSingleInputShuffleMask(Mask)) {
8421     // Use low duplicate instructions for masks that match their pattern.
8422     if (Subtarget->hasSSE3())
8423       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8424         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8425
8426     // Straight shuffle of a single input vector. Simulate this by using the
8427     // single input as both of the "inputs" to this instruction..
8428     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8429
8430     if (Subtarget->hasAVX()) {
8431       // If we have AVX, we can use VPERMILPS which will allow folding a load
8432       // into the shuffle.
8433       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8434                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8435     }
8436
8437     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8438                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8439   }
8440   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8441   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8442
8443   // If we have a single input, insert that into V1 if we can do so cheaply.
8444   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8445     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8446             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8447       return Insertion;
8448     // Try inverting the insertion since for v2 masks it is easy to do and we
8449     // can't reliably sort the mask one way or the other.
8450     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8451                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8452     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8453             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8454       return Insertion;
8455   }
8456
8457   // Try to use one of the special instruction patterns to handle two common
8458   // blend patterns if a zero-blend above didn't work.
8459   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8460       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8461     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8462       // We can either use a special instruction to load over the low double or
8463       // to move just the low double.
8464       return DAG.getNode(
8465           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8466           DL, MVT::v2f64, V2,
8467           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8468
8469   if (Subtarget->hasSSE41())
8470     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8471                                                   Subtarget, DAG))
8472       return Blend;
8473
8474   // Use dedicated unpack instructions for masks that match their pattern.
8475   if (SDValue V =
8476           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8477     return V;
8478
8479   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8480   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8481                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8482 }
8483
8484 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8485 ///
8486 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8487 /// the integer unit to minimize domain crossing penalties. However, for blends
8488 /// it falls back to the floating point shuffle operation with appropriate bit
8489 /// casting.
8490 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8491                                        const X86Subtarget *Subtarget,
8492                                        SelectionDAG &DAG) {
8493   SDLoc DL(Op);
8494   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8495   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8496   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8497   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8498   ArrayRef<int> Mask = SVOp->getMask();
8499   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8500
8501   if (isSingleInputShuffleMask(Mask)) {
8502     // Check for being able to broadcast a single element.
8503     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8504                                                           Mask, Subtarget, DAG))
8505       return Broadcast;
8506
8507     // Straight shuffle of a single input vector. For everything from SSE2
8508     // onward this has a single fast instruction with no scary immediates.
8509     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8510     V1 = DAG.getBitcast(MVT::v4i32, V1);
8511     int WidenedMask[4] = {
8512         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8513         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8514     return DAG.getBitcast(
8515         MVT::v2i64,
8516         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8517                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8518   }
8519   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8520   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8521   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8522   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8523
8524   // If we have a blend of two PACKUS operations an the blend aligns with the
8525   // low and half halves, we can just merge the PACKUS operations. This is
8526   // particularly important as it lets us merge shuffles that this routine itself
8527   // creates.
8528   auto GetPackNode = [](SDValue V) {
8529     while (V.getOpcode() == ISD::BITCAST)
8530       V = V.getOperand(0);
8531
8532     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8533   };
8534   if (SDValue V1Pack = GetPackNode(V1))
8535     if (SDValue V2Pack = GetPackNode(V2))
8536       return DAG.getBitcast(MVT::v2i64,
8537                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8538                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8539                                                      : V1Pack.getOperand(1),
8540                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8541                                                      : V2Pack.getOperand(1)));
8542
8543   // Try to use shift instructions.
8544   if (SDValue Shift =
8545           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8546     return Shift;
8547
8548   // When loading a scalar and then shuffling it into a vector we can often do
8549   // the insertion cheaply.
8550   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8551           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8552     return Insertion;
8553   // Try inverting the insertion since for v2 masks it is easy to do and we
8554   // can't reliably sort the mask one way or the other.
8555   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8556   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8557           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8558     return Insertion;
8559
8560   // We have different paths for blend lowering, but they all must use the
8561   // *exact* same predicate.
8562   bool IsBlendSupported = Subtarget->hasSSE41();
8563   if (IsBlendSupported)
8564     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8565                                                   Subtarget, DAG))
8566       return Blend;
8567
8568   // Use dedicated unpack instructions for masks that match their pattern.
8569   if (SDValue V =
8570           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8571     return V;
8572
8573   // Try to use byte rotation instructions.
8574   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8575   if (Subtarget->hasSSSE3())
8576     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8577             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8578       return Rotate;
8579
8580   // If we have direct support for blends, we should lower by decomposing into
8581   // a permute. That will be faster than the domain cross.
8582   if (IsBlendSupported)
8583     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8584                                                       Mask, DAG);
8585
8586   // We implement this with SHUFPD which is pretty lame because it will likely
8587   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8588   // However, all the alternatives are still more cycles and newer chips don't
8589   // have this problem. It would be really nice if x86 had better shuffles here.
8590   V1 = DAG.getBitcast(MVT::v2f64, V1);
8591   V2 = DAG.getBitcast(MVT::v2f64, V2);
8592   return DAG.getBitcast(MVT::v2i64,
8593                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8594 }
8595
8596 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8597 ///
8598 /// This is used to disable more specialized lowerings when the shufps lowering
8599 /// will happen to be efficient.
8600 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8601   // This routine only handles 128-bit shufps.
8602   assert(Mask.size() == 4 && "Unsupported mask size!");
8603
8604   // To lower with a single SHUFPS we need to have the low half and high half
8605   // each requiring a single input.
8606   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8607     return false;
8608   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8609     return false;
8610
8611   return true;
8612 }
8613
8614 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8615 ///
8616 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8617 /// It makes no assumptions about whether this is the *best* lowering, it simply
8618 /// uses it.
8619 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8620                                             ArrayRef<int> Mask, SDValue V1,
8621                                             SDValue V2, SelectionDAG &DAG) {
8622   SDValue LowV = V1, HighV = V2;
8623   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8624
8625   int NumV2Elements =
8626       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8627
8628   if (NumV2Elements == 1) {
8629     int V2Index =
8630         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8631         Mask.begin();
8632
8633     // Compute the index adjacent to V2Index and in the same half by toggling
8634     // the low bit.
8635     int V2AdjIndex = V2Index ^ 1;
8636
8637     if (Mask[V2AdjIndex] == -1) {
8638       // Handles all the cases where we have a single V2 element and an undef.
8639       // This will only ever happen in the high lanes because we commute the
8640       // vector otherwise.
8641       if (V2Index < 2)
8642         std::swap(LowV, HighV);
8643       NewMask[V2Index] -= 4;
8644     } else {
8645       // Handle the case where the V2 element ends up adjacent to a V1 element.
8646       // To make this work, blend them together as the first step.
8647       int V1Index = V2AdjIndex;
8648       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8649       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8650                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8651
8652       // Now proceed to reconstruct the final blend as we have the necessary
8653       // high or low half formed.
8654       if (V2Index < 2) {
8655         LowV = V2;
8656         HighV = V1;
8657       } else {
8658         HighV = V2;
8659       }
8660       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8661       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8662     }
8663   } else if (NumV2Elements == 2) {
8664     if (Mask[0] < 4 && Mask[1] < 4) {
8665       // Handle the easy case where we have V1 in the low lanes and V2 in the
8666       // high lanes.
8667       NewMask[2] -= 4;
8668       NewMask[3] -= 4;
8669     } else if (Mask[2] < 4 && Mask[3] < 4) {
8670       // We also handle the reversed case because this utility may get called
8671       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8672       // arrange things in the right direction.
8673       NewMask[0] -= 4;
8674       NewMask[1] -= 4;
8675       HighV = V1;
8676       LowV = V2;
8677     } else {
8678       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8679       // trying to place elements directly, just blend them and set up the final
8680       // shuffle to place them.
8681
8682       // The first two blend mask elements are for V1, the second two are for
8683       // V2.
8684       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8685                           Mask[2] < 4 ? Mask[2] : Mask[3],
8686                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8687                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8688       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8689                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8690
8691       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8692       // a blend.
8693       LowV = HighV = V1;
8694       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8695       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8696       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8697       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8698     }
8699   }
8700   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8701                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8702 }
8703
8704 /// \brief Lower 4-lane 32-bit floating point shuffles.
8705 ///
8706 /// Uses instructions exclusively from the floating point unit to minimize
8707 /// domain crossing penalties, as these are sufficient to implement all v4f32
8708 /// shuffles.
8709 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8710                                        const X86Subtarget *Subtarget,
8711                                        SelectionDAG &DAG) {
8712   SDLoc DL(Op);
8713   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8714   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8715   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8716   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8717   ArrayRef<int> Mask = SVOp->getMask();
8718   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8719
8720   int NumV2Elements =
8721       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8722
8723   if (NumV2Elements == 0) {
8724     // Check for being able to broadcast a single element.
8725     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8726                                                           Mask, Subtarget, DAG))
8727       return Broadcast;
8728
8729     // Use even/odd duplicate instructions for masks that match their pattern.
8730     if (Subtarget->hasSSE3()) {
8731       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8732         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8733       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8734         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8735     }
8736
8737     if (Subtarget->hasAVX()) {
8738       // If we have AVX, we can use VPERMILPS which will allow folding a load
8739       // into the shuffle.
8740       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8741                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8742     }
8743
8744     // Otherwise, use a straight shuffle of a single input vector. We pass the
8745     // input vector to both operands to simulate this with a SHUFPS.
8746     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8747                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8748   }
8749
8750   // There are special ways we can lower some single-element blends. However, we
8751   // have custom ways we can lower more complex single-element blends below that
8752   // we defer to if both this and BLENDPS fail to match, so restrict this to
8753   // when the V2 input is targeting element 0 of the mask -- that is the fast
8754   // case here.
8755   if (NumV2Elements == 1 && Mask[0] >= 4)
8756     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8757                                                          Mask, Subtarget, DAG))
8758       return V;
8759
8760   if (Subtarget->hasSSE41()) {
8761     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8762                                                   Subtarget, DAG))
8763       return Blend;
8764
8765     // Use INSERTPS if we can complete the shuffle efficiently.
8766     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8767       return V;
8768
8769     if (!isSingleSHUFPSMask(Mask))
8770       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8771               DL, MVT::v4f32, V1, V2, Mask, DAG))
8772         return BlendPerm;
8773   }
8774
8775   // Use dedicated unpack instructions for masks that match their pattern.
8776   if (SDValue V =
8777           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8778     return V;
8779
8780   // Otherwise fall back to a SHUFPS lowering strategy.
8781   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8782 }
8783
8784 /// \brief Lower 4-lane i32 vector shuffles.
8785 ///
8786 /// We try to handle these with integer-domain shuffles where we can, but for
8787 /// blends we use the floating point domain blend instructions.
8788 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8789                                        const X86Subtarget *Subtarget,
8790                                        SelectionDAG &DAG) {
8791   SDLoc DL(Op);
8792   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8793   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8794   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8795   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8796   ArrayRef<int> Mask = SVOp->getMask();
8797   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8798
8799   // Whenever we can lower this as a zext, that instruction is strictly faster
8800   // than any alternative. It also allows us to fold memory operands into the
8801   // shuffle in many cases.
8802   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8803                                                          Mask, Subtarget, DAG))
8804     return ZExt;
8805
8806   int NumV2Elements =
8807       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8808
8809   if (NumV2Elements == 0) {
8810     // Check for being able to broadcast a single element.
8811     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8812                                                           Mask, Subtarget, DAG))
8813       return Broadcast;
8814
8815     // Straight shuffle of a single input vector. For everything from SSE2
8816     // onward this has a single fast instruction with no scary immediates.
8817     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8818     // but we aren't actually going to use the UNPCK instruction because doing
8819     // so prevents folding a load into this instruction or making a copy.
8820     const int UnpackLoMask[] = {0, 0, 1, 1};
8821     const int UnpackHiMask[] = {2, 2, 3, 3};
8822     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8823       Mask = UnpackLoMask;
8824     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8825       Mask = UnpackHiMask;
8826
8827     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8828                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8829   }
8830
8831   // Try to use shift instructions.
8832   if (SDValue Shift =
8833           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8834     return Shift;
8835
8836   // There are special ways we can lower some single-element blends.
8837   if (NumV2Elements == 1)
8838     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8839                                                          Mask, Subtarget, DAG))
8840       return V;
8841
8842   // We have different paths for blend lowering, but they all must use the
8843   // *exact* same predicate.
8844   bool IsBlendSupported = Subtarget->hasSSE41();
8845   if (IsBlendSupported)
8846     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8847                                                   Subtarget, DAG))
8848       return Blend;
8849
8850   if (SDValue Masked =
8851           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8852     return Masked;
8853
8854   // Use dedicated unpack instructions for masks that match their pattern.
8855   if (SDValue V =
8856           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8857     return V;
8858
8859   // Try to use byte rotation instructions.
8860   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8861   if (Subtarget->hasSSSE3())
8862     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8863             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8864       return Rotate;
8865
8866   // If we have direct support for blends, we should lower by decomposing into
8867   // a permute. That will be faster than the domain cross.
8868   if (IsBlendSupported)
8869     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8870                                                       Mask, DAG);
8871
8872   // Try to lower by permuting the inputs into an unpack instruction.
8873   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8874                                                             V2, Mask, DAG))
8875     return Unpack;
8876
8877   // We implement this with SHUFPS because it can blend from two vectors.
8878   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8879   // up the inputs, bypassing domain shift penalties that we would encur if we
8880   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8881   // relevant.
8882   return DAG.getBitcast(
8883       MVT::v4i32,
8884       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8885                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8886 }
8887
8888 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8889 /// shuffle lowering, and the most complex part.
8890 ///
8891 /// The lowering strategy is to try to form pairs of input lanes which are
8892 /// targeted at the same half of the final vector, and then use a dword shuffle
8893 /// to place them onto the right half, and finally unpack the paired lanes into
8894 /// their final position.
8895 ///
8896 /// The exact breakdown of how to form these dword pairs and align them on the
8897 /// correct sides is really tricky. See the comments within the function for
8898 /// more of the details.
8899 ///
8900 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8901 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8902 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8903 /// vector, form the analogous 128-bit 8-element Mask.
8904 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8905     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8906     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8907   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8908   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8909
8910   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8911   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8912   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8913
8914   SmallVector<int, 4> LoInputs;
8915   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8916                [](int M) { return M >= 0; });
8917   std::sort(LoInputs.begin(), LoInputs.end());
8918   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8919   SmallVector<int, 4> HiInputs;
8920   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8921                [](int M) { return M >= 0; });
8922   std::sort(HiInputs.begin(), HiInputs.end());
8923   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8924   int NumLToL =
8925       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8926   int NumHToL = LoInputs.size() - NumLToL;
8927   int NumLToH =
8928       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8929   int NumHToH = HiInputs.size() - NumLToH;
8930   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8931   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8932   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8933   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8934
8935   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8936   // such inputs we can swap two of the dwords across the half mark and end up
8937   // with <=2 inputs to each half in each half. Once there, we can fall through
8938   // to the generic code below. For example:
8939   //
8940   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8941   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8942   //
8943   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8944   // and an existing 2-into-2 on the other half. In this case we may have to
8945   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8946   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8947   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8948   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8949   // half than the one we target for fixing) will be fixed when we re-enter this
8950   // path. We will also combine away any sequence of PSHUFD instructions that
8951   // result into a single instruction. Here is an example of the tricky case:
8952   //
8953   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8954   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8955   //
8956   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8957   //
8958   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8959   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8960   //
8961   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8962   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8963   //
8964   // The result is fine to be handled by the generic logic.
8965   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8966                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8967                           int AOffset, int BOffset) {
8968     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8969            "Must call this with A having 3 or 1 inputs from the A half.");
8970     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8971            "Must call this with B having 1 or 3 inputs from the B half.");
8972     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8973            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8974
8975     bool ThreeAInputs = AToAInputs.size() == 3;
8976
8977     // Compute the index of dword with only one word among the three inputs in
8978     // a half by taking the sum of the half with three inputs and subtracting
8979     // the sum of the actual three inputs. The difference is the remaining
8980     // slot.
8981     int ADWord, BDWord;
8982     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8983     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8984     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8985     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8986     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8987     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8988     int TripleNonInputIdx =
8989         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8990     TripleDWord = TripleNonInputIdx / 2;
8991
8992     // We use xor with one to compute the adjacent DWord to whichever one the
8993     // OneInput is in.
8994     OneInputDWord = (OneInput / 2) ^ 1;
8995
8996     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8997     // and BToA inputs. If there is also such a problem with the BToB and AToB
8998     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8999     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
9000     // is essential that we don't *create* a 3<-1 as then we might oscillate.
9001     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
9002       // Compute how many inputs will be flipped by swapping these DWords. We
9003       // need
9004       // to balance this to ensure we don't form a 3-1 shuffle in the other
9005       // half.
9006       int NumFlippedAToBInputs =
9007           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9008           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9009       int NumFlippedBToBInputs =
9010           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9011           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9012       if ((NumFlippedAToBInputs == 1 &&
9013            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9014           (NumFlippedBToBInputs == 1 &&
9015            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9016         // We choose whether to fix the A half or B half based on whether that
9017         // half has zero flipped inputs. At zero, we may not be able to fix it
9018         // with that half. We also bias towards fixing the B half because that
9019         // will more commonly be the high half, and we have to bias one way.
9020         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9021                                                        ArrayRef<int> Inputs) {
9022           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9023           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9024                                          PinnedIdx ^ 1) != Inputs.end();
9025           // Determine whether the free index is in the flipped dword or the
9026           // unflipped dword based on where the pinned index is. We use this bit
9027           // in an xor to conditionally select the adjacent dword.
9028           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9029           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9030                                              FixFreeIdx) != Inputs.end();
9031           if (IsFixIdxInput == IsFixFreeIdxInput)
9032             FixFreeIdx += 1;
9033           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9034                                         FixFreeIdx) != Inputs.end();
9035           assert(IsFixIdxInput != IsFixFreeIdxInput &&
9036                  "We need to be changing the number of flipped inputs!");
9037           int PSHUFHalfMask[] = {0, 1, 2, 3};
9038           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9039           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9040                           MVT::v8i16, V,
9041                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9042
9043           for (int &M : Mask)
9044             if (M != -1 && M == FixIdx)
9045               M = FixFreeIdx;
9046             else if (M != -1 && M == FixFreeIdx)
9047               M = FixIdx;
9048         };
9049         if (NumFlippedBToBInputs != 0) {
9050           int BPinnedIdx =
9051               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9052           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9053         } else {
9054           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9055           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9056           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9057         }
9058       }
9059     }
9060
9061     int PSHUFDMask[] = {0, 1, 2, 3};
9062     PSHUFDMask[ADWord] = BDWord;
9063     PSHUFDMask[BDWord] = ADWord;
9064     V = DAG.getBitcast(
9065         VT,
9066         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9067                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9068
9069     // Adjust the mask to match the new locations of A and B.
9070     for (int &M : Mask)
9071       if (M != -1 && M/2 == ADWord)
9072         M = 2 * BDWord + M % 2;
9073       else if (M != -1 && M/2 == BDWord)
9074         M = 2 * ADWord + M % 2;
9075
9076     // Recurse back into this routine to re-compute state now that this isn't
9077     // a 3 and 1 problem.
9078     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9079                                                      DAG);
9080   };
9081   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9082     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9083   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9084     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9085
9086   // At this point there are at most two inputs to the low and high halves from
9087   // each half. That means the inputs can always be grouped into dwords and
9088   // those dwords can then be moved to the correct half with a dword shuffle.
9089   // We use at most one low and one high word shuffle to collect these paired
9090   // inputs into dwords, and finally a dword shuffle to place them.
9091   int PSHUFLMask[4] = {-1, -1, -1, -1};
9092   int PSHUFHMask[4] = {-1, -1, -1, -1};
9093   int PSHUFDMask[4] = {-1, -1, -1, -1};
9094
9095   // First fix the masks for all the inputs that are staying in their
9096   // original halves. This will then dictate the targets of the cross-half
9097   // shuffles.
9098   auto fixInPlaceInputs =
9099       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9100                     MutableArrayRef<int> SourceHalfMask,
9101                     MutableArrayRef<int> HalfMask, int HalfOffset) {
9102     if (InPlaceInputs.empty())
9103       return;
9104     if (InPlaceInputs.size() == 1) {
9105       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9106           InPlaceInputs[0] - HalfOffset;
9107       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9108       return;
9109     }
9110     if (IncomingInputs.empty()) {
9111       // Just fix all of the in place inputs.
9112       for (int Input : InPlaceInputs) {
9113         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9114         PSHUFDMask[Input / 2] = Input / 2;
9115       }
9116       return;
9117     }
9118
9119     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9120     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9121         InPlaceInputs[0] - HalfOffset;
9122     // Put the second input next to the first so that they are packed into
9123     // a dword. We find the adjacent index by toggling the low bit.
9124     int AdjIndex = InPlaceInputs[0] ^ 1;
9125     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9126     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9127     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9128   };
9129   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9130   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9131
9132   // Now gather the cross-half inputs and place them into a free dword of
9133   // their target half.
9134   // FIXME: This operation could almost certainly be simplified dramatically to
9135   // look more like the 3-1 fixing operation.
9136   auto moveInputsToRightHalf = [&PSHUFDMask](
9137       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9138       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9139       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9140       int DestOffset) {
9141     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9142       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9143     };
9144     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9145                                                int Word) {
9146       int LowWord = Word & ~1;
9147       int HighWord = Word | 1;
9148       return isWordClobbered(SourceHalfMask, LowWord) ||
9149              isWordClobbered(SourceHalfMask, HighWord);
9150     };
9151
9152     if (IncomingInputs.empty())
9153       return;
9154
9155     if (ExistingInputs.empty()) {
9156       // Map any dwords with inputs from them into the right half.
9157       for (int Input : IncomingInputs) {
9158         // If the source half mask maps over the inputs, turn those into
9159         // swaps and use the swapped lane.
9160         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9161           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9162             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9163                 Input - SourceOffset;
9164             // We have to swap the uses in our half mask in one sweep.
9165             for (int &M : HalfMask)
9166               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9167                 M = Input;
9168               else if (M == Input)
9169                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9170           } else {
9171             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9172                        Input - SourceOffset &&
9173                    "Previous placement doesn't match!");
9174           }
9175           // Note that this correctly re-maps both when we do a swap and when
9176           // we observe the other side of the swap above. We rely on that to
9177           // avoid swapping the members of the input list directly.
9178           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9179         }
9180
9181         // Map the input's dword into the correct half.
9182         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9183           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9184         else
9185           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9186                      Input / 2 &&
9187                  "Previous placement doesn't match!");
9188       }
9189
9190       // And just directly shift any other-half mask elements to be same-half
9191       // as we will have mirrored the dword containing the element into the
9192       // same position within that half.
9193       for (int &M : HalfMask)
9194         if (M >= SourceOffset && M < SourceOffset + 4) {
9195           M = M - SourceOffset + DestOffset;
9196           assert(M >= 0 && "This should never wrap below zero!");
9197         }
9198       return;
9199     }
9200
9201     // Ensure we have the input in a viable dword of its current half. This
9202     // is particularly tricky because the original position may be clobbered
9203     // by inputs being moved and *staying* in that half.
9204     if (IncomingInputs.size() == 1) {
9205       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9206         int InputFixed = std::find(std::begin(SourceHalfMask),
9207                                    std::end(SourceHalfMask), -1) -
9208                          std::begin(SourceHalfMask) + SourceOffset;
9209         SourceHalfMask[InputFixed - SourceOffset] =
9210             IncomingInputs[0] - SourceOffset;
9211         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9212                      InputFixed);
9213         IncomingInputs[0] = InputFixed;
9214       }
9215     } else if (IncomingInputs.size() == 2) {
9216       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9217           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9218         // We have two non-adjacent or clobbered inputs we need to extract from
9219         // the source half. To do this, we need to map them into some adjacent
9220         // dword slot in the source mask.
9221         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9222                               IncomingInputs[1] - SourceOffset};
9223
9224         // If there is a free slot in the source half mask adjacent to one of
9225         // the inputs, place the other input in it. We use (Index XOR 1) to
9226         // compute an adjacent index.
9227         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9228             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9229           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9230           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9231           InputsFixed[1] = InputsFixed[0] ^ 1;
9232         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9233                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9234           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9235           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9236           InputsFixed[0] = InputsFixed[1] ^ 1;
9237         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9238                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9239           // The two inputs are in the same DWord but it is clobbered and the
9240           // adjacent DWord isn't used at all. Move both inputs to the free
9241           // slot.
9242           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9243           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9244           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9245           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9246         } else {
9247           // The only way we hit this point is if there is no clobbering
9248           // (because there are no off-half inputs to this half) and there is no
9249           // free slot adjacent to one of the inputs. In this case, we have to
9250           // swap an input with a non-input.
9251           for (int i = 0; i < 4; ++i)
9252             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9253                    "We can't handle any clobbers here!");
9254           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9255                  "Cannot have adjacent inputs here!");
9256
9257           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9258           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9259
9260           // We also have to update the final source mask in this case because
9261           // it may need to undo the above swap.
9262           for (int &M : FinalSourceHalfMask)
9263             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9264               M = InputsFixed[1] + SourceOffset;
9265             else if (M == InputsFixed[1] + SourceOffset)
9266               M = (InputsFixed[0] ^ 1) + SourceOffset;
9267
9268           InputsFixed[1] = InputsFixed[0] ^ 1;
9269         }
9270
9271         // Point everything at the fixed inputs.
9272         for (int &M : HalfMask)
9273           if (M == IncomingInputs[0])
9274             M = InputsFixed[0] + SourceOffset;
9275           else if (M == IncomingInputs[1])
9276             M = InputsFixed[1] + SourceOffset;
9277
9278         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9279         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9280       }
9281     } else {
9282       llvm_unreachable("Unhandled input size!");
9283     }
9284
9285     // Now hoist the DWord down to the right half.
9286     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9287     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9288     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9289     for (int &M : HalfMask)
9290       for (int Input : IncomingInputs)
9291         if (M == Input)
9292           M = FreeDWord * 2 + Input % 2;
9293   };
9294   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9295                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9296   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9297                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9298
9299   // Now enact all the shuffles we've computed to move the inputs into their
9300   // target half.
9301   if (!isNoopShuffleMask(PSHUFLMask))
9302     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9303                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9304   if (!isNoopShuffleMask(PSHUFHMask))
9305     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9306                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9307   if (!isNoopShuffleMask(PSHUFDMask))
9308     V = DAG.getBitcast(
9309         VT,
9310         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9311                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9312
9313   // At this point, each half should contain all its inputs, and we can then
9314   // just shuffle them into their final position.
9315   assert(std::count_if(LoMask.begin(), LoMask.end(),
9316                        [](int M) { return M >= 4; }) == 0 &&
9317          "Failed to lift all the high half inputs to the low mask!");
9318   assert(std::count_if(HiMask.begin(), HiMask.end(),
9319                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9320          "Failed to lift all the low half inputs to the high mask!");
9321
9322   // Do a half shuffle for the low mask.
9323   if (!isNoopShuffleMask(LoMask))
9324     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9325                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9326
9327   // Do a half shuffle with the high mask after shifting its values down.
9328   for (int &M : HiMask)
9329     if (M >= 0)
9330       M -= 4;
9331   if (!isNoopShuffleMask(HiMask))
9332     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9333                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9334
9335   return V;
9336 }
9337
9338 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9339 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9340                                           SDValue V2, ArrayRef<int> Mask,
9341                                           SelectionDAG &DAG, bool &V1InUse,
9342                                           bool &V2InUse) {
9343   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9344   SDValue V1Mask[16];
9345   SDValue V2Mask[16];
9346   V1InUse = false;
9347   V2InUse = false;
9348
9349   int Size = Mask.size();
9350   int Scale = 16 / Size;
9351   for (int i = 0; i < 16; ++i) {
9352     if (Mask[i / Scale] == -1) {
9353       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9354     } else {
9355       const int ZeroMask = 0x80;
9356       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9357                                           : ZeroMask;
9358       int V2Idx = Mask[i / Scale] < Size
9359                       ? ZeroMask
9360                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9361       if (Zeroable[i / Scale])
9362         V1Idx = V2Idx = ZeroMask;
9363       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9364       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9365       V1InUse |= (ZeroMask != V1Idx);
9366       V2InUse |= (ZeroMask != V2Idx);
9367     }
9368   }
9369
9370   if (V1InUse)
9371     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9372                      DAG.getBitcast(MVT::v16i8, V1),
9373                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9374   if (V2InUse)
9375     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9376                      DAG.getBitcast(MVT::v16i8, V2),
9377                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9378
9379   // If we need shuffled inputs from both, blend the two.
9380   SDValue V;
9381   if (V1InUse && V2InUse)
9382     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9383   else
9384     V = V1InUse ? V1 : V2;
9385
9386   // Cast the result back to the correct type.
9387   return DAG.getBitcast(VT, V);
9388 }
9389
9390 /// \brief Generic lowering of 8-lane i16 shuffles.
9391 ///
9392 /// This handles both single-input shuffles and combined shuffle/blends with
9393 /// two inputs. The single input shuffles are immediately delegated to
9394 /// a dedicated lowering routine.
9395 ///
9396 /// The blends are lowered in one of three fundamental ways. If there are few
9397 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9398 /// of the input is significantly cheaper when lowered as an interleaving of
9399 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9400 /// halves of the inputs separately (making them have relatively few inputs)
9401 /// and then concatenate them.
9402 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9403                                        const X86Subtarget *Subtarget,
9404                                        SelectionDAG &DAG) {
9405   SDLoc DL(Op);
9406   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9407   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9408   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9409   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9410   ArrayRef<int> OrigMask = SVOp->getMask();
9411   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9412                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9413   MutableArrayRef<int> Mask(MaskStorage);
9414
9415   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9416
9417   // Whenever we can lower this as a zext, that instruction is strictly faster
9418   // than any alternative.
9419   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9420           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9421     return ZExt;
9422
9423   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9424   (void)isV1;
9425   auto isV2 = [](int M) { return M >= 8; };
9426
9427   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9428
9429   if (NumV2Inputs == 0) {
9430     // Check for being able to broadcast a single element.
9431     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9432                                                           Mask, Subtarget, DAG))
9433       return Broadcast;
9434
9435     // Try to use shift instructions.
9436     if (SDValue Shift =
9437             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9438       return Shift;
9439
9440     // Use dedicated unpack instructions for masks that match their pattern.
9441     if (SDValue V =
9442             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9443       return V;
9444
9445     // Try to use byte rotation instructions.
9446     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9447                                                         Mask, Subtarget, DAG))
9448       return Rotate;
9449
9450     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9451                                                      Subtarget, DAG);
9452   }
9453
9454   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9455          "All single-input shuffles should be canonicalized to be V1-input "
9456          "shuffles.");
9457
9458   // Try to use shift instructions.
9459   if (SDValue Shift =
9460           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9461     return Shift;
9462
9463   // See if we can use SSE4A Extraction / Insertion.
9464   if (Subtarget->hasSSE4A())
9465     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9466       return V;
9467
9468   // There are special ways we can lower some single-element blends.
9469   if (NumV2Inputs == 1)
9470     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9471                                                          Mask, Subtarget, DAG))
9472       return V;
9473
9474   // We have different paths for blend lowering, but they all must use the
9475   // *exact* same predicate.
9476   bool IsBlendSupported = Subtarget->hasSSE41();
9477   if (IsBlendSupported)
9478     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9479                                                   Subtarget, DAG))
9480       return Blend;
9481
9482   if (SDValue Masked =
9483           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9484     return Masked;
9485
9486   // Use dedicated unpack instructions for masks that match their pattern.
9487   if (SDValue V =
9488           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9489     return V;
9490
9491   // Try to use byte rotation instructions.
9492   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9493           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9494     return Rotate;
9495
9496   if (SDValue BitBlend =
9497           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9498     return BitBlend;
9499
9500   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9501                                                             V2, Mask, DAG))
9502     return Unpack;
9503
9504   // If we can't directly blend but can use PSHUFB, that will be better as it
9505   // can both shuffle and set up the inefficient blend.
9506   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9507     bool V1InUse, V2InUse;
9508     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9509                                       V1InUse, V2InUse);
9510   }
9511
9512   // We can always bit-blend if we have to so the fallback strategy is to
9513   // decompose into single-input permutes and blends.
9514   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9515                                                       Mask, DAG);
9516 }
9517
9518 /// \brief Check whether a compaction lowering can be done by dropping even
9519 /// elements and compute how many times even elements must be dropped.
9520 ///
9521 /// This handles shuffles which take every Nth element where N is a power of
9522 /// two. Example shuffle masks:
9523 ///
9524 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9525 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9526 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9527 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9528 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9529 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9530 ///
9531 /// Any of these lanes can of course be undef.
9532 ///
9533 /// This routine only supports N <= 3.
9534 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9535 /// for larger N.
9536 ///
9537 /// \returns N above, or the number of times even elements must be dropped if
9538 /// there is such a number. Otherwise returns zero.
9539 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9540   // Figure out whether we're looping over two inputs or just one.
9541   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9542
9543   // The modulus for the shuffle vector entries is based on whether this is
9544   // a single input or not.
9545   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9546   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9547          "We should only be called with masks with a power-of-2 size!");
9548
9549   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9550
9551   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9552   // and 2^3 simultaneously. This is because we may have ambiguity with
9553   // partially undef inputs.
9554   bool ViableForN[3] = {true, true, true};
9555
9556   for (int i = 0, e = Mask.size(); i < e; ++i) {
9557     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9558     // want.
9559     if (Mask[i] == -1)
9560       continue;
9561
9562     bool IsAnyViable = false;
9563     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9564       if (ViableForN[j]) {
9565         uint64_t N = j + 1;
9566
9567         // The shuffle mask must be equal to (i * 2^N) % M.
9568         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9569           IsAnyViable = true;
9570         else
9571           ViableForN[j] = false;
9572       }
9573     // Early exit if we exhaust the possible powers of two.
9574     if (!IsAnyViable)
9575       break;
9576   }
9577
9578   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9579     if (ViableForN[j])
9580       return j + 1;
9581
9582   // Return 0 as there is no viable power of two.
9583   return 0;
9584 }
9585
9586 /// \brief Generic lowering of v16i8 shuffles.
9587 ///
9588 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9589 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9590 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9591 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9592 /// back together.
9593 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9594                                        const X86Subtarget *Subtarget,
9595                                        SelectionDAG &DAG) {
9596   SDLoc DL(Op);
9597   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9598   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9599   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9600   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9601   ArrayRef<int> Mask = SVOp->getMask();
9602   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9603
9604   // Try to use shift instructions.
9605   if (SDValue Shift =
9606           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9607     return Shift;
9608
9609   // Try to use byte rotation instructions.
9610   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9611           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9612     return Rotate;
9613
9614   // Try to use a zext lowering.
9615   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9616           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9617     return ZExt;
9618
9619   // See if we can use SSE4A Extraction / Insertion.
9620   if (Subtarget->hasSSE4A())
9621     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9622       return V;
9623
9624   int NumV2Elements =
9625       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9626
9627   // For single-input shuffles, there are some nicer lowering tricks we can use.
9628   if (NumV2Elements == 0) {
9629     // Check for being able to broadcast a single element.
9630     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9631                                                           Mask, Subtarget, DAG))
9632       return Broadcast;
9633
9634     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9635     // Notably, this handles splat and partial-splat shuffles more efficiently.
9636     // However, it only makes sense if the pre-duplication shuffle simplifies
9637     // things significantly. Currently, this means we need to be able to
9638     // express the pre-duplication shuffle as an i16 shuffle.
9639     //
9640     // FIXME: We should check for other patterns which can be widened into an
9641     // i16 shuffle as well.
9642     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9643       for (int i = 0; i < 16; i += 2)
9644         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9645           return false;
9646
9647       return true;
9648     };
9649     auto tryToWidenViaDuplication = [&]() -> SDValue {
9650       if (!canWidenViaDuplication(Mask))
9651         return SDValue();
9652       SmallVector<int, 4> LoInputs;
9653       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9654                    [](int M) { return M >= 0 && M < 8; });
9655       std::sort(LoInputs.begin(), LoInputs.end());
9656       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9657                      LoInputs.end());
9658       SmallVector<int, 4> HiInputs;
9659       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9660                    [](int M) { return M >= 8; });
9661       std::sort(HiInputs.begin(), HiInputs.end());
9662       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9663                      HiInputs.end());
9664
9665       bool TargetLo = LoInputs.size() >= HiInputs.size();
9666       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9667       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9668
9669       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9670       SmallDenseMap<int, int, 8> LaneMap;
9671       for (int I : InPlaceInputs) {
9672         PreDupI16Shuffle[I/2] = I/2;
9673         LaneMap[I] = I;
9674       }
9675       int j = TargetLo ? 0 : 4, je = j + 4;
9676       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9677         // Check if j is already a shuffle of this input. This happens when
9678         // there are two adjacent bytes after we move the low one.
9679         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9680           // If we haven't yet mapped the input, search for a slot into which
9681           // we can map it.
9682           while (j < je && PreDupI16Shuffle[j] != -1)
9683             ++j;
9684
9685           if (j == je)
9686             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9687             return SDValue();
9688
9689           // Map this input with the i16 shuffle.
9690           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9691         }
9692
9693         // Update the lane map based on the mapping we ended up with.
9694         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9695       }
9696       V1 = DAG.getBitcast(
9697           MVT::v16i8,
9698           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9699                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9700
9701       // Unpack the bytes to form the i16s that will be shuffled into place.
9702       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9703                        MVT::v16i8, V1, V1);
9704
9705       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9706       for (int i = 0; i < 16; ++i)
9707         if (Mask[i] != -1) {
9708           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9709           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9710           if (PostDupI16Shuffle[i / 2] == -1)
9711             PostDupI16Shuffle[i / 2] = MappedMask;
9712           else
9713             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9714                    "Conflicting entrties in the original shuffle!");
9715         }
9716       return DAG.getBitcast(
9717           MVT::v16i8,
9718           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9719                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9720     };
9721     if (SDValue V = tryToWidenViaDuplication())
9722       return V;
9723   }
9724
9725   if (SDValue Masked =
9726           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9727     return Masked;
9728
9729   // Use dedicated unpack instructions for masks that match their pattern.
9730   if (SDValue V =
9731           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9732     return V;
9733
9734   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9735   // with PSHUFB. It is important to do this before we attempt to generate any
9736   // blends but after all of the single-input lowerings. If the single input
9737   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9738   // want to preserve that and we can DAG combine any longer sequences into
9739   // a PSHUFB in the end. But once we start blending from multiple inputs,
9740   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9741   // and there are *very* few patterns that would actually be faster than the
9742   // PSHUFB approach because of its ability to zero lanes.
9743   //
9744   // FIXME: The only exceptions to the above are blends which are exact
9745   // interleavings with direct instructions supporting them. We currently don't
9746   // handle those well here.
9747   if (Subtarget->hasSSSE3()) {
9748     bool V1InUse = false;
9749     bool V2InUse = false;
9750
9751     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9752                                                 DAG, V1InUse, V2InUse);
9753
9754     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9755     // do so. This avoids using them to handle blends-with-zero which is
9756     // important as a single pshufb is significantly faster for that.
9757     if (V1InUse && V2InUse) {
9758       if (Subtarget->hasSSE41())
9759         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9760                                                       Mask, Subtarget, DAG))
9761           return Blend;
9762
9763       // We can use an unpack to do the blending rather than an or in some
9764       // cases. Even though the or may be (very minorly) more efficient, we
9765       // preference this lowering because there are common cases where part of
9766       // the complexity of the shuffles goes away when we do the final blend as
9767       // an unpack.
9768       // FIXME: It might be worth trying to detect if the unpack-feeding
9769       // shuffles will both be pshufb, in which case we shouldn't bother with
9770       // this.
9771       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9772               DL, MVT::v16i8, V1, V2, Mask, DAG))
9773         return Unpack;
9774     }
9775
9776     return PSHUFB;
9777   }
9778
9779   // There are special ways we can lower some single-element blends.
9780   if (NumV2Elements == 1)
9781     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9782                                                          Mask, Subtarget, DAG))
9783       return V;
9784
9785   if (SDValue BitBlend =
9786           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9787     return BitBlend;
9788
9789   // Check whether a compaction lowering can be done. This handles shuffles
9790   // which take every Nth element for some even N. See the helper function for
9791   // details.
9792   //
9793   // We special case these as they can be particularly efficiently handled with
9794   // the PACKUSB instruction on x86 and they show up in common patterns of
9795   // rearranging bytes to truncate wide elements.
9796   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9797     // NumEvenDrops is the power of two stride of the elements. Another way of
9798     // thinking about it is that we need to drop the even elements this many
9799     // times to get the original input.
9800     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9801
9802     // First we need to zero all the dropped bytes.
9803     assert(NumEvenDrops <= 3 &&
9804            "No support for dropping even elements more than 3 times.");
9805     // We use the mask type to pick which bytes are preserved based on how many
9806     // elements are dropped.
9807     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9808     SDValue ByteClearMask = DAG.getBitcast(
9809         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9810     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9811     if (!IsSingleInput)
9812       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9813
9814     // Now pack things back together.
9815     V1 = DAG.getBitcast(MVT::v8i16, V1);
9816     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9817     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9818     for (int i = 1; i < NumEvenDrops; ++i) {
9819       Result = DAG.getBitcast(MVT::v8i16, Result);
9820       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9821     }
9822
9823     return Result;
9824   }
9825
9826   // Handle multi-input cases by blending single-input shuffles.
9827   if (NumV2Elements > 0)
9828     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9829                                                       Mask, DAG);
9830
9831   // The fallback path for single-input shuffles widens this into two v8i16
9832   // vectors with unpacks, shuffles those, and then pulls them back together
9833   // with a pack.
9834   SDValue V = V1;
9835
9836   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9837   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9838   for (int i = 0; i < 16; ++i)
9839     if (Mask[i] >= 0)
9840       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9841
9842   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9843
9844   SDValue VLoHalf, VHiHalf;
9845   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9846   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9847   // i16s.
9848   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9849                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9850       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9851                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9852     // Use a mask to drop the high bytes.
9853     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9854     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9855                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9856
9857     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9858     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9859
9860     // Squash the masks to point directly into VLoHalf.
9861     for (int &M : LoBlendMask)
9862       if (M >= 0)
9863         M /= 2;
9864     for (int &M : HiBlendMask)
9865       if (M >= 0)
9866         M /= 2;
9867   } else {
9868     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9869     // VHiHalf so that we can blend them as i16s.
9870     VLoHalf = DAG.getBitcast(
9871         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9872     VHiHalf = DAG.getBitcast(
9873         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9874   }
9875
9876   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9877   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9878
9879   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9880 }
9881
9882 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9883 ///
9884 /// This routine breaks down the specific type of 128-bit shuffle and
9885 /// dispatches to the lowering routines accordingly.
9886 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9887                                         MVT VT, const X86Subtarget *Subtarget,
9888                                         SelectionDAG &DAG) {
9889   switch (VT.SimpleTy) {
9890   case MVT::v2i64:
9891     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9892   case MVT::v2f64:
9893     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9894   case MVT::v4i32:
9895     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9896   case MVT::v4f32:
9897     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9898   case MVT::v8i16:
9899     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9900   case MVT::v16i8:
9901     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9902
9903   default:
9904     llvm_unreachable("Unimplemented!");
9905   }
9906 }
9907
9908 /// \brief Helper function to test whether a shuffle mask could be
9909 /// simplified by widening the elements being shuffled.
9910 ///
9911 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9912 /// leaves it in an unspecified state.
9913 ///
9914 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9915 /// shuffle masks. The latter have the special property of a '-2' representing
9916 /// a zero-ed lane of a vector.
9917 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9918                                     SmallVectorImpl<int> &WidenedMask) {
9919   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9920     // If both elements are undef, its trivial.
9921     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9922       WidenedMask.push_back(SM_SentinelUndef);
9923       continue;
9924     }
9925
9926     // Check for an undef mask and a mask value properly aligned to fit with
9927     // a pair of values. If we find such a case, use the non-undef mask's value.
9928     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9929       WidenedMask.push_back(Mask[i + 1] / 2);
9930       continue;
9931     }
9932     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9933       WidenedMask.push_back(Mask[i] / 2);
9934       continue;
9935     }
9936
9937     // When zeroing, we need to spread the zeroing across both lanes to widen.
9938     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9939       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9940           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9941         WidenedMask.push_back(SM_SentinelZero);
9942         continue;
9943       }
9944       return false;
9945     }
9946
9947     // Finally check if the two mask values are adjacent and aligned with
9948     // a pair.
9949     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9950       WidenedMask.push_back(Mask[i] / 2);
9951       continue;
9952     }
9953
9954     // Otherwise we can't safely widen the elements used in this shuffle.
9955     return false;
9956   }
9957   assert(WidenedMask.size() == Mask.size() / 2 &&
9958          "Incorrect size of mask after widening the elements!");
9959
9960   return true;
9961 }
9962
9963 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9964 ///
9965 /// This routine just extracts two subvectors, shuffles them independently, and
9966 /// then concatenates them back together. This should work effectively with all
9967 /// AVX vector shuffle types.
9968 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9969                                           SDValue V2, ArrayRef<int> Mask,
9970                                           SelectionDAG &DAG) {
9971   assert(VT.getSizeInBits() >= 256 &&
9972          "Only for 256-bit or wider vector shuffles!");
9973   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9974   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9975
9976   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9977   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9978
9979   int NumElements = VT.getVectorNumElements();
9980   int SplitNumElements = NumElements / 2;
9981   MVT ScalarVT = VT.getVectorElementType();
9982   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9983
9984   // Rather than splitting build-vectors, just build two narrower build
9985   // vectors. This helps shuffling with splats and zeros.
9986   auto SplitVector = [&](SDValue V) {
9987     while (V.getOpcode() == ISD::BITCAST)
9988       V = V->getOperand(0);
9989
9990     MVT OrigVT = V.getSimpleValueType();
9991     int OrigNumElements = OrigVT.getVectorNumElements();
9992     int OrigSplitNumElements = OrigNumElements / 2;
9993     MVT OrigScalarVT = OrigVT.getVectorElementType();
9994     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9995
9996     SDValue LoV, HiV;
9997
9998     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9999     if (!BV) {
10000       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10001                         DAG.getIntPtrConstant(0, DL));
10002       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10003                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
10004     } else {
10005
10006       SmallVector<SDValue, 16> LoOps, HiOps;
10007       for (int i = 0; i < OrigSplitNumElements; ++i) {
10008         LoOps.push_back(BV->getOperand(i));
10009         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10010       }
10011       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10012       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10013     }
10014     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10015                           DAG.getBitcast(SplitVT, HiV));
10016   };
10017
10018   SDValue LoV1, HiV1, LoV2, HiV2;
10019   std::tie(LoV1, HiV1) = SplitVector(V1);
10020   std::tie(LoV2, HiV2) = SplitVector(V2);
10021
10022   // Now create two 4-way blends of these half-width vectors.
10023   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10024     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10025     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10026     for (int i = 0; i < SplitNumElements; ++i) {
10027       int M = HalfMask[i];
10028       if (M >= NumElements) {
10029         if (M >= NumElements + SplitNumElements)
10030           UseHiV2 = true;
10031         else
10032           UseLoV2 = true;
10033         V2BlendMask.push_back(M - NumElements);
10034         V1BlendMask.push_back(-1);
10035         BlendMask.push_back(SplitNumElements + i);
10036       } else if (M >= 0) {
10037         if (M >= SplitNumElements)
10038           UseHiV1 = true;
10039         else
10040           UseLoV1 = true;
10041         V2BlendMask.push_back(-1);
10042         V1BlendMask.push_back(M);
10043         BlendMask.push_back(i);
10044       } else {
10045         V2BlendMask.push_back(-1);
10046         V1BlendMask.push_back(-1);
10047         BlendMask.push_back(-1);
10048       }
10049     }
10050
10051     // Because the lowering happens after all combining takes place, we need to
10052     // manually combine these blend masks as much as possible so that we create
10053     // a minimal number of high-level vector shuffle nodes.
10054
10055     // First try just blending the halves of V1 or V2.
10056     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10057       return DAG.getUNDEF(SplitVT);
10058     if (!UseLoV2 && !UseHiV2)
10059       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10060     if (!UseLoV1 && !UseHiV1)
10061       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10062
10063     SDValue V1Blend, V2Blend;
10064     if (UseLoV1 && UseHiV1) {
10065       V1Blend =
10066         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10067     } else {
10068       // We only use half of V1 so map the usage down into the final blend mask.
10069       V1Blend = UseLoV1 ? LoV1 : HiV1;
10070       for (int i = 0; i < SplitNumElements; ++i)
10071         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10072           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10073     }
10074     if (UseLoV2 && UseHiV2) {
10075       V2Blend =
10076         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10077     } else {
10078       // We only use half of V2 so map the usage down into the final blend mask.
10079       V2Blend = UseLoV2 ? LoV2 : HiV2;
10080       for (int i = 0; i < SplitNumElements; ++i)
10081         if (BlendMask[i] >= SplitNumElements)
10082           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10083     }
10084     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10085   };
10086   SDValue Lo = HalfBlend(LoMask);
10087   SDValue Hi = HalfBlend(HiMask);
10088   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10089 }
10090
10091 /// \brief Either split a vector in halves or decompose the shuffles and the
10092 /// blend.
10093 ///
10094 /// This is provided as a good fallback for many lowerings of non-single-input
10095 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10096 /// between splitting the shuffle into 128-bit components and stitching those
10097 /// back together vs. extracting the single-input shuffles and blending those
10098 /// results.
10099 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10100                                                 SDValue V2, ArrayRef<int> Mask,
10101                                                 SelectionDAG &DAG) {
10102   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10103                                             "lower single-input shuffles as it "
10104                                             "could then recurse on itself.");
10105   int Size = Mask.size();
10106
10107   // If this can be modeled as a broadcast of two elements followed by a blend,
10108   // prefer that lowering. This is especially important because broadcasts can
10109   // often fold with memory operands.
10110   auto DoBothBroadcast = [&] {
10111     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10112     for (int M : Mask)
10113       if (M >= Size) {
10114         if (V2BroadcastIdx == -1)
10115           V2BroadcastIdx = M - Size;
10116         else if (M - Size != V2BroadcastIdx)
10117           return false;
10118       } else if (M >= 0) {
10119         if (V1BroadcastIdx == -1)
10120           V1BroadcastIdx = M;
10121         else if (M != V1BroadcastIdx)
10122           return false;
10123       }
10124     return true;
10125   };
10126   if (DoBothBroadcast())
10127     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10128                                                       DAG);
10129
10130   // If the inputs all stem from a single 128-bit lane of each input, then we
10131   // split them rather than blending because the split will decompose to
10132   // unusually few instructions.
10133   int LaneCount = VT.getSizeInBits() / 128;
10134   int LaneSize = Size / LaneCount;
10135   SmallBitVector LaneInputs[2];
10136   LaneInputs[0].resize(LaneCount, false);
10137   LaneInputs[1].resize(LaneCount, false);
10138   for (int i = 0; i < Size; ++i)
10139     if (Mask[i] >= 0)
10140       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10141   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10142     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10143
10144   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10145   // that the decomposed single-input shuffles don't end up here.
10146   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10147 }
10148
10149 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10150 /// a permutation and blend of those lanes.
10151 ///
10152 /// This essentially blends the out-of-lane inputs to each lane into the lane
10153 /// from a permuted copy of the vector. This lowering strategy results in four
10154 /// instructions in the worst case for a single-input cross lane shuffle which
10155 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10156 /// of. Special cases for each particular shuffle pattern should be handled
10157 /// prior to trying this lowering.
10158 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10159                                                        SDValue V1, SDValue V2,
10160                                                        ArrayRef<int> Mask,
10161                                                        SelectionDAG &DAG) {
10162   // FIXME: This should probably be generalized for 512-bit vectors as well.
10163   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10164   int LaneSize = Mask.size() / 2;
10165
10166   // If there are only inputs from one 128-bit lane, splitting will in fact be
10167   // less expensive. The flags track whether the given lane contains an element
10168   // that crosses to another lane.
10169   bool LaneCrossing[2] = {false, false};
10170   for (int i = 0, Size = Mask.size(); i < Size; ++i)
10171     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10172       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10173   if (!LaneCrossing[0] || !LaneCrossing[1])
10174     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10175
10176   if (isSingleInputShuffleMask(Mask)) {
10177     SmallVector<int, 32> FlippedBlendMask;
10178     for (int i = 0, Size = Mask.size(); i < Size; ++i)
10179       FlippedBlendMask.push_back(
10180           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10181                                   ? Mask[i]
10182                                   : Mask[i] % LaneSize +
10183                                         (i / LaneSize) * LaneSize + Size));
10184
10185     // Flip the vector, and blend the results which should now be in-lane. The
10186     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10187     // 5 for the high source. The value 3 selects the high half of source 2 and
10188     // the value 2 selects the low half of source 2. We only use source 2 to
10189     // allow folding it into a memory operand.
10190     unsigned PERMMask = 3 | 2 << 4;
10191     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10192                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10193     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10194   }
10195
10196   // This now reduces to two single-input shuffles of V1 and V2 which at worst
10197   // will be handled by the above logic and a blend of the results, much like
10198   // other patterns in AVX.
10199   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10200 }
10201
10202 /// \brief Handle lowering 2-lane 128-bit shuffles.
10203 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10204                                         SDValue V2, ArrayRef<int> Mask,
10205                                         const X86Subtarget *Subtarget,
10206                                         SelectionDAG &DAG) {
10207   // TODO: If minimizing size and one of the inputs is a zero vector and the
10208   // the zero vector has only one use, we could use a VPERM2X128 to save the
10209   // instruction bytes needed to explicitly generate the zero vector.
10210
10211   // Blends are faster and handle all the non-lane-crossing cases.
10212   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10213                                                 Subtarget, DAG))
10214     return Blend;
10215
10216   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10217   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10218
10219   // If either input operand is a zero vector, use VPERM2X128 because its mask
10220   // allows us to replace the zero input with an implicit zero.
10221   if (!IsV1Zero && !IsV2Zero) {
10222     // Check for patterns which can be matched with a single insert of a 128-bit
10223     // subvector.
10224     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10225     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10226       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10227                                    VT.getVectorNumElements() / 2);
10228       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10229                                 DAG.getIntPtrConstant(0, DL));
10230       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10231                                 OnlyUsesV1 ? V1 : V2,
10232                                 DAG.getIntPtrConstant(0, DL));
10233       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10234     }
10235   }
10236
10237   // Otherwise form a 128-bit permutation. After accounting for undefs,
10238   // convert the 64-bit shuffle mask selection values into 128-bit
10239   // selection bits by dividing the indexes by 2 and shifting into positions
10240   // defined by a vperm2*128 instruction's immediate control byte.
10241
10242   // The immediate permute control byte looks like this:
10243   //    [1:0] - select 128 bits from sources for low half of destination
10244   //    [2]   - ignore
10245   //    [3]   - zero low half of destination
10246   //    [5:4] - select 128 bits from sources for high half of destination
10247   //    [6]   - ignore
10248   //    [7]   - zero high half of destination
10249
10250   int MaskLO = Mask[0];
10251   if (MaskLO == SM_SentinelUndef)
10252     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10253
10254   int MaskHI = Mask[2];
10255   if (MaskHI == SM_SentinelUndef)
10256     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10257
10258   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10259
10260   // If either input is a zero vector, replace it with an undef input.
10261   // Shuffle mask values <  4 are selecting elements of V1.
10262   // Shuffle mask values >= 4 are selecting elements of V2.
10263   // Adjust each half of the permute mask by clearing the half that was
10264   // selecting the zero vector and setting the zero mask bit.
10265   if (IsV1Zero) {
10266     V1 = DAG.getUNDEF(VT);
10267     if (MaskLO < 4)
10268       PermMask = (PermMask & 0xf0) | 0x08;
10269     if (MaskHI < 4)
10270       PermMask = (PermMask & 0x0f) | 0x80;
10271   }
10272   if (IsV2Zero) {
10273     V2 = DAG.getUNDEF(VT);
10274     if (MaskLO >= 4)
10275       PermMask = (PermMask & 0xf0) | 0x08;
10276     if (MaskHI >= 4)
10277       PermMask = (PermMask & 0x0f) | 0x80;
10278   }
10279
10280   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10281                      DAG.getConstant(PermMask, DL, MVT::i8));
10282 }
10283
10284 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10285 /// shuffling each lane.
10286 ///
10287 /// This will only succeed when the result of fixing the 128-bit lanes results
10288 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10289 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10290 /// the lane crosses early and then use simpler shuffles within each lane.
10291 ///
10292 /// FIXME: It might be worthwhile at some point to support this without
10293 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10294 /// in x86 only floating point has interesting non-repeating shuffles, and even
10295 /// those are still *marginally* more expensive.
10296 static SDValue lowerVectorShuffleByMerging128BitLanes(
10297     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10298     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10299   assert(!isSingleInputShuffleMask(Mask) &&
10300          "This is only useful with multiple inputs.");
10301
10302   int Size = Mask.size();
10303   int LaneSize = 128 / VT.getScalarSizeInBits();
10304   int NumLanes = Size / LaneSize;
10305   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10306
10307   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10308   // check whether the in-128-bit lane shuffles share a repeating pattern.
10309   SmallVector<int, 4> Lanes;
10310   Lanes.resize(NumLanes, -1);
10311   SmallVector<int, 4> InLaneMask;
10312   InLaneMask.resize(LaneSize, -1);
10313   for (int i = 0; i < Size; ++i) {
10314     if (Mask[i] < 0)
10315       continue;
10316
10317     int j = i / LaneSize;
10318
10319     if (Lanes[j] < 0) {
10320       // First entry we've seen for this lane.
10321       Lanes[j] = Mask[i] / LaneSize;
10322     } else if (Lanes[j] != Mask[i] / LaneSize) {
10323       // This doesn't match the lane selected previously!
10324       return SDValue();
10325     }
10326
10327     // Check that within each lane we have a consistent shuffle mask.
10328     int k = i % LaneSize;
10329     if (InLaneMask[k] < 0) {
10330       InLaneMask[k] = Mask[i] % LaneSize;
10331     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10332       // This doesn't fit a repeating in-lane mask.
10333       return SDValue();
10334     }
10335   }
10336
10337   // First shuffle the lanes into place.
10338   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10339                                 VT.getSizeInBits() / 64);
10340   SmallVector<int, 8> LaneMask;
10341   LaneMask.resize(NumLanes * 2, -1);
10342   for (int i = 0; i < NumLanes; ++i)
10343     if (Lanes[i] >= 0) {
10344       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10345       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10346     }
10347
10348   V1 = DAG.getBitcast(LaneVT, V1);
10349   V2 = DAG.getBitcast(LaneVT, V2);
10350   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10351
10352   // Cast it back to the type we actually want.
10353   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10354
10355   // Now do a simple shuffle that isn't lane crossing.
10356   SmallVector<int, 8> NewMask;
10357   NewMask.resize(Size, -1);
10358   for (int i = 0; i < Size; ++i)
10359     if (Mask[i] >= 0)
10360       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10361   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10362          "Must not introduce lane crosses at this point!");
10363
10364   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10365 }
10366
10367 /// Lower shuffles where an entire half of a 256-bit vector is UNDEF.
10368 /// This allows for fast cases such as subvector extraction/insertion
10369 /// or shuffling smaller vector types which can lower more efficiently.
10370 static SDValue lowerVectorShuffleWithUndefHalf(SDLoc DL, MVT VT, SDValue V1,
10371                                                SDValue V2, ArrayRef<int> Mask,
10372                                                const X86Subtarget *Subtarget,
10373                                                SelectionDAG &DAG) {
10374   assert(VT.getSizeInBits() == 256 && "Expected 256-bit vector");
10375
10376   unsigned NumElts = VT.getVectorNumElements();
10377   unsigned HalfNumElts = NumElts / 2;
10378   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
10379
10380   bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
10381   bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
10382   if (!UndefLower && !UndefUpper)
10383     return SDValue();
10384
10385   // Upper half is undef and lower half is whole upper subvector.
10386   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
10387   if (UndefUpper &&
10388       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
10389     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10390                              DAG.getIntPtrConstant(HalfNumElts, DL));
10391     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10392                        DAG.getIntPtrConstant(0, DL));
10393   }
10394
10395   // Lower half is undef and upper half is whole lower subvector.
10396   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
10397   if (UndefLower &&
10398       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
10399     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10400                              DAG.getIntPtrConstant(0, DL));
10401     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10402                        DAG.getIntPtrConstant(HalfNumElts, DL));
10403   }
10404
10405   // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
10406   if (UndefLower && Subtarget->hasAVX2() &&
10407       (VT == MVT::v4f64 || VT == MVT::v4i64))
10408     return SDValue();
10409
10410   // If the shuffle only uses the lower halves of the input operands,
10411   // then extract them and perform the 'half' shuffle at half width.
10412   // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
10413   int HalfIdx1 = -1, HalfIdx2 = -1;
10414   SmallVector<int, 8> HalfMask;
10415   unsigned Offset = UndefLower ? HalfNumElts : 0;
10416   for (unsigned i = 0; i != HalfNumElts; ++i) {
10417     int M = Mask[i + Offset];
10418     if (M < 0) {
10419       HalfMask.push_back(M);
10420       continue;
10421     }
10422
10423     // Determine which of the 4 half vectors this element is from.
10424     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
10425     int HalfIdx = M / HalfNumElts;
10426
10427     // Only shuffle using the lower halves of the inputs.
10428     // TODO: Investigate usefulness of shuffling with upper halves.
10429     if (HalfIdx != 0 && HalfIdx != 2)
10430       return SDValue();
10431
10432     // Determine the element index into its half vector source.
10433     int HalfElt = M % HalfNumElts;
10434
10435     // We can shuffle with up to 2 half vectors, set the new 'half'
10436     // shuffle mask accordingly.
10437     if (-1 == HalfIdx1 || HalfIdx1 == HalfIdx) {
10438       HalfMask.push_back(HalfElt);
10439       HalfIdx1 = HalfIdx;
10440       continue;
10441     }
10442     if (-1 == HalfIdx2 || HalfIdx2 == HalfIdx) {
10443       HalfMask.push_back(HalfElt + HalfNumElts);
10444       HalfIdx2 = HalfIdx;
10445       continue;
10446     }
10447
10448     // Too many half vectors referenced.
10449     return SDValue();
10450   }
10451   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
10452
10453   auto GetHalfVector = [&](int HalfIdx) {
10454     if (HalfIdx < 0)
10455       return DAG.getUNDEF(HalfVT);
10456     SDValue V = (HalfIdx < 2 ? V1 : V2);
10457     HalfIdx = (HalfIdx % 2) * HalfNumElts;
10458     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
10459                        DAG.getIntPtrConstant(HalfIdx, DL));
10460   };
10461
10462   SDValue Half1 = GetHalfVector(HalfIdx1);
10463   SDValue Half2 = GetHalfVector(HalfIdx2);
10464   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
10465   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
10466                      DAG.getIntPtrConstant(Offset, DL));
10467 }
10468
10469 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10470 /// given mask.
10471 ///
10472 /// This returns true if the elements from a particular input are already in the
10473 /// slot required by the given mask and require no permutation.
10474 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10475   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10476   int Size = Mask.size();
10477   for (int i = 0; i < Size; ++i)
10478     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10479       return false;
10480
10481   return true;
10482 }
10483
10484 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10485                                             ArrayRef<int> Mask, SDValue V1,
10486                                             SDValue V2, SelectionDAG &DAG) {
10487
10488   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10489   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10490   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10491   int NumElts = VT.getVectorNumElements();
10492   bool ShufpdMask = true;
10493   bool CommutableMask = true;
10494   unsigned Immediate = 0;
10495   for (int i = 0; i < NumElts; ++i) {
10496     if (Mask[i] < 0)
10497       continue;
10498     int Val = (i & 6) + NumElts * (i & 1);
10499     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10500     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10501       ShufpdMask = false;
10502     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10503       CommutableMask = false;
10504     Immediate |= (Mask[i] % 2) << i;
10505   }
10506   if (ShufpdMask)
10507     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10508                        DAG.getConstant(Immediate, DL, MVT::i8));
10509   if (CommutableMask)
10510     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10511                        DAG.getConstant(Immediate, DL, MVT::i8));
10512   return SDValue();
10513 }
10514
10515 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10516 ///
10517 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10518 /// isn't available.
10519 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10520                                        const X86Subtarget *Subtarget,
10521                                        SelectionDAG &DAG) {
10522   SDLoc DL(Op);
10523   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10524   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10525   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10526   ArrayRef<int> Mask = SVOp->getMask();
10527   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10528
10529   SmallVector<int, 4> WidenedMask;
10530   if (canWidenShuffleElements(Mask, WidenedMask))
10531     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10532                                     DAG);
10533
10534   if (isSingleInputShuffleMask(Mask)) {
10535     // Check for being able to broadcast a single element.
10536     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10537                                                           Mask, Subtarget, DAG))
10538       return Broadcast;
10539
10540     // Use low duplicate instructions for masks that match their pattern.
10541     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10542       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10543
10544     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10545       // Non-half-crossing single input shuffles can be lowerid with an
10546       // interleaved permutation.
10547       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10548                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10549       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10550                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10551     }
10552
10553     // With AVX2 we have direct support for this permutation.
10554     if (Subtarget->hasAVX2())
10555       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10556                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10557
10558     // Otherwise, fall back.
10559     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10560                                                    DAG);
10561   }
10562
10563   // Use dedicated unpack instructions for masks that match their pattern.
10564   if (SDValue V =
10565           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10566     return V;
10567
10568   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10569                                                 Subtarget, DAG))
10570     return Blend;
10571
10572   // Check if the blend happens to exactly fit that of SHUFPD.
10573   if (SDValue Op =
10574       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10575     return Op;
10576
10577   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10578   // shuffle. However, if we have AVX2 and either inputs are already in place,
10579   // we will be able to shuffle even across lanes the other input in a single
10580   // instruction so skip this pattern.
10581   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10582                                  isShuffleMaskInputInPlace(1, Mask))))
10583     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10584             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10585       return Result;
10586
10587   // If we have AVX2 then we always want to lower with a blend because an v4 we
10588   // can fully permute the elements.
10589   if (Subtarget->hasAVX2())
10590     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10591                                                       Mask, DAG);
10592
10593   // Otherwise fall back on generic lowering.
10594   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10595 }
10596
10597 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10598 ///
10599 /// This routine is only called when we have AVX2 and thus a reasonable
10600 /// instruction set for v4i64 shuffling..
10601 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10602                                        const X86Subtarget *Subtarget,
10603                                        SelectionDAG &DAG) {
10604   SDLoc DL(Op);
10605   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10606   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10607   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10608   ArrayRef<int> Mask = SVOp->getMask();
10609   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10610   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10611
10612   SmallVector<int, 4> WidenedMask;
10613   if (canWidenShuffleElements(Mask, WidenedMask))
10614     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10615                                     DAG);
10616
10617   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10618                                                 Subtarget, DAG))
10619     return Blend;
10620
10621   // Check for being able to broadcast a single element.
10622   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10623                                                         Mask, Subtarget, DAG))
10624     return Broadcast;
10625
10626   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10627   // use lower latency instructions that will operate on both 128-bit lanes.
10628   SmallVector<int, 2> RepeatedMask;
10629   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10630     if (isSingleInputShuffleMask(Mask)) {
10631       int PSHUFDMask[] = {-1, -1, -1, -1};
10632       for (int i = 0; i < 2; ++i)
10633         if (RepeatedMask[i] >= 0) {
10634           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10635           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10636         }
10637       return DAG.getBitcast(
10638           MVT::v4i64,
10639           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10640                       DAG.getBitcast(MVT::v8i32, V1),
10641                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10642     }
10643   }
10644
10645   // AVX2 provides a direct instruction for permuting a single input across
10646   // lanes.
10647   if (isSingleInputShuffleMask(Mask))
10648     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10649                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10650
10651   // Try to use shift instructions.
10652   if (SDValue Shift =
10653           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10654     return Shift;
10655
10656   // Use dedicated unpack instructions for masks that match their pattern.
10657   if (SDValue V =
10658           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10659     return V;
10660
10661   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10662   // shuffle. However, if we have AVX2 and either inputs are already in place,
10663   // we will be able to shuffle even across lanes the other input in a single
10664   // instruction so skip this pattern.
10665   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10666                                  isShuffleMaskInputInPlace(1, Mask))))
10667     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10668             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10669       return Result;
10670
10671   // Otherwise fall back on generic blend lowering.
10672   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10673                                                     Mask, DAG);
10674 }
10675
10676 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10677 ///
10678 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10679 /// isn't available.
10680 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10681                                        const X86Subtarget *Subtarget,
10682                                        SelectionDAG &DAG) {
10683   SDLoc DL(Op);
10684   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10685   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10686   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10687   ArrayRef<int> Mask = SVOp->getMask();
10688   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10689
10690   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10691                                                 Subtarget, DAG))
10692     return Blend;
10693
10694   // Check for being able to broadcast a single element.
10695   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10696                                                         Mask, Subtarget, DAG))
10697     return Broadcast;
10698
10699   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10700   // options to efficiently lower the shuffle.
10701   SmallVector<int, 4> RepeatedMask;
10702   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10703     assert(RepeatedMask.size() == 4 &&
10704            "Repeated masks must be half the mask width!");
10705
10706     // Use even/odd duplicate instructions for masks that match their pattern.
10707     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10708       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10709     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10710       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10711
10712     if (isSingleInputShuffleMask(Mask))
10713       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10714                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10715
10716     // Use dedicated unpack instructions for masks that match their pattern.
10717     if (SDValue V =
10718             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10719       return V;
10720
10721     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10722     // have already handled any direct blends. We also need to squash the
10723     // repeated mask into a simulated v4f32 mask.
10724     for (int i = 0; i < 4; ++i)
10725       if (RepeatedMask[i] >= 8)
10726         RepeatedMask[i] -= 4;
10727     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10728   }
10729
10730   // If we have a single input shuffle with different shuffle patterns in the
10731   // two 128-bit lanes use the variable mask to VPERMILPS.
10732   if (isSingleInputShuffleMask(Mask)) {
10733     SDValue VPermMask[8];
10734     for (int i = 0; i < 8; ++i)
10735       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10736                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10737     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10738       return DAG.getNode(
10739           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10740           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10741
10742     if (Subtarget->hasAVX2())
10743       return DAG.getNode(
10744           X86ISD::VPERMV, DL, MVT::v8f32,
10745           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10746
10747     // Otherwise, fall back.
10748     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10749                                                    DAG);
10750   }
10751
10752   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10753   // shuffle.
10754   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10755           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10756     return Result;
10757
10758   // If we have AVX2 then we always want to lower with a blend because at v8 we
10759   // can fully permute the elements.
10760   if (Subtarget->hasAVX2())
10761     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10762                                                       Mask, DAG);
10763
10764   // Otherwise fall back on generic lowering.
10765   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10766 }
10767
10768 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10769 ///
10770 /// This routine is only called when we have AVX2 and thus a reasonable
10771 /// instruction set for v8i32 shuffling..
10772 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10773                                        const X86Subtarget *Subtarget,
10774                                        SelectionDAG &DAG) {
10775   SDLoc DL(Op);
10776   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10777   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10778   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10779   ArrayRef<int> Mask = SVOp->getMask();
10780   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10781   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10782
10783   // Whenever we can lower this as a zext, that instruction is strictly faster
10784   // than any alternative. It also allows us to fold memory operands into the
10785   // shuffle in many cases.
10786   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10787                                                          Mask, Subtarget, DAG))
10788     return ZExt;
10789
10790   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10791                                                 Subtarget, DAG))
10792     return Blend;
10793
10794   // Check for being able to broadcast a single element.
10795   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10796                                                         Mask, Subtarget, DAG))
10797     return Broadcast;
10798
10799   // If the shuffle mask is repeated in each 128-bit lane we can use more
10800   // efficient instructions that mirror the shuffles across the two 128-bit
10801   // lanes.
10802   SmallVector<int, 4> RepeatedMask;
10803   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10804     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10805     if (isSingleInputShuffleMask(Mask))
10806       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10807                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10808
10809     // Use dedicated unpack instructions for masks that match their pattern.
10810     if (SDValue V =
10811             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10812       return V;
10813   }
10814
10815   // Try to use shift instructions.
10816   if (SDValue Shift =
10817           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10818     return Shift;
10819
10820   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10821           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10822     return Rotate;
10823
10824   // If the shuffle patterns aren't repeated but it is a single input, directly
10825   // generate a cross-lane VPERMD instruction.
10826   if (isSingleInputShuffleMask(Mask)) {
10827     SDValue VPermMask[8];
10828     for (int i = 0; i < 8; ++i)
10829       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10830                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10831     return DAG.getNode(
10832         X86ISD::VPERMV, DL, MVT::v8i32,
10833         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10834   }
10835
10836   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10837   // shuffle.
10838   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10839           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10840     return Result;
10841
10842   // Otherwise fall back on generic blend lowering.
10843   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10844                                                     Mask, DAG);
10845 }
10846
10847 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10848 ///
10849 /// This routine is only called when we have AVX2 and thus a reasonable
10850 /// instruction set for v16i16 shuffling..
10851 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10852                                         const X86Subtarget *Subtarget,
10853                                         SelectionDAG &DAG) {
10854   SDLoc DL(Op);
10855   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10856   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10857   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10858   ArrayRef<int> Mask = SVOp->getMask();
10859   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10860   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10861
10862   // Whenever we can lower this as a zext, that instruction is strictly faster
10863   // than any alternative. It also allows us to fold memory operands into the
10864   // shuffle in many cases.
10865   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10866                                                          Mask, Subtarget, DAG))
10867     return ZExt;
10868
10869   // Check for being able to broadcast a single element.
10870   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10871                                                         Mask, Subtarget, DAG))
10872     return Broadcast;
10873
10874   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10875                                                 Subtarget, DAG))
10876     return Blend;
10877
10878   // Use dedicated unpack instructions for masks that match their pattern.
10879   if (SDValue V =
10880           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10881     return V;
10882
10883   // Try to use shift instructions.
10884   if (SDValue Shift =
10885           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10886     return Shift;
10887
10888   // Try to use byte rotation instructions.
10889   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10890           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10891     return Rotate;
10892
10893   if (isSingleInputShuffleMask(Mask)) {
10894     // There are no generalized cross-lane shuffle operations available on i16
10895     // element types.
10896     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10897       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10898                                                      Mask, DAG);
10899
10900     SmallVector<int, 8> RepeatedMask;
10901     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10902       // As this is a single-input shuffle, the repeated mask should be
10903       // a strictly valid v8i16 mask that we can pass through to the v8i16
10904       // lowering to handle even the v16 case.
10905       return lowerV8I16GeneralSingleInputVectorShuffle(
10906           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10907     }
10908
10909     SDValue PSHUFBMask[32];
10910     for (int i = 0; i < 16; ++i) {
10911       if (Mask[i] == -1) {
10912         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10913         continue;
10914       }
10915
10916       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10917       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10918       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10919       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10920     }
10921     return DAG.getBitcast(MVT::v16i16,
10922                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10923                                       DAG.getBitcast(MVT::v32i8, V1),
10924                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10925                                                   MVT::v32i8, PSHUFBMask)));
10926   }
10927
10928   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10929   // shuffle.
10930   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10931           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10932     return Result;
10933
10934   // Otherwise fall back on generic lowering.
10935   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10936 }
10937
10938 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10939 ///
10940 /// This routine is only called when we have AVX2 and thus a reasonable
10941 /// instruction set for v32i8 shuffling..
10942 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10943                                        const X86Subtarget *Subtarget,
10944                                        SelectionDAG &DAG) {
10945   SDLoc DL(Op);
10946   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10947   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10948   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10949   ArrayRef<int> Mask = SVOp->getMask();
10950   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10951   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10952
10953   // Whenever we can lower this as a zext, that instruction is strictly faster
10954   // than any alternative. It also allows us to fold memory operands into the
10955   // shuffle in many cases.
10956   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10957                                                          Mask, Subtarget, DAG))
10958     return ZExt;
10959
10960   // Check for being able to broadcast a single element.
10961   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10962                                                         Mask, Subtarget, DAG))
10963     return Broadcast;
10964
10965   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10966                                                 Subtarget, DAG))
10967     return Blend;
10968
10969   // Use dedicated unpack instructions for masks that match their pattern.
10970   if (SDValue V =
10971           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10972     return V;
10973
10974   // Try to use shift instructions.
10975   if (SDValue Shift =
10976           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10977     return Shift;
10978
10979   // Try to use byte rotation instructions.
10980   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10981           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10982     return Rotate;
10983
10984   if (isSingleInputShuffleMask(Mask)) {
10985     // There are no generalized cross-lane shuffle operations available on i8
10986     // element types.
10987     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10988       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10989                                                      Mask, DAG);
10990
10991     SDValue PSHUFBMask[32];
10992     for (int i = 0; i < 32; ++i)
10993       PSHUFBMask[i] =
10994           Mask[i] < 0
10995               ? DAG.getUNDEF(MVT::i8)
10996               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10997                                 MVT::i8);
10998
10999     return DAG.getNode(
11000         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
11001         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
11002   }
11003
11004   // Try to simplify this by merging 128-bit lanes to enable a lane-based
11005   // shuffle.
11006   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11007           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11008     return Result;
11009
11010   // Otherwise fall back on generic lowering.
11011   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11012 }
11013
11014 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11015 ///
11016 /// This routine either breaks down the specific type of a 256-bit x86 vector
11017 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11018 /// together based on the available instructions.
11019 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11020                                         MVT VT, const X86Subtarget *Subtarget,
11021                                         SelectionDAG &DAG) {
11022   SDLoc DL(Op);
11023   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11024   ArrayRef<int> Mask = SVOp->getMask();
11025
11026   // If we have a single input to the zero element, insert that into V1 if we
11027   // can do so cheaply.
11028   int NumElts = VT.getVectorNumElements();
11029   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
11030     return M >= NumElts;
11031   });
11032
11033   if (NumV2Elements == 1 && Mask[0] >= NumElts)
11034     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
11035                               DL, VT, V1, V2, Mask, Subtarget, DAG))
11036       return Insertion;
11037
11038   // Handle special cases where the lower or upper half is UNDEF.
11039   if (SDValue V =
11040           lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
11041     return V;
11042
11043   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
11044   // can check for those subtargets here and avoid much of the subtarget
11045   // querying in the per-vector-type lowering routines. With AVX1 we have
11046   // essentially *zero* ability to manipulate a 256-bit vector with integer
11047   // types. Since we'll use floating point types there eventually, just
11048   // immediately cast everything to a float and operate entirely in that domain.
11049   if (VT.isInteger() && !Subtarget->hasAVX2()) {
11050     int ElementBits = VT.getScalarSizeInBits();
11051     if (ElementBits < 32)
11052       // No floating point type available, decompose into 128-bit vectors.
11053       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11054
11055     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11056                                 VT.getVectorNumElements());
11057     V1 = DAG.getBitcast(FpVT, V1);
11058     V2 = DAG.getBitcast(FpVT, V2);
11059     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11060   }
11061
11062   switch (VT.SimpleTy) {
11063   case MVT::v4f64:
11064     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11065   case MVT::v4i64:
11066     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11067   case MVT::v8f32:
11068     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11069   case MVT::v8i32:
11070     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11071   case MVT::v16i16:
11072     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11073   case MVT::v32i8:
11074     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11075
11076   default:
11077     llvm_unreachable("Not a valid 256-bit x86 vector type!");
11078   }
11079 }
11080
11081 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
11082 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
11083                                         ArrayRef<int> Mask,
11084                                         SDValue V1, SDValue V2,
11085                                         SelectionDAG &DAG) {
11086   assert(VT.getScalarSizeInBits() == 64 &&
11087          "Unexpected element type size for 128bit shuffle.");
11088
11089   // To handle 256 bit vector requires VLX and most probably
11090   // function lowerV2X128VectorShuffle() is better solution.
11091   assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
11092
11093   SmallVector<int, 4> WidenedMask;
11094   if (!canWidenShuffleElements(Mask, WidenedMask))
11095     return SDValue();
11096
11097   // Form a 128-bit permutation.
11098   // Convert the 64-bit shuffle mask selection values into 128-bit selection
11099   // bits defined by a vshuf64x2 instruction's immediate control byte.
11100   unsigned PermMask = 0, Imm = 0;
11101   unsigned ControlBitsNum = WidenedMask.size() / 2;
11102
11103   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11104     if (WidenedMask[i] == SM_SentinelZero)
11105       return SDValue();
11106
11107     // Use first element in place of undef mask.
11108     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
11109     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
11110   }
11111
11112   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
11113                      DAG.getConstant(PermMask, DL, MVT::i8));
11114 }
11115
11116 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
11117                                            ArrayRef<int> Mask, SDValue V1,
11118                                            SDValue V2, SelectionDAG &DAG) {
11119
11120   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11121
11122   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11123   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11124
11125   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11126   if (isSingleInputShuffleMask(Mask))
11127     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11128
11129   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11130 }
11131
11132 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11133 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11134                                        const X86Subtarget *Subtarget,
11135                                        SelectionDAG &DAG) {
11136   SDLoc DL(Op);
11137   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11138   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11139   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11140   ArrayRef<int> Mask = SVOp->getMask();
11141   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11142
11143   if (SDValue Shuf128 =
11144           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11145     return Shuf128;
11146
11147   if (SDValue Unpck =
11148           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11149     return Unpck;
11150
11151   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11152 }
11153
11154 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11155 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11156                                         const X86Subtarget *Subtarget,
11157                                         SelectionDAG &DAG) {
11158   SDLoc DL(Op);
11159   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11160   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11161   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11162   ArrayRef<int> Mask = SVOp->getMask();
11163   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11164
11165   if (SDValue Unpck =
11166           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11167     return Unpck;
11168
11169   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11170 }
11171
11172 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11173 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11174                                        const X86Subtarget *Subtarget,
11175                                        SelectionDAG &DAG) {
11176   SDLoc DL(Op);
11177   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11178   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11179   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11180   ArrayRef<int> Mask = SVOp->getMask();
11181   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11182
11183   if (SDValue Shuf128 =
11184           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11185     return Shuf128;
11186
11187   if (SDValue Unpck =
11188           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11189     return Unpck;
11190
11191   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11192 }
11193
11194 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11195 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11196                                         const X86Subtarget *Subtarget,
11197                                         SelectionDAG &DAG) {
11198   SDLoc DL(Op);
11199   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11200   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11201   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11202   ArrayRef<int> Mask = SVOp->getMask();
11203   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11204
11205   if (SDValue Unpck =
11206           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11207     return Unpck;
11208
11209   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11210 }
11211
11212 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11213 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11214                                         const X86Subtarget *Subtarget,
11215                                         SelectionDAG &DAG) {
11216   SDLoc DL(Op);
11217   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11218   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11219   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11220   ArrayRef<int> Mask = SVOp->getMask();
11221   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11222   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11223
11224   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11225 }
11226
11227 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11228 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11229                                        const X86Subtarget *Subtarget,
11230                                        SelectionDAG &DAG) {
11231   SDLoc DL(Op);
11232   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11233   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11234   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11235   ArrayRef<int> Mask = SVOp->getMask();
11236   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11237   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11238
11239   // FIXME: Implement direct support for this type!
11240   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11241 }
11242
11243 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11244 ///
11245 /// This routine either breaks down the specific type of a 512-bit x86 vector
11246 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11247 /// together based on the available instructions.
11248 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11249                                         MVT VT, const X86Subtarget *Subtarget,
11250                                         SelectionDAG &DAG) {
11251   SDLoc DL(Op);
11252   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11253   ArrayRef<int> Mask = SVOp->getMask();
11254   assert(Subtarget->hasAVX512() &&
11255          "Cannot lower 512-bit vectors w/ basic ISA!");
11256
11257   // Check for being able to broadcast a single element.
11258   if (SDValue Broadcast =
11259           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11260     return Broadcast;
11261
11262   // Dispatch to each element type for lowering. If we don't have supprot for
11263   // specific element type shuffles at 512 bits, immediately split them and
11264   // lower them. Each lowering routine of a given type is allowed to assume that
11265   // the requisite ISA extensions for that element type are available.
11266   switch (VT.SimpleTy) {
11267   case MVT::v8f64:
11268     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11269   case MVT::v16f32:
11270     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11271   case MVT::v8i64:
11272     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11273   case MVT::v16i32:
11274     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11275   case MVT::v32i16:
11276     if (Subtarget->hasBWI())
11277       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11278     break;
11279   case MVT::v64i8:
11280     if (Subtarget->hasBWI())
11281       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11282     break;
11283
11284   default:
11285     llvm_unreachable("Not a valid 512-bit x86 vector type!");
11286   }
11287
11288   // Otherwise fall back on splitting.
11289   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11290 }
11291
11292 // Lower vXi1 vector shuffles.
11293 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11294 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11295 // vector, shuffle and then truncate it back.
11296 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11297                                       MVT VT, const X86Subtarget *Subtarget,
11298                                       SelectionDAG &DAG) {
11299   SDLoc DL(Op);
11300   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11301   ArrayRef<int> Mask = SVOp->getMask();
11302   assert(Subtarget->hasAVX512() &&
11303          "Cannot lower 512-bit vectors w/o basic ISA!");
11304   MVT ExtVT;
11305   switch (VT.SimpleTy) {
11306   default:
11307     llvm_unreachable("Expected a vector of i1 elements");
11308   case MVT::v2i1:
11309     ExtVT = MVT::v2i64;
11310     break;
11311   case MVT::v4i1:
11312     ExtVT = MVT::v4i32;
11313     break;
11314   case MVT::v8i1:
11315     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11316     break;
11317   case MVT::v16i1:
11318     ExtVT = MVT::v16i32;
11319     break;
11320   case MVT::v32i1:
11321     ExtVT = MVT::v32i16;
11322     break;
11323   case MVT::v64i1:
11324     ExtVT = MVT::v64i8;
11325     break;
11326   }
11327
11328   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11329     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11330   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11331     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11332   else
11333     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11334
11335   if (V2.isUndef())
11336     V2 = DAG.getUNDEF(ExtVT);
11337   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11338     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11339   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11340     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11341   else
11342     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11343   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11344                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11345 }
11346 /// \brief Top-level lowering for x86 vector shuffles.
11347 ///
11348 /// This handles decomposition, canonicalization, and lowering of all x86
11349 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11350 /// above in helper routines. The canonicalization attempts to widen shuffles
11351 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11352 /// s.t. only one of the two inputs needs to be tested, etc.
11353 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11354                                   SelectionDAG &DAG) {
11355   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11356   ArrayRef<int> Mask = SVOp->getMask();
11357   SDValue V1 = Op.getOperand(0);
11358   SDValue V2 = Op.getOperand(1);
11359   MVT VT = Op.getSimpleValueType();
11360   int NumElements = VT.getVectorNumElements();
11361   SDLoc dl(Op);
11362   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11363
11364   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11365          "Can't lower MMX shuffles");
11366
11367   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11368   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11369   if (V1IsUndef && V2IsUndef)
11370     return DAG.getUNDEF(VT);
11371
11372   // When we create a shuffle node we put the UNDEF node to second operand,
11373   // but in some cases the first operand may be transformed to UNDEF.
11374   // In this case we should just commute the node.
11375   if (V1IsUndef)
11376     return DAG.getCommutedVectorShuffle(*SVOp);
11377
11378   // Check for non-undef masks pointing at an undef vector and make the masks
11379   // undef as well. This makes it easier to match the shuffle based solely on
11380   // the mask.
11381   if (V2IsUndef)
11382     for (int M : Mask)
11383       if (M >= NumElements) {
11384         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11385         for (int &M : NewMask)
11386           if (M >= NumElements)
11387             M = -1;
11388         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11389       }
11390
11391   // We actually see shuffles that are entirely re-arrangements of a set of
11392   // zero inputs. This mostly happens while decomposing complex shuffles into
11393   // simple ones. Directly lower these as a buildvector of zeros.
11394   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11395   if (Zeroable.all())
11396     return getZeroVector(VT, Subtarget, DAG, dl);
11397
11398   // Try to collapse shuffles into using a vector type with fewer elements but
11399   // wider element types. We cap this to not form integers or floating point
11400   // elements wider than 64 bits, but it might be interesting to form i128
11401   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11402   SmallVector<int, 16> WidenedMask;
11403   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11404       canWidenShuffleElements(Mask, WidenedMask)) {
11405     MVT NewEltVT = VT.isFloatingPoint()
11406                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11407                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11408     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11409     // Make sure that the new vector type is legal. For example, v2f64 isn't
11410     // legal on SSE1.
11411     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11412       V1 = DAG.getBitcast(NewVT, V1);
11413       V2 = DAG.getBitcast(NewVT, V2);
11414       return DAG.getBitcast(
11415           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11416     }
11417   }
11418
11419   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11420   for (int M : SVOp->getMask())
11421     if (M < 0)
11422       ++NumUndefElements;
11423     else if (M < NumElements)
11424       ++NumV1Elements;
11425     else
11426       ++NumV2Elements;
11427
11428   // Commute the shuffle as needed such that more elements come from V1 than
11429   // V2. This allows us to match the shuffle pattern strictly on how many
11430   // elements come from V1 without handling the symmetric cases.
11431   if (NumV2Elements > NumV1Elements)
11432     return DAG.getCommutedVectorShuffle(*SVOp);
11433
11434   // When the number of V1 and V2 elements are the same, try to minimize the
11435   // number of uses of V2 in the low half of the vector. When that is tied,
11436   // ensure that the sum of indices for V1 is equal to or lower than the sum
11437   // indices for V2. When those are equal, try to ensure that the number of odd
11438   // indices for V1 is lower than the number of odd indices for V2.
11439   if (NumV1Elements == NumV2Elements) {
11440     int LowV1Elements = 0, LowV2Elements = 0;
11441     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11442       if (M >= NumElements)
11443         ++LowV2Elements;
11444       else if (M >= 0)
11445         ++LowV1Elements;
11446     if (LowV2Elements > LowV1Elements) {
11447       return DAG.getCommutedVectorShuffle(*SVOp);
11448     } else if (LowV2Elements == LowV1Elements) {
11449       int SumV1Indices = 0, SumV2Indices = 0;
11450       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11451         if (SVOp->getMask()[i] >= NumElements)
11452           SumV2Indices += i;
11453         else if (SVOp->getMask()[i] >= 0)
11454           SumV1Indices += i;
11455       if (SumV2Indices < SumV1Indices) {
11456         return DAG.getCommutedVectorShuffle(*SVOp);
11457       } else if (SumV2Indices == SumV1Indices) {
11458         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11459         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11460           if (SVOp->getMask()[i] >= NumElements)
11461             NumV2OddIndices += i % 2;
11462           else if (SVOp->getMask()[i] >= 0)
11463             NumV1OddIndices += i % 2;
11464         if (NumV2OddIndices < NumV1OddIndices)
11465           return DAG.getCommutedVectorShuffle(*SVOp);
11466       }
11467     }
11468   }
11469
11470   // For each vector width, delegate to a specialized lowering routine.
11471   if (VT.is128BitVector())
11472     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11473
11474   if (VT.is256BitVector())
11475     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11476
11477   if (VT.is512BitVector())
11478     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11479
11480   if (Is1BitVector)
11481     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11482   llvm_unreachable("Unimplemented!");
11483 }
11484
11485 // This function assumes its argument is a BUILD_VECTOR of constants or
11486 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11487 // true.
11488 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11489                                     unsigned &MaskValue) {
11490   MaskValue = 0;
11491   unsigned NumElems = BuildVector->getNumOperands();
11492
11493   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11494   // We don't handle the >2 lanes case right now.
11495   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11496   if (NumLanes > 2)
11497     return false;
11498
11499   unsigned NumElemsInLane = NumElems / NumLanes;
11500
11501   // Blend for v16i16 should be symmetric for the both lanes.
11502   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11503     SDValue EltCond = BuildVector->getOperand(i);
11504     SDValue SndLaneEltCond =
11505         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11506
11507     int Lane1Cond = -1, Lane2Cond = -1;
11508     if (isa<ConstantSDNode>(EltCond))
11509       Lane1Cond = !isNullConstant(EltCond);
11510     if (isa<ConstantSDNode>(SndLaneEltCond))
11511       Lane2Cond = !isNullConstant(SndLaneEltCond);
11512
11513     unsigned LaneMask = 0;
11514     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11515       // Lane1Cond != 0, means we want the first argument.
11516       // Lane1Cond == 0, means we want the second argument.
11517       // The encoding of this argument is 0 for the first argument, 1
11518       // for the second. Therefore, invert the condition.
11519       LaneMask = !Lane1Cond << i;
11520     else if (Lane1Cond < 0)
11521       LaneMask = !Lane2Cond << i;
11522     else
11523       return false;
11524
11525     MaskValue |= LaneMask;
11526     if (NumLanes == 2)
11527       MaskValue |= LaneMask << NumElemsInLane;
11528   }
11529   return true;
11530 }
11531
11532 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11533 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11534                                            const X86Subtarget *Subtarget,
11535                                            SelectionDAG &DAG) {
11536   SDValue Cond = Op.getOperand(0);
11537   SDValue LHS = Op.getOperand(1);
11538   SDValue RHS = Op.getOperand(2);
11539   SDLoc dl(Op);
11540   MVT VT = Op.getSimpleValueType();
11541
11542   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11543     return SDValue();
11544   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11545
11546   // Only non-legal VSELECTs reach this lowering, convert those into generic
11547   // shuffles and re-use the shuffle lowering path for blends.
11548   SmallVector<int, 32> Mask;
11549   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11550     SDValue CondElt = CondBV->getOperand(i);
11551     Mask.push_back(
11552         isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11553                                      : -1);
11554   }
11555   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11556 }
11557
11558 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11559   // A vselect where all conditions and data are constants can be optimized into
11560   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11561   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11562       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11563       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11564     return SDValue();
11565
11566   // Try to lower this to a blend-style vector shuffle. This can handle all
11567   // constant condition cases.
11568   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11569     return BlendOp;
11570
11571   // Variable blends are only legal from SSE4.1 onward.
11572   if (!Subtarget->hasSSE41())
11573     return SDValue();
11574
11575   // Only some types will be legal on some subtargets. If we can emit a legal
11576   // VSELECT-matching blend, return Op, and but if we need to expand, return
11577   // a null value.
11578   switch (Op.getSimpleValueType().SimpleTy) {
11579   default:
11580     // Most of the vector types have blends past SSE4.1.
11581     return Op;
11582
11583   case MVT::v32i8:
11584     // The byte blends for AVX vectors were introduced only in AVX2.
11585     if (Subtarget->hasAVX2())
11586       return Op;
11587
11588     return SDValue();
11589
11590   case MVT::v8i16:
11591   case MVT::v16i16:
11592     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11593     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11594       return Op;
11595
11596     // FIXME: We should custom lower this by fixing the condition and using i8
11597     // blends.
11598     return SDValue();
11599   }
11600 }
11601
11602 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11603   MVT VT = Op.getSimpleValueType();
11604   SDLoc dl(Op);
11605
11606   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11607     return SDValue();
11608
11609   if (VT.getSizeInBits() == 8) {
11610     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11611                                   Op.getOperand(0), Op.getOperand(1));
11612     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11613                                   DAG.getValueType(VT));
11614     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11615   }
11616
11617   if (VT.getSizeInBits() == 16) {
11618     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11619     if (isNullConstant(Op.getOperand(1)))
11620       return DAG.getNode(
11621           ISD::TRUNCATE, dl, MVT::i16,
11622           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11623                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11624                       Op.getOperand(1)));
11625     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11626                                   Op.getOperand(0), Op.getOperand(1));
11627     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11628                                   DAG.getValueType(VT));
11629     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11630   }
11631
11632   if (VT == MVT::f32) {
11633     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11634     // the result back to FR32 register. It's only worth matching if the
11635     // result has a single use which is a store or a bitcast to i32.  And in
11636     // the case of a store, it's not worth it if the index is a constant 0,
11637     // because a MOVSSmr can be used instead, which is smaller and faster.
11638     if (!Op.hasOneUse())
11639       return SDValue();
11640     SDNode *User = *Op.getNode()->use_begin();
11641     if ((User->getOpcode() != ISD::STORE ||
11642          isNullConstant(Op.getOperand(1))) &&
11643         (User->getOpcode() != ISD::BITCAST ||
11644          User->getValueType(0) != MVT::i32))
11645       return SDValue();
11646     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11647                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11648                                   Op.getOperand(1));
11649     return DAG.getBitcast(MVT::f32, Extract);
11650   }
11651
11652   if (VT == MVT::i32 || VT == MVT::i64) {
11653     // ExtractPS/pextrq works with constant index.
11654     if (isa<ConstantSDNode>(Op.getOperand(1)))
11655       return Op;
11656   }
11657   return SDValue();
11658 }
11659
11660 /// Extract one bit from mask vector, like v16i1 or v8i1.
11661 /// AVX-512 feature.
11662 SDValue
11663 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11664   SDValue Vec = Op.getOperand(0);
11665   SDLoc dl(Vec);
11666   MVT VecVT = Vec.getSimpleValueType();
11667   SDValue Idx = Op.getOperand(1);
11668   MVT EltVT = Op.getSimpleValueType();
11669
11670   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11671   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11672          "Unexpected vector type in ExtractBitFromMaskVector");
11673
11674   // variable index can't be handled in mask registers,
11675   // extend vector to VR512
11676   if (!isa<ConstantSDNode>(Idx)) {
11677     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11678     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11679     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11680                               ExtVT.getVectorElementType(), Ext, Idx);
11681     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11682   }
11683
11684   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11685   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11686   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11687     rc = getRegClassFor(MVT::v16i1);
11688   unsigned MaxSift = rc->getSize()*8 - 1;
11689   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11690                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11691   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11692                     DAG.getConstant(MaxSift, dl, MVT::i8));
11693   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11694                        DAG.getIntPtrConstant(0, dl));
11695 }
11696
11697 SDValue
11698 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11699                                            SelectionDAG &DAG) const {
11700   SDLoc dl(Op);
11701   SDValue Vec = Op.getOperand(0);
11702   MVT VecVT = Vec.getSimpleValueType();
11703   SDValue Idx = Op.getOperand(1);
11704
11705   if (Op.getSimpleValueType() == MVT::i1)
11706     return ExtractBitFromMaskVector(Op, DAG);
11707
11708   if (!isa<ConstantSDNode>(Idx)) {
11709     if (VecVT.is512BitVector() ||
11710         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11711          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11712
11713       MVT MaskEltVT =
11714         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11715       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11716                                     MaskEltVT.getSizeInBits());
11717
11718       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11719       auto PtrVT = getPointerTy(DAG.getDataLayout());
11720       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11721                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11722                                  DAG.getConstant(0, dl, PtrVT));
11723       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11724       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11725                          DAG.getConstant(0, dl, PtrVT));
11726     }
11727     return SDValue();
11728   }
11729
11730   // If this is a 256-bit vector result, first extract the 128-bit vector and
11731   // then extract the element from the 128-bit vector.
11732   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11733
11734     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11735     // Get the 128-bit vector.
11736     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11737     MVT EltVT = VecVT.getVectorElementType();
11738
11739     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11740     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11741
11742     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11743     // this can be done with a mask.
11744     IdxVal &= ElemsPerChunk - 1;
11745     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11746                        DAG.getConstant(IdxVal, dl, MVT::i32));
11747   }
11748
11749   assert(VecVT.is128BitVector() && "Unexpected vector length");
11750
11751   if (Subtarget->hasSSE41())
11752     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11753       return Res;
11754
11755   MVT VT = Op.getSimpleValueType();
11756   // TODO: handle v16i8.
11757   if (VT.getSizeInBits() == 16) {
11758     SDValue Vec = Op.getOperand(0);
11759     if (isNullConstant(Op.getOperand(1)))
11760       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11761                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11762                                      DAG.getBitcast(MVT::v4i32, Vec),
11763                                      Op.getOperand(1)));
11764     // Transform it so it match pextrw which produces a 32-bit result.
11765     MVT EltVT = MVT::i32;
11766     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11767                                   Op.getOperand(0), Op.getOperand(1));
11768     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11769                                   DAG.getValueType(VT));
11770     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11771   }
11772
11773   if (VT.getSizeInBits() == 32) {
11774     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11775     if (Idx == 0)
11776       return Op;
11777
11778     // SHUFPS the element to the lowest double word, then movss.
11779     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11780     MVT VVT = Op.getOperand(0).getSimpleValueType();
11781     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11782                                        DAG.getUNDEF(VVT), Mask);
11783     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11784                        DAG.getIntPtrConstant(0, dl));
11785   }
11786
11787   if (VT.getSizeInBits() == 64) {
11788     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11789     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11790     //        to match extract_elt for f64.
11791     if (isNullConstant(Op.getOperand(1)))
11792       return Op;
11793
11794     // UNPCKHPD the element to the lowest double word, then movsd.
11795     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11796     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11797     int Mask[2] = { 1, -1 };
11798     MVT VVT = Op.getOperand(0).getSimpleValueType();
11799     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11800                                        DAG.getUNDEF(VVT), Mask);
11801     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11802                        DAG.getIntPtrConstant(0, dl));
11803   }
11804
11805   return SDValue();
11806 }
11807
11808 /// Insert one bit to mask vector, like v16i1 or v8i1.
11809 /// AVX-512 feature.
11810 SDValue
11811 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11812   SDLoc dl(Op);
11813   SDValue Vec = Op.getOperand(0);
11814   SDValue Elt = Op.getOperand(1);
11815   SDValue Idx = Op.getOperand(2);
11816   MVT VecVT = Vec.getSimpleValueType();
11817
11818   if (!isa<ConstantSDNode>(Idx)) {
11819     // Non constant index. Extend source and destination,
11820     // insert element and then truncate the result.
11821     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11822     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11823     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11824       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11825       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11826     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11827   }
11828
11829   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11830   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11831   if (IdxVal)
11832     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11833                            DAG.getConstant(IdxVal, dl, MVT::i8));
11834   if (Vec.getOpcode() == ISD::UNDEF)
11835     return EltInVec;
11836   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11837 }
11838
11839 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11840                                                   SelectionDAG &DAG) const {
11841   MVT VT = Op.getSimpleValueType();
11842   MVT EltVT = VT.getVectorElementType();
11843
11844   if (EltVT == MVT::i1)
11845     return InsertBitToMaskVector(Op, DAG);
11846
11847   SDLoc dl(Op);
11848   SDValue N0 = Op.getOperand(0);
11849   SDValue N1 = Op.getOperand(1);
11850   SDValue N2 = Op.getOperand(2);
11851   if (!isa<ConstantSDNode>(N2))
11852     return SDValue();
11853   auto *N2C = cast<ConstantSDNode>(N2);
11854   unsigned IdxVal = N2C->getZExtValue();
11855
11856   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11857   // into that, and then insert the subvector back into the result.
11858   if (VT.is256BitVector() || VT.is512BitVector()) {
11859     // With a 256-bit vector, we can insert into the zero element efficiently
11860     // using a blend if we have AVX or AVX2 and the right data type.
11861     if (VT.is256BitVector() && IdxVal == 0) {
11862       // TODO: It is worthwhile to cast integer to floating point and back
11863       // and incur a domain crossing penalty if that's what we'll end up
11864       // doing anyway after extracting to a 128-bit vector.
11865       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11866           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11867         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11868         N2 = DAG.getIntPtrConstant(1, dl);
11869         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11870       }
11871     }
11872
11873     // Get the desired 128-bit vector chunk.
11874     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11875
11876     // Insert the element into the desired chunk.
11877     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11878     assert(isPowerOf2_32(NumEltsIn128));
11879     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11880     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11881
11882     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11883                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11884
11885     // Insert the changed part back into the bigger vector
11886     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11887   }
11888   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11889
11890   if (Subtarget->hasSSE41()) {
11891     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11892       unsigned Opc;
11893       if (VT == MVT::v8i16) {
11894         Opc = X86ISD::PINSRW;
11895       } else {
11896         assert(VT == MVT::v16i8);
11897         Opc = X86ISD::PINSRB;
11898       }
11899
11900       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11901       // argument.
11902       if (N1.getValueType() != MVT::i32)
11903         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11904       if (N2.getValueType() != MVT::i32)
11905         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11906       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11907     }
11908
11909     if (EltVT == MVT::f32) {
11910       // Bits [7:6] of the constant are the source select. This will always be
11911       //   zero here. The DAG Combiner may combine an extract_elt index into
11912       //   these bits. For example (insert (extract, 3), 2) could be matched by
11913       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11914       // Bits [5:4] of the constant are the destination select. This is the
11915       //   value of the incoming immediate.
11916       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11917       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11918
11919       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11920       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11921         // If this is an insertion of 32-bits into the low 32-bits of
11922         // a vector, we prefer to generate a blend with immediate rather
11923         // than an insertps. Blends are simpler operations in hardware and so
11924         // will always have equal or better performance than insertps.
11925         // But if optimizing for size and there's a load folding opportunity,
11926         // generate insertps because blendps does not have a 32-bit memory
11927         // operand form.
11928         N2 = DAG.getIntPtrConstant(1, dl);
11929         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11930         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11931       }
11932       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11933       // Create this as a scalar to vector..
11934       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11935       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11936     }
11937
11938     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11939       // PINSR* works with constant index.
11940       return Op;
11941     }
11942   }
11943
11944   if (EltVT == MVT::i8)
11945     return SDValue();
11946
11947   if (EltVT.getSizeInBits() == 16) {
11948     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11949     // as its second argument.
11950     if (N1.getValueType() != MVT::i32)
11951       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11952     if (N2.getValueType() != MVT::i32)
11953       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11954     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11955   }
11956   return SDValue();
11957 }
11958
11959 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11960   SDLoc dl(Op);
11961   MVT OpVT = Op.getSimpleValueType();
11962
11963   // If this is a 256-bit vector result, first insert into a 128-bit
11964   // vector and then insert into the 256-bit vector.
11965   if (!OpVT.is128BitVector()) {
11966     // Insert into a 128-bit vector.
11967     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11968     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11969                                  OpVT.getVectorNumElements() / SizeFactor);
11970
11971     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11972
11973     // Insert the 128-bit vector.
11974     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11975   }
11976
11977   if (OpVT == MVT::v1i64 &&
11978       Op.getOperand(0).getValueType() == MVT::i64)
11979     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11980
11981   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11982   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11983   return DAG.getBitcast(
11984       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11985 }
11986
11987 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11988 // a simple subregister reference or explicit instructions to grab
11989 // upper bits of a vector.
11990 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11991                                       SelectionDAG &DAG) {
11992   SDLoc dl(Op);
11993   SDValue In =  Op.getOperand(0);
11994   SDValue Idx = Op.getOperand(1);
11995   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11996   MVT ResVT   = Op.getSimpleValueType();
11997   MVT InVT    = In.getSimpleValueType();
11998
11999   if (Subtarget->hasFp256()) {
12000     if (ResVT.is128BitVector() &&
12001         (InVT.is256BitVector() || InVT.is512BitVector()) &&
12002         isa<ConstantSDNode>(Idx)) {
12003       return Extract128BitVector(In, IdxVal, DAG, dl);
12004     }
12005     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12006         isa<ConstantSDNode>(Idx)) {
12007       return Extract256BitVector(In, IdxVal, DAG, dl);
12008     }
12009   }
12010   return SDValue();
12011 }
12012
12013 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
12014 // simple superregister reference or explicit instructions to insert
12015 // the upper bits of a vector.
12016 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12017                                      SelectionDAG &DAG) {
12018   if (!Subtarget->hasAVX())
12019     return SDValue();
12020
12021   SDLoc dl(Op);
12022   SDValue Vec = Op.getOperand(0);
12023   SDValue SubVec = Op.getOperand(1);
12024   SDValue Idx = Op.getOperand(2);
12025
12026   if (!isa<ConstantSDNode>(Idx))
12027     return SDValue();
12028
12029   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12030   MVT OpVT = Op.getSimpleValueType();
12031   MVT SubVecVT = SubVec.getSimpleValueType();
12032
12033   // Fold two 16-byte subvector loads into one 32-byte load:
12034   // (insert_subvector (insert_subvector undef, (load addr), 0),
12035   //                   (load addr + 16), Elts/2)
12036   // --> load32 addr
12037   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
12038       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
12039       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
12040     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
12041     if (Idx2 && Idx2->getZExtValue() == 0) {
12042       SDValue SubVec2 = Vec.getOperand(1);
12043       // If needed, look through a bitcast to get to the load.
12044       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
12045         SubVec2 = SubVec2.getOperand(0);
12046
12047       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
12048         bool Fast;
12049         unsigned Alignment = FirstLd->getAlignment();
12050         unsigned AS = FirstLd->getAddressSpace();
12051         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
12052         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
12053                                     OpVT, AS, Alignment, &Fast) && Fast) {
12054           SDValue Ops[] = { SubVec2, SubVec };
12055           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
12056             return Ld;
12057         }
12058       }
12059     }
12060   }
12061
12062   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
12063       SubVecVT.is128BitVector())
12064     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12065
12066   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
12067     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12068
12069   if (OpVT.getVectorElementType() == MVT::i1)
12070     return Insert1BitVector(Op, DAG);
12071
12072   return SDValue();
12073 }
12074
12075 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12076 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12077 // one of the above mentioned nodes. It has to be wrapped because otherwise
12078 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12079 // be used to form addressing mode. These wrapped nodes will be selected
12080 // into MOV32ri.
12081 SDValue
12082 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12083   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12084
12085   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12086   // global base reg.
12087   unsigned char OpFlag = 0;
12088   unsigned WrapperKind = X86ISD::Wrapper;
12089   CodeModel::Model M = DAG.getTarget().getCodeModel();
12090
12091   if (Subtarget->isPICStyleRIPRel() &&
12092       (M == CodeModel::Small || M == CodeModel::Kernel))
12093     WrapperKind = X86ISD::WrapperRIP;
12094   else if (Subtarget->isPICStyleGOT())
12095     OpFlag = X86II::MO_GOTOFF;
12096   else if (Subtarget->isPICStyleStubPIC())
12097     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12098
12099   auto PtrVT = getPointerTy(DAG.getDataLayout());
12100   SDValue Result = DAG.getTargetConstantPool(
12101       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
12102   SDLoc DL(CP);
12103   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12104   // With PIC, the address is actually $g + Offset.
12105   if (OpFlag) {
12106     Result =
12107         DAG.getNode(ISD::ADD, DL, PtrVT,
12108                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12109   }
12110
12111   return Result;
12112 }
12113
12114 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12115   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12116
12117   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12118   // global base reg.
12119   unsigned char OpFlag = 0;
12120   unsigned WrapperKind = X86ISD::Wrapper;
12121   CodeModel::Model M = DAG.getTarget().getCodeModel();
12122
12123   if (Subtarget->isPICStyleRIPRel() &&
12124       (M == CodeModel::Small || M == CodeModel::Kernel))
12125     WrapperKind = X86ISD::WrapperRIP;
12126   else if (Subtarget->isPICStyleGOT())
12127     OpFlag = X86II::MO_GOTOFF;
12128   else if (Subtarget->isPICStyleStubPIC())
12129     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12130
12131   auto PtrVT = getPointerTy(DAG.getDataLayout());
12132   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12133   SDLoc DL(JT);
12134   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12135
12136   // With PIC, the address is actually $g + Offset.
12137   if (OpFlag)
12138     Result =
12139         DAG.getNode(ISD::ADD, DL, PtrVT,
12140                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12141
12142   return Result;
12143 }
12144
12145 SDValue
12146 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12147   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12148
12149   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12150   // global base reg.
12151   unsigned char OpFlag = 0;
12152   unsigned WrapperKind = X86ISD::Wrapper;
12153   CodeModel::Model M = DAG.getTarget().getCodeModel();
12154
12155   if (Subtarget->isPICStyleRIPRel() &&
12156       (M == CodeModel::Small || M == CodeModel::Kernel)) {
12157     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12158       OpFlag = X86II::MO_GOTPCREL;
12159     WrapperKind = X86ISD::WrapperRIP;
12160   } else if (Subtarget->isPICStyleGOT()) {
12161     OpFlag = X86II::MO_GOT;
12162   } else if (Subtarget->isPICStyleStubPIC()) {
12163     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12164   } else if (Subtarget->isPICStyleStubNoDynamic()) {
12165     OpFlag = X86II::MO_DARWIN_NONLAZY;
12166   }
12167
12168   auto PtrVT = getPointerTy(DAG.getDataLayout());
12169   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12170
12171   SDLoc DL(Op);
12172   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12173
12174   // With PIC, the address is actually $g + Offset.
12175   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12176       !Subtarget->is64Bit()) {
12177     Result =
12178         DAG.getNode(ISD::ADD, DL, PtrVT,
12179                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12180   }
12181
12182   // For symbols that require a load from a stub to get the address, emit the
12183   // load.
12184   if (isGlobalStubReference(OpFlag))
12185     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12186                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12187                          false, false, false, 0);
12188
12189   return Result;
12190 }
12191
12192 SDValue
12193 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12194   // Create the TargetBlockAddressAddress node.
12195   unsigned char OpFlags =
12196     Subtarget->ClassifyBlockAddressReference();
12197   CodeModel::Model M = DAG.getTarget().getCodeModel();
12198   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12199   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12200   SDLoc dl(Op);
12201   auto PtrVT = getPointerTy(DAG.getDataLayout());
12202   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12203
12204   if (Subtarget->isPICStyleRIPRel() &&
12205       (M == CodeModel::Small || M == CodeModel::Kernel))
12206     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12207   else
12208     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12209
12210   // With PIC, the address is actually $g + Offset.
12211   if (isGlobalRelativeToPICBase(OpFlags)) {
12212     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12213                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12214   }
12215
12216   return Result;
12217 }
12218
12219 SDValue
12220 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12221                                       int64_t Offset, SelectionDAG &DAG) const {
12222   // Create the TargetGlobalAddress node, folding in the constant
12223   // offset if it is legal.
12224   unsigned char OpFlags =
12225       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12226   CodeModel::Model M = DAG.getTarget().getCodeModel();
12227   auto PtrVT = getPointerTy(DAG.getDataLayout());
12228   SDValue Result;
12229   if (OpFlags == X86II::MO_NO_FLAG &&
12230       X86::isOffsetSuitableForCodeModel(Offset, M)) {
12231     // A direct static reference to a global.
12232     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12233     Offset = 0;
12234   } else {
12235     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12236   }
12237
12238   if (Subtarget->isPICStyleRIPRel() &&
12239       (M == CodeModel::Small || M == CodeModel::Kernel))
12240     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12241   else
12242     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12243
12244   // With PIC, the address is actually $g + Offset.
12245   if (isGlobalRelativeToPICBase(OpFlags)) {
12246     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12247                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12248   }
12249
12250   // For globals that require a load from a stub to get the address, emit the
12251   // load.
12252   if (isGlobalStubReference(OpFlags))
12253     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12254                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12255                          false, false, false, 0);
12256
12257   // If there was a non-zero offset that we didn't fold, create an explicit
12258   // addition for it.
12259   if (Offset != 0)
12260     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12261                          DAG.getConstant(Offset, dl, PtrVT));
12262
12263   return Result;
12264 }
12265
12266 SDValue
12267 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12268   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12269   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12270   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12271 }
12272
12273 static SDValue
12274 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12275            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12276            unsigned char OperandFlags, bool LocalDynamic = false) {
12277   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12278   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12279   SDLoc dl(GA);
12280   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12281                                            GA->getValueType(0),
12282                                            GA->getOffset(),
12283                                            OperandFlags);
12284
12285   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12286                                            : X86ISD::TLSADDR;
12287
12288   if (InFlag) {
12289     SDValue Ops[] = { Chain,  TGA, *InFlag };
12290     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12291   } else {
12292     SDValue Ops[]  = { Chain, TGA };
12293     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12294   }
12295
12296   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12297   MFI->setAdjustsStack(true);
12298   MFI->setHasCalls(true);
12299
12300   SDValue Flag = Chain.getValue(1);
12301   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12302 }
12303
12304 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12305 static SDValue
12306 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12307                                 const EVT PtrVT) {
12308   SDValue InFlag;
12309   SDLoc dl(GA);  // ? function entry point might be better
12310   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12311                                    DAG.getNode(X86ISD::GlobalBaseReg,
12312                                                SDLoc(), PtrVT), InFlag);
12313   InFlag = Chain.getValue(1);
12314
12315   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12316 }
12317
12318 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12319 static SDValue
12320 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12321                                 const EVT PtrVT) {
12322   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12323                     X86::RAX, X86II::MO_TLSGD);
12324 }
12325
12326 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12327                                            SelectionDAG &DAG,
12328                                            const EVT PtrVT,
12329                                            bool is64Bit) {
12330   SDLoc dl(GA);
12331
12332   // Get the start address of the TLS block for this module.
12333   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12334       .getInfo<X86MachineFunctionInfo>();
12335   MFI->incNumLocalDynamicTLSAccesses();
12336
12337   SDValue Base;
12338   if (is64Bit) {
12339     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12340                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12341   } else {
12342     SDValue InFlag;
12343     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12344         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12345     InFlag = Chain.getValue(1);
12346     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12347                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12348   }
12349
12350   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12351   // of Base.
12352
12353   // Build x@dtpoff.
12354   unsigned char OperandFlags = X86II::MO_DTPOFF;
12355   unsigned WrapperKind = X86ISD::Wrapper;
12356   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12357                                            GA->getValueType(0),
12358                                            GA->getOffset(), OperandFlags);
12359   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12360
12361   // Add x@dtpoff with the base.
12362   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12363 }
12364
12365 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12366 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12367                                    const EVT PtrVT, TLSModel::Model model,
12368                                    bool is64Bit, bool isPIC) {
12369   SDLoc dl(GA);
12370
12371   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12372   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12373                                                          is64Bit ? 257 : 256));
12374
12375   SDValue ThreadPointer =
12376       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12377                   MachinePointerInfo(Ptr), false, false, false, 0);
12378
12379   unsigned char OperandFlags = 0;
12380   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12381   // initialexec.
12382   unsigned WrapperKind = X86ISD::Wrapper;
12383   if (model == TLSModel::LocalExec) {
12384     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12385   } else if (model == TLSModel::InitialExec) {
12386     if (is64Bit) {
12387       OperandFlags = X86II::MO_GOTTPOFF;
12388       WrapperKind = X86ISD::WrapperRIP;
12389     } else {
12390       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12391     }
12392   } else {
12393     llvm_unreachable("Unexpected model");
12394   }
12395
12396   // emit "addl x@ntpoff,%eax" (local exec)
12397   // or "addl x@indntpoff,%eax" (initial exec)
12398   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12399   SDValue TGA =
12400       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12401                                  GA->getOffset(), OperandFlags);
12402   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12403
12404   if (model == TLSModel::InitialExec) {
12405     if (isPIC && !is64Bit) {
12406       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12407                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12408                            Offset);
12409     }
12410
12411     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12412                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12413                          false, false, false, 0);
12414   }
12415
12416   // The address of the thread local variable is the add of the thread
12417   // pointer with the offset of the variable.
12418   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12419 }
12420
12421 SDValue
12422 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12423
12424   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12425
12426   // Cygwin uses emutls.
12427   // FIXME: It may be EmulatedTLS-generic also for X86-Android.
12428   if (Subtarget->isTargetWindowsCygwin())
12429     return LowerToTLSEmulatedModel(GA, DAG);
12430
12431   const GlobalValue *GV = GA->getGlobal();
12432   auto PtrVT = getPointerTy(DAG.getDataLayout());
12433
12434   if (Subtarget->isTargetELF()) {
12435     if (DAG.getTarget().Options.EmulatedTLS)
12436       return LowerToTLSEmulatedModel(GA, DAG);
12437     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12438     switch (model) {
12439       case TLSModel::GeneralDynamic:
12440         if (Subtarget->is64Bit())
12441           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12442         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12443       case TLSModel::LocalDynamic:
12444         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12445                                            Subtarget->is64Bit());
12446       case TLSModel::InitialExec:
12447       case TLSModel::LocalExec:
12448         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12449                                    DAG.getTarget().getRelocationModel() ==
12450                                        Reloc::PIC_);
12451     }
12452     llvm_unreachable("Unknown TLS model.");
12453   }
12454
12455   if (Subtarget->isTargetDarwin()) {
12456     // Darwin only has one model of TLS.  Lower to that.
12457     unsigned char OpFlag = 0;
12458     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12459                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12460
12461     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12462     // global base reg.
12463     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12464                  !Subtarget->is64Bit();
12465     if (PIC32)
12466       OpFlag = X86II::MO_TLVP_PIC_BASE;
12467     else
12468       OpFlag = X86II::MO_TLVP;
12469     SDLoc DL(Op);
12470     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12471                                                 GA->getValueType(0),
12472                                                 GA->getOffset(), OpFlag);
12473     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12474
12475     // With PIC32, the address is actually $g + Offset.
12476     if (PIC32)
12477       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12478                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12479                            Offset);
12480
12481     // Lowering the machine isd will make sure everything is in the right
12482     // location.
12483     SDValue Chain = DAG.getEntryNode();
12484     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12485     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, DL, true), DL);
12486     SDValue Args[] = { Chain, Offset };
12487     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12488     Chain =
12489         DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
12490                            DAG.getIntPtrConstant(0, DL, true), SDValue(), DL);
12491
12492     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12493     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12494     MFI->setAdjustsStack(true);
12495
12496     // And our return value (tls address) is in the standard call return value
12497     // location.
12498     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12499     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12500   }
12501
12502   if (Subtarget->isTargetKnownWindowsMSVC() ||
12503       Subtarget->isTargetWindowsGNU()) {
12504     // Just use the implicit TLS architecture
12505     // Need to generate someting similar to:
12506     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12507     //                                  ; from TEB
12508     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12509     //   mov     rcx, qword [rdx+rcx*8]
12510     //   mov     eax, .tls$:tlsvar
12511     //   [rax+rcx] contains the address
12512     // Windows 64bit: gs:0x58
12513     // Windows 32bit: fs:__tls_array
12514
12515     SDLoc dl(GA);
12516     SDValue Chain = DAG.getEntryNode();
12517
12518     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12519     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12520     // use its literal value of 0x2C.
12521     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12522                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12523                                                              256)
12524                                         : Type::getInt32PtrTy(*DAG.getContext(),
12525                                                               257));
12526
12527     SDValue TlsArray = Subtarget->is64Bit()
12528                            ? DAG.getIntPtrConstant(0x58, dl)
12529                            : (Subtarget->isTargetWindowsGNU()
12530                                   ? DAG.getIntPtrConstant(0x2C, dl)
12531                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12532
12533     SDValue ThreadPointer =
12534         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12535                     false, false, 0);
12536
12537     SDValue res;
12538     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12539       res = ThreadPointer;
12540     } else {
12541       // Load the _tls_index variable
12542       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12543       if (Subtarget->is64Bit())
12544         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12545                              MachinePointerInfo(), MVT::i32, false, false,
12546                              false, 0);
12547       else
12548         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12549                           false, false, 0);
12550
12551       auto &DL = DAG.getDataLayout();
12552       SDValue Scale =
12553           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12554       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12555
12556       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12557     }
12558
12559     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12560                       false, 0);
12561
12562     // Get the offset of start of .tls section
12563     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12564                                              GA->getValueType(0),
12565                                              GA->getOffset(), X86II::MO_SECREL);
12566     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12567
12568     // The address of the thread local variable is the add of the thread
12569     // pointer with the offset of the variable.
12570     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12571   }
12572
12573   llvm_unreachable("TLS not implemented for this target.");
12574 }
12575
12576 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12577 /// and take a 2 x i32 value to shift plus a shift amount.
12578 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12579   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12580   MVT VT = Op.getSimpleValueType();
12581   unsigned VTBits = VT.getSizeInBits();
12582   SDLoc dl(Op);
12583   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12584   SDValue ShOpLo = Op.getOperand(0);
12585   SDValue ShOpHi = Op.getOperand(1);
12586   SDValue ShAmt  = Op.getOperand(2);
12587   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12588   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12589   // during isel.
12590   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12591                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12592   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12593                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12594                        : DAG.getConstant(0, dl, VT);
12595
12596   SDValue Tmp2, Tmp3;
12597   if (Op.getOpcode() == ISD::SHL_PARTS) {
12598     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12599     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12600   } else {
12601     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12602     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12603   }
12604
12605   // If the shift amount is larger or equal than the width of a part we can't
12606   // rely on the results of shld/shrd. Insert a test and select the appropriate
12607   // values for large shift amounts.
12608   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12609                                 DAG.getConstant(VTBits, dl, MVT::i8));
12610   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12611                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12612
12613   SDValue Hi, Lo;
12614   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12615   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12616   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12617
12618   if (Op.getOpcode() == ISD::SHL_PARTS) {
12619     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12620     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12621   } else {
12622     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12623     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12624   }
12625
12626   SDValue Ops[2] = { Lo, Hi };
12627   return DAG.getMergeValues(Ops, dl);
12628 }
12629
12630 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12631                                            SelectionDAG &DAG) const {
12632   SDValue Src = Op.getOperand(0);
12633   MVT SrcVT = Src.getSimpleValueType();
12634   MVT VT = Op.getSimpleValueType();
12635   SDLoc dl(Op);
12636
12637   if (SrcVT.isVector()) {
12638     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12639       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12640                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12641                          DAG.getUNDEF(SrcVT)));
12642     }
12643     if (SrcVT.getVectorElementType() == MVT::i1) {
12644       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12645       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12646                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12647     }
12648     return SDValue();
12649   }
12650
12651   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12652          "Unknown SINT_TO_FP to lower!");
12653
12654   // These are really Legal; return the operand so the caller accepts it as
12655   // Legal.
12656   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12657     return Op;
12658   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12659       Subtarget->is64Bit()) {
12660     return Op;
12661   }
12662
12663   unsigned Size = SrcVT.getSizeInBits()/8;
12664   MachineFunction &MF = DAG.getMachineFunction();
12665   auto PtrVT = getPointerTy(MF.getDataLayout());
12666   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12667   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12668   SDValue Chain = DAG.getStore(
12669       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12670       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12671       false, 0);
12672   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12673 }
12674
12675 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12676                                      SDValue StackSlot,
12677                                      SelectionDAG &DAG) const {
12678   // Build the FILD
12679   SDLoc DL(Op);
12680   SDVTList Tys;
12681   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12682   if (useSSE)
12683     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12684   else
12685     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12686
12687   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12688
12689   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12690   MachineMemOperand *MMO;
12691   if (FI) {
12692     int SSFI = FI->getIndex();
12693     MMO = DAG.getMachineFunction().getMachineMemOperand(
12694         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12695         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12696   } else {
12697     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12698     StackSlot = StackSlot.getOperand(1);
12699   }
12700   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12701   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12702                                            X86ISD::FILD, DL,
12703                                            Tys, Ops, SrcVT, MMO);
12704
12705   if (useSSE) {
12706     Chain = Result.getValue(1);
12707     SDValue InFlag = Result.getValue(2);
12708
12709     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12710     // shouldn't be necessary except that RFP cannot be live across
12711     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12712     MachineFunction &MF = DAG.getMachineFunction();
12713     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12714     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12715     auto PtrVT = getPointerTy(MF.getDataLayout());
12716     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12717     Tys = DAG.getVTList(MVT::Other);
12718     SDValue Ops[] = {
12719       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12720     };
12721     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12722         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12723         MachineMemOperand::MOStore, SSFISize, SSFISize);
12724
12725     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12726                                     Ops, Op.getValueType(), MMO);
12727     Result = DAG.getLoad(
12728         Op.getValueType(), DL, Chain, StackSlot,
12729         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12730         false, false, false, 0);
12731   }
12732
12733   return Result;
12734 }
12735
12736 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12737 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12738                                                SelectionDAG &DAG) const {
12739   // This algorithm is not obvious. Here it is what we're trying to output:
12740   /*
12741      movq       %rax,  %xmm0
12742      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12743      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12744      #ifdef __SSE3__
12745        haddpd   %xmm0, %xmm0
12746      #else
12747        pshufd   $0x4e, %xmm0, %xmm1
12748        addpd    %xmm1, %xmm0
12749      #endif
12750   */
12751
12752   SDLoc dl(Op);
12753   LLVMContext *Context = DAG.getContext();
12754
12755   // Build some magic constants.
12756   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12757   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12758   auto PtrVT = getPointerTy(DAG.getDataLayout());
12759   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12760
12761   SmallVector<Constant*,2> CV1;
12762   CV1.push_back(
12763     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12764                                       APInt(64, 0x4330000000000000ULL))));
12765   CV1.push_back(
12766     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12767                                       APInt(64, 0x4530000000000000ULL))));
12768   Constant *C1 = ConstantVector::get(CV1);
12769   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12770
12771   // Load the 64-bit value into an XMM register.
12772   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12773                             Op.getOperand(0));
12774   SDValue CLod0 =
12775       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12776                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12777                   false, false, false, 16);
12778   SDValue Unpck1 =
12779       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12780
12781   SDValue CLod1 =
12782       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12783                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12784                   false, false, false, 16);
12785   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12786   // TODO: Are there any fast-math-flags to propagate here?
12787   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12788   SDValue Result;
12789
12790   if (Subtarget->hasSSE3()) {
12791     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12792     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12793   } else {
12794     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12795     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12796                                            S2F, 0x4E, DAG);
12797     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12798                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12799   }
12800
12801   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12802                      DAG.getIntPtrConstant(0, dl));
12803 }
12804
12805 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12806 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12807                                                SelectionDAG &DAG) const {
12808   SDLoc dl(Op);
12809   // FP constant to bias correct the final result.
12810   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12811                                    MVT::f64);
12812
12813   // Load the 32-bit value into an XMM register.
12814   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12815                              Op.getOperand(0));
12816
12817   // Zero out the upper parts of the register.
12818   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12819
12820   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12821                      DAG.getBitcast(MVT::v2f64, Load),
12822                      DAG.getIntPtrConstant(0, dl));
12823
12824   // Or the load with the bias.
12825   SDValue Or = DAG.getNode(
12826       ISD::OR, dl, MVT::v2i64,
12827       DAG.getBitcast(MVT::v2i64,
12828                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12829       DAG.getBitcast(MVT::v2i64,
12830                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12831   Or =
12832       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12833                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12834
12835   // Subtract the bias.
12836   // TODO: Are there any fast-math-flags to propagate here?
12837   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12838
12839   // Handle final rounding.
12840   MVT DestVT = Op.getSimpleValueType();
12841
12842   if (DestVT.bitsLT(MVT::f64))
12843     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12844                        DAG.getIntPtrConstant(0, dl));
12845   if (DestVT.bitsGT(MVT::f64))
12846     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12847
12848   // Handle final rounding.
12849   return Sub;
12850 }
12851
12852 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12853                                      const X86Subtarget &Subtarget) {
12854   // The algorithm is the following:
12855   // #ifdef __SSE4_1__
12856   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12857   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12858   //                                 (uint4) 0x53000000, 0xaa);
12859   // #else
12860   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12861   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12862   // #endif
12863   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12864   //     return (float4) lo + fhi;
12865
12866   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12867   // reassociate the two FADDs, and if we do that, the algorithm fails
12868   // spectacularly (PR24512).
12869   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12870   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12871   // there's also the MachineCombiner reassociations happening on Machine IR.
12872   if (DAG.getTarget().Options.UnsafeFPMath)
12873     return SDValue();
12874
12875   SDLoc DL(Op);
12876   SDValue V = Op->getOperand(0);
12877   MVT VecIntVT = V.getSimpleValueType();
12878   bool Is128 = VecIntVT == MVT::v4i32;
12879   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12880   // If we convert to something else than the supported type, e.g., to v4f64,
12881   // abort early.
12882   if (VecFloatVT != Op->getSimpleValueType(0))
12883     return SDValue();
12884
12885   unsigned NumElts = VecIntVT.getVectorNumElements();
12886   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12887          "Unsupported custom type");
12888   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12889
12890   // In the #idef/#else code, we have in common:
12891   // - The vector of constants:
12892   // -- 0x4b000000
12893   // -- 0x53000000
12894   // - A shift:
12895   // -- v >> 16
12896
12897   // Create the splat vector for 0x4b000000.
12898   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12899   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12900                            CstLow, CstLow, CstLow, CstLow};
12901   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12902                                   makeArrayRef(&CstLowArray[0], NumElts));
12903   // Create the splat vector for 0x53000000.
12904   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12905   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12906                             CstHigh, CstHigh, CstHigh, CstHigh};
12907   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12908                                    makeArrayRef(&CstHighArray[0], NumElts));
12909
12910   // Create the right shift.
12911   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12912   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12913                              CstShift, CstShift, CstShift, CstShift};
12914   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12915                                     makeArrayRef(&CstShiftArray[0], NumElts));
12916   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12917
12918   SDValue Low, High;
12919   if (Subtarget.hasSSE41()) {
12920     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12921     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12922     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12923     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12924     // Low will be bitcasted right away, so do not bother bitcasting back to its
12925     // original type.
12926     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12927                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12928     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12929     //                                 (uint4) 0x53000000, 0xaa);
12930     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12931     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12932     // High will be bitcasted right away, so do not bother bitcasting back to
12933     // its original type.
12934     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12935                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12936   } else {
12937     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12938     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12939                                      CstMask, CstMask, CstMask);
12940     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12941     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12942     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12943
12944     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12945     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12946   }
12947
12948   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12949   SDValue CstFAdd = DAG.getConstantFP(
12950       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12951   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12952                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12953   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12954                                    makeArrayRef(&CstFAddArray[0], NumElts));
12955
12956   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12957   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12958   // TODO: Are there any fast-math-flags to propagate here?
12959   SDValue FHigh =
12960       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12961   //     return (float4) lo + fhi;
12962   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12963   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12964 }
12965
12966 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12967                                                SelectionDAG &DAG) const {
12968   SDValue N0 = Op.getOperand(0);
12969   MVT SVT = N0.getSimpleValueType();
12970   SDLoc dl(Op);
12971
12972   switch (SVT.SimpleTy) {
12973   default:
12974     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12975   case MVT::v4i8:
12976   case MVT::v4i16:
12977   case MVT::v8i8:
12978   case MVT::v8i16: {
12979     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12980     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12981                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12982   }
12983   case MVT::v4i32:
12984   case MVT::v8i32:
12985     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12986   case MVT::v16i8:
12987   case MVT::v16i16:
12988     assert(Subtarget->hasAVX512());
12989     return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12990                        DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12991   }
12992 }
12993
12994 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12995                                            SelectionDAG &DAG) const {
12996   SDValue N0 = Op.getOperand(0);
12997   SDLoc dl(Op);
12998   auto PtrVT = getPointerTy(DAG.getDataLayout());
12999
13000   if (Op.getSimpleValueType().isVector())
13001     return lowerUINT_TO_FP_vec(Op, DAG);
13002
13003   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13004   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13005   // the optimization here.
13006   if (DAG.SignBitIsZero(N0))
13007     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13008
13009   MVT SrcVT = N0.getSimpleValueType();
13010   MVT DstVT = Op.getSimpleValueType();
13011
13012   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
13013       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
13014     // Conversions from unsigned i32 to f32/f64 are legal,
13015     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
13016     return Op;
13017   }
13018
13019   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13020     return LowerUINT_TO_FP_i64(Op, DAG);
13021   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13022     return LowerUINT_TO_FP_i32(Op, DAG);
13023   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13024     return SDValue();
13025
13026   // Make a 64-bit buffer, and use it to build an FILD.
13027   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13028   if (SrcVT == MVT::i32) {
13029     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
13030     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
13031     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13032                                   StackSlot, MachinePointerInfo(),
13033                                   false, false, 0);
13034     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
13035                                   OffsetSlot, MachinePointerInfo(),
13036                                   false, false, 0);
13037     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13038     return Fild;
13039   }
13040
13041   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13042   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13043                                StackSlot, MachinePointerInfo(),
13044                                false, false, 0);
13045   // For i64 source, we need to add the appropriate power of 2 if the input
13046   // was negative.  This is the same as the optimization in
13047   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13048   // we must be careful to do the computation in x87 extended precision, not
13049   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13050   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13051   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13052       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13053       MachineMemOperand::MOLoad, 8, 8);
13054
13055   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13056   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13057   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13058                                          MVT::i64, MMO);
13059
13060   APInt FF(32, 0x5F800000ULL);
13061
13062   // Check whether the sign bit is set.
13063   SDValue SignSet = DAG.getSetCC(
13064       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
13065       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
13066
13067   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13068   SDValue FudgePtr = DAG.getConstantPool(
13069       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
13070
13071   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13072   SDValue Zero = DAG.getIntPtrConstant(0, dl);
13073   SDValue Four = DAG.getIntPtrConstant(4, dl);
13074   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13075                                Zero, Four);
13076   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
13077
13078   // Load the value out, extending it from f32 to f80.
13079   // FIXME: Avoid the extend by constructing the right constant pool?
13080   SDValue Fudge = DAG.getExtLoad(
13081       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
13082       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
13083       false, false, false, 4);
13084   // Extend everything to 80 bits to force it to be done on x87.
13085   // TODO: Are there any fast-math-flags to propagate here?
13086   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13087   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
13088                      DAG.getIntPtrConstant(0, dl));
13089 }
13090
13091 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
13092 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
13093 // just return an <SDValue(), SDValue()> pair.
13094 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
13095 // to i16, i32 or i64, and we lower it to a legal sequence.
13096 // If lowered to the final integer result we return a <result, SDValue()> pair.
13097 // Otherwise we lower it to a sequence ending with a FIST, return a
13098 // <FIST, StackSlot> pair, and the caller is responsible for loading
13099 // the final integer result from StackSlot.
13100 std::pair<SDValue,SDValue>
13101 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13102                                    bool IsSigned, bool IsReplace) const {
13103   SDLoc DL(Op);
13104
13105   EVT DstTy = Op.getValueType();
13106   EVT TheVT = Op.getOperand(0).getValueType();
13107   auto PtrVT = getPointerTy(DAG.getDataLayout());
13108
13109   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
13110     // f16 must be promoted before using the lowering in this routine.
13111     // fp128 does not use this lowering.
13112     return std::make_pair(SDValue(), SDValue());
13113   }
13114
13115   // If using FIST to compute an unsigned i64, we'll need some fixup
13116   // to handle values above the maximum signed i64.  A FIST is always
13117   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13118   bool UnsignedFixup = !IsSigned &&
13119                        DstTy == MVT::i64 &&
13120                        (!Subtarget->is64Bit() ||
13121                         !isScalarFPTypeInSSEReg(TheVT));
13122
13123   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
13124     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13125     // The low 32 bits of the fist result will have the correct uint32 result.
13126     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13127     DstTy = MVT::i64;
13128   }
13129
13130   assert(DstTy.getSimpleVT() <= MVT::i64 &&
13131          DstTy.getSimpleVT() >= MVT::i16 &&
13132          "Unknown FP_TO_INT to lower!");
13133
13134   // These are really Legal.
13135   if (DstTy == MVT::i32 &&
13136       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13137     return std::make_pair(SDValue(), SDValue());
13138   if (Subtarget->is64Bit() &&
13139       DstTy == MVT::i64 &&
13140       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13141     return std::make_pair(SDValue(), SDValue());
13142
13143   // We lower FP->int64 into FISTP64 followed by a load from a temporary
13144   // stack slot.
13145   MachineFunction &MF = DAG.getMachineFunction();
13146   unsigned MemSize = DstTy.getSizeInBits()/8;
13147   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13148   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13149
13150   unsigned Opc;
13151   switch (DstTy.getSimpleVT().SimpleTy) {
13152   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13153   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13154   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13155   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13156   }
13157
13158   SDValue Chain = DAG.getEntryNode();
13159   SDValue Value = Op.getOperand(0);
13160   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13161
13162   if (UnsignedFixup) {
13163     //
13164     // Conversion to unsigned i64 is implemented with a select,
13165     // depending on whether the source value fits in the range
13166     // of a signed i64.  Let Thresh be the FP equivalent of
13167     // 0x8000000000000000ULL.
13168     //
13169     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13170     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
13171     //  Fist-to-mem64 FistSrc
13172     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13173     //  to XOR'ing the high 32 bits with Adjust.
13174     //
13175     // Being a power of 2, Thresh is exactly representable in all FP formats.
13176     // For X87 we'd like to use the smallest FP type for this constant, but
13177     // for DAG type consistency we have to match the FP operand type.
13178
13179     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13180     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13181     bool LosesInfo = false;
13182     if (TheVT == MVT::f64)
13183       // The rounding mode is irrelevant as the conversion should be exact.
13184       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13185                               &LosesInfo);
13186     else if (TheVT == MVT::f80)
13187       Status = Thresh.convert(APFloat::x87DoubleExtended,
13188                               APFloat::rmNearestTiesToEven, &LosesInfo);
13189
13190     assert(Status == APFloat::opOK && !LosesInfo &&
13191            "FP conversion should have been exact");
13192
13193     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13194
13195     SDValue Cmp = DAG.getSetCC(DL,
13196                                getSetCCResultType(DAG.getDataLayout(),
13197                                                   *DAG.getContext(), TheVT),
13198                                Value, ThreshVal, ISD::SETLT);
13199     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13200                            DAG.getConstant(0, DL, MVT::i32),
13201                            DAG.getConstant(0x80000000, DL, MVT::i32));
13202     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13203     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13204                                               *DAG.getContext(), TheVT),
13205                        Value, ThreshVal, ISD::SETLT);
13206     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13207   }
13208
13209   // FIXME This causes a redundant load/store if the SSE-class value is already
13210   // in memory, such as if it is on the callstack.
13211   if (isScalarFPTypeInSSEReg(TheVT)) {
13212     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13213     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13214                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
13215                          false, 0);
13216     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13217     SDValue Ops[] = {
13218       Chain, StackSlot, DAG.getValueType(TheVT)
13219     };
13220
13221     MachineMemOperand *MMO =
13222         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13223                                 MachineMemOperand::MOLoad, MemSize, MemSize);
13224     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13225     Chain = Value.getValue(1);
13226     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13227     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13228   }
13229
13230   MachineMemOperand *MMO =
13231       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13232                               MachineMemOperand::MOStore, MemSize, MemSize);
13233
13234   if (UnsignedFixup) {
13235
13236     // Insert the FIST, load its result as two i32's,
13237     // and XOR the high i32 with Adjust.
13238
13239     SDValue FistOps[] = { Chain, Value, StackSlot };
13240     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13241                                            FistOps, DstTy, MMO);
13242
13243     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13244                                 MachinePointerInfo(),
13245                                 false, false, false, 0);
13246     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13247                                    DAG.getConstant(4, DL, PtrVT));
13248
13249     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13250                                  MachinePointerInfo(),
13251                                  false, false, false, 0);
13252     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13253
13254     if (Subtarget->is64Bit()) {
13255       // Join High32 and Low32 into a 64-bit result.
13256       // (High32 << 32) | Low32
13257       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13258       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13259       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13260                            DAG.getConstant(32, DL, MVT::i8));
13261       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13262       return std::make_pair(Result, SDValue());
13263     }
13264
13265     SDValue ResultOps[] = { Low32, High32 };
13266
13267     SDValue pair = IsReplace
13268       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13269       : DAG.getMergeValues(ResultOps, DL);
13270     return std::make_pair(pair, SDValue());
13271   } else {
13272     // Build the FP_TO_INT*_IN_MEM
13273     SDValue Ops[] = { Chain, Value, StackSlot };
13274     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13275                                            Ops, DstTy, MMO);
13276     return std::make_pair(FIST, StackSlot);
13277   }
13278 }
13279
13280 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13281                               const X86Subtarget *Subtarget) {
13282   MVT VT = Op->getSimpleValueType(0);
13283   SDValue In = Op->getOperand(0);
13284   MVT InVT = In.getSimpleValueType();
13285   SDLoc dl(Op);
13286
13287   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13288     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13289
13290   // Optimize vectors in AVX mode:
13291   //
13292   //   v8i16 -> v8i32
13293   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13294   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13295   //   Concat upper and lower parts.
13296   //
13297   //   v4i32 -> v4i64
13298   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13299   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13300   //   Concat upper and lower parts.
13301   //
13302
13303   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13304       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13305       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13306     return SDValue();
13307
13308   if (Subtarget->hasInt256())
13309     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13310
13311   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13312   SDValue Undef = DAG.getUNDEF(InVT);
13313   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13314   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13315   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13316
13317   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13318                              VT.getVectorNumElements()/2);
13319
13320   OpLo = DAG.getBitcast(HVT, OpLo);
13321   OpHi = DAG.getBitcast(HVT, OpHi);
13322
13323   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13324 }
13325
13326 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13327                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13328   MVT VT = Op->getSimpleValueType(0);
13329   SDValue In = Op->getOperand(0);
13330   MVT InVT = In.getSimpleValueType();
13331   SDLoc DL(Op);
13332   unsigned int NumElts = VT.getVectorNumElements();
13333   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13334     return SDValue();
13335
13336   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13337     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13338
13339   assert(InVT.getVectorElementType() == MVT::i1);
13340   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13341   SDValue One =
13342    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13343   SDValue Zero =
13344    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13345
13346   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13347   if (VT.is512BitVector())
13348     return V;
13349   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13350 }
13351
13352 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13353                                SelectionDAG &DAG) {
13354   if (Subtarget->hasFp256())
13355     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13356       return Res;
13357
13358   return SDValue();
13359 }
13360
13361 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13362                                 SelectionDAG &DAG) {
13363   SDLoc DL(Op);
13364   MVT VT = Op.getSimpleValueType();
13365   SDValue In = Op.getOperand(0);
13366   MVT SVT = In.getSimpleValueType();
13367
13368   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13369     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13370
13371   if (Subtarget->hasFp256())
13372     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13373       return Res;
13374
13375   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13376          VT.getVectorNumElements() != SVT.getVectorNumElements());
13377   return SDValue();
13378 }
13379
13380 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
13381                                   const X86Subtarget *Subtarget) {
13382
13383   SDLoc DL(Op);
13384   MVT VT = Op.getSimpleValueType();
13385   SDValue In = Op.getOperand(0);
13386   MVT InVT = In.getSimpleValueType();
13387
13388   assert(VT.getVectorElementType() == MVT::i1 && "Unexected vector type.");
13389
13390   // Shift LSB to MSB and use VPMOVB2M - SKX.
13391   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
13392   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13393          Subtarget->hasBWI()) ||     // legal, will go to VPMOVB2M, VPMOVW2M
13394       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13395              InVT.getScalarSizeInBits() <= 16 && Subtarget->hasBWI() &&
13396              Subtarget->hasVLX())) { // legal, will go to VPMOVB2M, VPMOVW2M
13397     // Shift packed bytes not supported natively, bitcast to dword
13398     MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
13399     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, ExtVT,
13400                                      DAG.getBitcast(ExtVT, In),
13401                                      DAG.getConstant(ShiftInx, DL, ExtVT));
13402     ShiftNode = DAG.getBitcast(InVT, ShiftNode);
13403     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13404   }
13405   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13406          Subtarget->hasDQI()) ||  // legal, will go to VPMOVD2M, VPMOVQ2M
13407       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13408          InVT.getScalarSizeInBits() >= 32 && Subtarget->hasDQI() &&
13409          Subtarget->hasVLX())) {  // legal, will go to VPMOVD2M, VPMOVQ2M
13410
13411     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13412                                      DAG.getConstant(ShiftInx, DL, InVT));
13413     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13414   }
13415
13416   // Shift LSB to MSB, extend if necessary and use TESTM.
13417   unsigned NumElts = InVT.getVectorNumElements();
13418   if (InVT.getSizeInBits() < 512 &&
13419       (InVT.getScalarType() == MVT::i8 || InVT.getScalarType() == MVT::i16 ||
13420        !Subtarget->hasVLX())) {
13421     assert((NumElts == 8 || NumElts == 16) && "Unexected vector type.");
13422
13423     // TESTD/Q should be used (if BW supported we use CVT2MASK above),
13424     // so vector should be extended to packed dword/qword.
13425     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(512/NumElts), NumElts);
13426     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13427     InVT = ExtVT;
13428     ShiftInx = InVT.getScalarSizeInBits() - 1;
13429   }
13430
13431   SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13432                                    DAG.getConstant(ShiftInx, DL, InVT));
13433   return DAG.getNode(X86ISD::TESTM, DL, VT, ShiftNode, ShiftNode);
13434 }
13435
13436 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13437   SDLoc DL(Op);
13438   MVT VT = Op.getSimpleValueType();
13439   SDValue In = Op.getOperand(0);
13440   MVT InVT = In.getSimpleValueType();
13441
13442   if (VT == MVT::i1) {
13443     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13444            "Invalid scalar TRUNCATE operation");
13445     if (InVT.getSizeInBits() >= 32)
13446       return SDValue();
13447     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13448     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13449   }
13450   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13451          "Invalid TRUNCATE operation");
13452
13453   if (VT.getVectorElementType() == MVT::i1)
13454     return LowerTruncateVecI1(Op, DAG, Subtarget);
13455
13456   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13457   if (Subtarget->hasAVX512()) {
13458     // word to byte only under BWI
13459     if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13460       return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13461                          DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13462     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13463   }
13464   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13465     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13466     if (Subtarget->hasInt256()) {
13467       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13468       In = DAG.getBitcast(MVT::v8i32, In);
13469       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13470                                 ShufMask);
13471       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13472                          DAG.getIntPtrConstant(0, DL));
13473     }
13474
13475     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13476                                DAG.getIntPtrConstant(0, DL));
13477     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13478                                DAG.getIntPtrConstant(2, DL));
13479     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13480     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13481     static const int ShufMask[] = {0, 2, 4, 6};
13482     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13483   }
13484
13485   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13486     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13487     if (Subtarget->hasInt256()) {
13488       In = DAG.getBitcast(MVT::v32i8, In);
13489
13490       SmallVector<SDValue,32> pshufbMask;
13491       for (unsigned i = 0; i < 2; ++i) {
13492         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13493         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13494         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13495         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13496         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13497         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13498         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13499         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13500         for (unsigned j = 0; j < 8; ++j)
13501           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13502       }
13503       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13504       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13505       In = DAG.getBitcast(MVT::v4i64, In);
13506
13507       static const int ShufMask[] = {0,  2,  -1,  -1};
13508       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13509                                 &ShufMask[0]);
13510       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13511                        DAG.getIntPtrConstant(0, DL));
13512       return DAG.getBitcast(VT, In);
13513     }
13514
13515     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13516                                DAG.getIntPtrConstant(0, DL));
13517
13518     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13519                                DAG.getIntPtrConstant(4, DL));
13520
13521     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13522     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13523
13524     // The PSHUFB mask:
13525     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13526                                    -1, -1, -1, -1, -1, -1, -1, -1};
13527
13528     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13529     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13530     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13531
13532     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13533     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13534
13535     // The MOVLHPS Mask:
13536     static const int ShufMask2[] = {0, 1, 4, 5};
13537     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13538     return DAG.getBitcast(MVT::v8i16, res);
13539   }
13540
13541   // Handle truncation of V256 to V128 using shuffles.
13542   if (!VT.is128BitVector() || !InVT.is256BitVector())
13543     return SDValue();
13544
13545   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13546
13547   unsigned NumElems = VT.getVectorNumElements();
13548   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13549
13550   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13551   // Prepare truncation shuffle mask
13552   for (unsigned i = 0; i != NumElems; ++i)
13553     MaskVec[i] = i * 2;
13554   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13555                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13556   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13557                      DAG.getIntPtrConstant(0, DL));
13558 }
13559
13560 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13561                                            SelectionDAG &DAG) const {
13562   assert(!Op.getSimpleValueType().isVector());
13563
13564   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13565     /*IsSigned=*/ true, /*IsReplace=*/ false);
13566   SDValue FIST = Vals.first, StackSlot = Vals.second;
13567   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13568   if (!FIST.getNode())
13569     return Op;
13570
13571   if (StackSlot.getNode())
13572     // Load the result.
13573     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13574                        FIST, StackSlot, MachinePointerInfo(),
13575                        false, false, false, 0);
13576
13577   // The node is the result.
13578   return FIST;
13579 }
13580
13581 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13582                                            SelectionDAG &DAG) const {
13583   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13584     /*IsSigned=*/ false, /*IsReplace=*/ false);
13585   SDValue FIST = Vals.first, StackSlot = Vals.second;
13586   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13587   if (!FIST.getNode())
13588     return Op;
13589
13590   if (StackSlot.getNode())
13591     // Load the result.
13592     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13593                        FIST, StackSlot, MachinePointerInfo(),
13594                        false, false, false, 0);
13595
13596   // The node is the result.
13597   return FIST;
13598 }
13599
13600 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13601   SDLoc DL(Op);
13602   MVT VT = Op.getSimpleValueType();
13603   SDValue In = Op.getOperand(0);
13604   MVT SVT = In.getSimpleValueType();
13605
13606   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13607
13608   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13609                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13610                                  In, DAG.getUNDEF(SVT)));
13611 }
13612
13613 /// The only differences between FABS and FNEG are the mask and the logic op.
13614 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13615 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13616   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13617          "Wrong opcode for lowering FABS or FNEG.");
13618
13619   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13620
13621   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13622   // into an FNABS. We'll lower the FABS after that if it is still in use.
13623   if (IsFABS)
13624     for (SDNode *User : Op->uses())
13625       if (User->getOpcode() == ISD::FNEG)
13626         return Op;
13627
13628   SDLoc dl(Op);
13629   MVT VT = Op.getSimpleValueType();
13630
13631   bool IsF128 = (VT == MVT::f128);
13632
13633   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13634   // decide if we should generate a 16-byte constant mask when we only need 4 or
13635   // 8 bytes for the scalar case.
13636
13637   MVT LogicVT;
13638   MVT EltVT;
13639   unsigned NumElts;
13640
13641   if (VT.isVector()) {
13642     LogicVT = VT;
13643     EltVT = VT.getVectorElementType();
13644     NumElts = VT.getVectorNumElements();
13645   } else if (IsF128) {
13646     // SSE instructions are used for optimized f128 logical operations.
13647     LogicVT = MVT::f128;
13648     EltVT = VT;
13649     NumElts = 1;
13650   } else {
13651     // There are no scalar bitwise logical SSE/AVX instructions, so we
13652     // generate a 16-byte vector constant and logic op even for the scalar case.
13653     // Using a 16-byte mask allows folding the load of the mask with
13654     // the logic op, so it can save (~4 bytes) on code size.
13655     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13656     EltVT = VT;
13657     NumElts = (VT == MVT::f64) ? 2 : 4;
13658   }
13659
13660   unsigned EltBits = EltVT.getSizeInBits();
13661   LLVMContext *Context = DAG.getContext();
13662   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13663   APInt MaskElt =
13664     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13665   Constant *C = ConstantInt::get(*Context, MaskElt);
13666   C = ConstantVector::getSplat(NumElts, C);
13667   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13668   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13669   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13670   SDValue Mask =
13671       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13672                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13673                   false, false, false, Alignment);
13674
13675   SDValue Op0 = Op.getOperand(0);
13676   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13677   unsigned LogicOp =
13678     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13679   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13680
13681   if (VT.isVector() || IsF128)
13682     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13683
13684   // For the scalar case extend to a 128-bit vector, perform the logic op,
13685   // and extract the scalar result back out.
13686   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13687   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13688   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13689                      DAG.getIntPtrConstant(0, dl));
13690 }
13691
13692 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13693   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13694   LLVMContext *Context = DAG.getContext();
13695   SDValue Op0 = Op.getOperand(0);
13696   SDValue Op1 = Op.getOperand(1);
13697   SDLoc dl(Op);
13698   MVT VT = Op.getSimpleValueType();
13699   MVT SrcVT = Op1.getSimpleValueType();
13700   bool IsF128 = (VT == MVT::f128);
13701
13702   // If second operand is smaller, extend it first.
13703   if (SrcVT.bitsLT(VT)) {
13704     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13705     SrcVT = VT;
13706   }
13707   // And if it is bigger, shrink it first.
13708   if (SrcVT.bitsGT(VT)) {
13709     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13710     SrcVT = VT;
13711   }
13712
13713   // At this point the operands and the result should have the same
13714   // type, and that won't be f80 since that is not custom lowered.
13715   assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13716          "Unexpected type in LowerFCOPYSIGN");
13717
13718   const fltSemantics &Sem =
13719       VT == MVT::f64 ? APFloat::IEEEdouble :
13720           (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13721   const unsigned SizeInBits = VT.getSizeInBits();
13722
13723   SmallVector<Constant *, 4> CV(
13724       VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13725       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13726
13727   // First, clear all bits but the sign bit from the second operand (sign).
13728   CV[0] = ConstantFP::get(*Context,
13729                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13730   Constant *C = ConstantVector::get(CV);
13731   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13732   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13733
13734   // Perform all logic operations as 16-byte vectors because there are no
13735   // scalar FP logic instructions in SSE. This allows load folding of the
13736   // constants into the logic instructions.
13737   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13738   SDValue Mask1 =
13739       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13740                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13741                   false, false, false, 16);
13742   if (!IsF128)
13743     Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13744   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13745
13746   // Next, clear the sign bit from the first operand (magnitude).
13747   // If it's a constant, we can clear it here.
13748   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13749     APFloat APF = Op0CN->getValueAPF();
13750     // If the magnitude is a positive zero, the sign bit alone is enough.
13751     if (APF.isPosZero())
13752       return IsF128 ? SignBit :
13753           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13754                       DAG.getIntPtrConstant(0, dl));
13755     APF.clearSign();
13756     CV[0] = ConstantFP::get(*Context, APF);
13757   } else {
13758     CV[0] = ConstantFP::get(
13759         *Context,
13760         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13761   }
13762   C = ConstantVector::get(CV);
13763   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13764   SDValue Val =
13765       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13766                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13767                   false, false, false, 16);
13768   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13769   if (!isa<ConstantFPSDNode>(Op0)) {
13770     if (!IsF128)
13771       Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13772     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13773   }
13774   // OR the magnitude value with the sign bit.
13775   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13776   return IsF128 ? Val :
13777       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13778                   DAG.getIntPtrConstant(0, dl));
13779 }
13780
13781 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13782   SDValue N0 = Op.getOperand(0);
13783   SDLoc dl(Op);
13784   MVT VT = Op.getSimpleValueType();
13785
13786   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13787   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13788                                   DAG.getConstant(1, dl, VT));
13789   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13790 }
13791
13792 // Check whether an OR'd tree is PTEST-able.
13793 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13794                                       SelectionDAG &DAG) {
13795   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13796
13797   if (!Subtarget->hasSSE41())
13798     return SDValue();
13799
13800   if (!Op->hasOneUse())
13801     return SDValue();
13802
13803   SDNode *N = Op.getNode();
13804   SDLoc DL(N);
13805
13806   SmallVector<SDValue, 8> Opnds;
13807   DenseMap<SDValue, unsigned> VecInMap;
13808   SmallVector<SDValue, 8> VecIns;
13809   EVT VT = MVT::Other;
13810
13811   // Recognize a special case where a vector is casted into wide integer to
13812   // test all 0s.
13813   Opnds.push_back(N->getOperand(0));
13814   Opnds.push_back(N->getOperand(1));
13815
13816   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13817     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13818     // BFS traverse all OR'd operands.
13819     if (I->getOpcode() == ISD::OR) {
13820       Opnds.push_back(I->getOperand(0));
13821       Opnds.push_back(I->getOperand(1));
13822       // Re-evaluate the number of nodes to be traversed.
13823       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13824       continue;
13825     }
13826
13827     // Quit if a non-EXTRACT_VECTOR_ELT
13828     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13829       return SDValue();
13830
13831     // Quit if without a constant index.
13832     SDValue Idx = I->getOperand(1);
13833     if (!isa<ConstantSDNode>(Idx))
13834       return SDValue();
13835
13836     SDValue ExtractedFromVec = I->getOperand(0);
13837     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13838     if (M == VecInMap.end()) {
13839       VT = ExtractedFromVec.getValueType();
13840       // Quit if not 128/256-bit vector.
13841       if (!VT.is128BitVector() && !VT.is256BitVector())
13842         return SDValue();
13843       // Quit if not the same type.
13844       if (VecInMap.begin() != VecInMap.end() &&
13845           VT != VecInMap.begin()->first.getValueType())
13846         return SDValue();
13847       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13848       VecIns.push_back(ExtractedFromVec);
13849     }
13850     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13851   }
13852
13853   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13854          "Not extracted from 128-/256-bit vector.");
13855
13856   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13857
13858   for (DenseMap<SDValue, unsigned>::const_iterator
13859         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13860     // Quit if not all elements are used.
13861     if (I->second != FullMask)
13862       return SDValue();
13863   }
13864
13865   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13866
13867   // Cast all vectors into TestVT for PTEST.
13868   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13869     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13870
13871   // If more than one full vectors are evaluated, OR them first before PTEST.
13872   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13873     // Each iteration will OR 2 nodes and append the result until there is only
13874     // 1 node left, i.e. the final OR'd value of all vectors.
13875     SDValue LHS = VecIns[Slot];
13876     SDValue RHS = VecIns[Slot + 1];
13877     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13878   }
13879
13880   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13881                      VecIns.back(), VecIns.back());
13882 }
13883
13884 /// \brief return true if \c Op has a use that doesn't just read flags.
13885 static bool hasNonFlagsUse(SDValue Op) {
13886   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13887        ++UI) {
13888     SDNode *User = *UI;
13889     unsigned UOpNo = UI.getOperandNo();
13890     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13891       // Look pass truncate.
13892       UOpNo = User->use_begin().getOperandNo();
13893       User = *User->use_begin();
13894     }
13895
13896     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13897         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13898       return true;
13899   }
13900   return false;
13901 }
13902
13903 /// Emit nodes that will be selected as "test Op0,Op0", or something
13904 /// equivalent.
13905 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13906                                     SelectionDAG &DAG) const {
13907   if (Op.getValueType() == MVT::i1) {
13908     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13909     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13910                        DAG.getConstant(0, dl, MVT::i8));
13911   }
13912   // CF and OF aren't always set the way we want. Determine which
13913   // of these we need.
13914   bool NeedCF = false;
13915   bool NeedOF = false;
13916   switch (X86CC) {
13917   default: break;
13918   case X86::COND_A: case X86::COND_AE:
13919   case X86::COND_B: case X86::COND_BE:
13920     NeedCF = true;
13921     break;
13922   case X86::COND_G: case X86::COND_GE:
13923   case X86::COND_L: case X86::COND_LE:
13924   case X86::COND_O: case X86::COND_NO: {
13925     // Check if we really need to set the
13926     // Overflow flag. If NoSignedWrap is present
13927     // that is not actually needed.
13928     switch (Op->getOpcode()) {
13929     case ISD::ADD:
13930     case ISD::SUB:
13931     case ISD::MUL:
13932     case ISD::SHL: {
13933       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13934       if (BinNode->Flags.hasNoSignedWrap())
13935         break;
13936     }
13937     default:
13938       NeedOF = true;
13939       break;
13940     }
13941     break;
13942   }
13943   }
13944   // See if we can use the EFLAGS value from the operand instead of
13945   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13946   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13947   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13948     // Emit a CMP with 0, which is the TEST pattern.
13949     //if (Op.getValueType() == MVT::i1)
13950     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13951     //                     DAG.getConstant(0, MVT::i1));
13952     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13953                        DAG.getConstant(0, dl, Op.getValueType()));
13954   }
13955   unsigned Opcode = 0;
13956   unsigned NumOperands = 0;
13957
13958   // Truncate operations may prevent the merge of the SETCC instruction
13959   // and the arithmetic instruction before it. Attempt to truncate the operands
13960   // of the arithmetic instruction and use a reduced bit-width instruction.
13961   bool NeedTruncation = false;
13962   SDValue ArithOp = Op;
13963   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13964     SDValue Arith = Op->getOperand(0);
13965     // Both the trunc and the arithmetic op need to have one user each.
13966     if (Arith->hasOneUse())
13967       switch (Arith.getOpcode()) {
13968         default: break;
13969         case ISD::ADD:
13970         case ISD::SUB:
13971         case ISD::AND:
13972         case ISD::OR:
13973         case ISD::XOR: {
13974           NeedTruncation = true;
13975           ArithOp = Arith;
13976         }
13977       }
13978   }
13979
13980   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13981   // which may be the result of a CAST.  We use the variable 'Op', which is the
13982   // non-casted variable when we check for possible users.
13983   switch (ArithOp.getOpcode()) {
13984   case ISD::ADD:
13985     // Due to an isel shortcoming, be conservative if this add is likely to be
13986     // selected as part of a load-modify-store instruction. When the root node
13987     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13988     // uses of other nodes in the match, such as the ADD in this case. This
13989     // leads to the ADD being left around and reselected, with the result being
13990     // two adds in the output.  Alas, even if none our users are stores, that
13991     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13992     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13993     // climbing the DAG back to the root, and it doesn't seem to be worth the
13994     // effort.
13995     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13996          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13997       if (UI->getOpcode() != ISD::CopyToReg &&
13998           UI->getOpcode() != ISD::SETCC &&
13999           UI->getOpcode() != ISD::STORE)
14000         goto default_case;
14001
14002     if (ConstantSDNode *C =
14003         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14004       // An add of one will be selected as an INC.
14005       if (C->isOne() && !Subtarget->slowIncDec()) {
14006         Opcode = X86ISD::INC;
14007         NumOperands = 1;
14008         break;
14009       }
14010
14011       // An add of negative one (subtract of one) will be selected as a DEC.
14012       if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
14013         Opcode = X86ISD::DEC;
14014         NumOperands = 1;
14015         break;
14016       }
14017     }
14018
14019     // Otherwise use a regular EFLAGS-setting add.
14020     Opcode = X86ISD::ADD;
14021     NumOperands = 2;
14022     break;
14023   case ISD::SHL:
14024   case ISD::SRL:
14025     // If we have a constant logical shift that's only used in a comparison
14026     // against zero turn it into an equivalent AND. This allows turning it into
14027     // a TEST instruction later.
14028     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14029         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14030       EVT VT = Op.getValueType();
14031       unsigned BitWidth = VT.getSizeInBits();
14032       unsigned ShAmt = Op->getConstantOperandVal(1);
14033       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14034         break;
14035       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14036                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14037                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14038       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14039         break;
14040       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14041                                 DAG.getConstant(Mask, dl, VT));
14042       DAG.ReplaceAllUsesWith(Op, New);
14043       Op = New;
14044     }
14045     break;
14046
14047   case ISD::AND:
14048     // If the primary and result isn't used, don't bother using X86ISD::AND,
14049     // because a TEST instruction will be better.
14050     if (!hasNonFlagsUse(Op))
14051       break;
14052     // FALL THROUGH
14053   case ISD::SUB:
14054   case ISD::OR:
14055   case ISD::XOR:
14056     // Due to the ISEL shortcoming noted above, be conservative if this op is
14057     // likely to be selected as part of a load-modify-store instruction.
14058     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14059            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14060       if (UI->getOpcode() == ISD::STORE)
14061         goto default_case;
14062
14063     // Otherwise use a regular EFLAGS-setting instruction.
14064     switch (ArithOp.getOpcode()) {
14065     default: llvm_unreachable("unexpected operator!");
14066     case ISD::SUB: Opcode = X86ISD::SUB; break;
14067     case ISD::XOR: Opcode = X86ISD::XOR; break;
14068     case ISD::AND: Opcode = X86ISD::AND; break;
14069     case ISD::OR: {
14070       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14071         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14072         if (EFLAGS.getNode())
14073           return EFLAGS;
14074       }
14075       Opcode = X86ISD::OR;
14076       break;
14077     }
14078     }
14079
14080     NumOperands = 2;
14081     break;
14082   case X86ISD::ADD:
14083   case X86ISD::SUB:
14084   case X86ISD::INC:
14085   case X86ISD::DEC:
14086   case X86ISD::OR:
14087   case X86ISD::XOR:
14088   case X86ISD::AND:
14089     return SDValue(Op.getNode(), 1);
14090   default:
14091   default_case:
14092     break;
14093   }
14094
14095   // If we found that truncation is beneficial, perform the truncation and
14096   // update 'Op'.
14097   if (NeedTruncation) {
14098     EVT VT = Op.getValueType();
14099     SDValue WideVal = Op->getOperand(0);
14100     EVT WideVT = WideVal.getValueType();
14101     unsigned ConvertedOp = 0;
14102     // Use a target machine opcode to prevent further DAGCombine
14103     // optimizations that may separate the arithmetic operations
14104     // from the setcc node.
14105     switch (WideVal.getOpcode()) {
14106       default: break;
14107       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14108       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14109       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14110       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14111       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14112     }
14113
14114     if (ConvertedOp) {
14115       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14116       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14117         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14118         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14119         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14120       }
14121     }
14122   }
14123
14124   if (Opcode == 0)
14125     // Emit a CMP with 0, which is the TEST pattern.
14126     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14127                        DAG.getConstant(0, dl, Op.getValueType()));
14128
14129   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14130   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
14131
14132   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14133   DAG.ReplaceAllUsesWith(Op, New);
14134   return SDValue(New.getNode(), 1);
14135 }
14136
14137 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14138 /// equivalent.
14139 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14140                                    SDLoc dl, SelectionDAG &DAG) const {
14141   if (isNullConstant(Op1))
14142     return EmitTest(Op0, X86CC, dl, DAG);
14143
14144   assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14145          "Unexpected comparison operation for MVT::i1 operands");
14146
14147   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14148        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14149     // Do the comparison at i32 if it's smaller, besides the Atom case.
14150     // This avoids subregister aliasing issues. Keep the smaller reference
14151     // if we're optimizing for size, however, as that'll allow better folding
14152     // of memory operations.
14153     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14154         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14155         !Subtarget->isAtom()) {
14156       unsigned ExtendOp =
14157           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14158       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14159       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14160     }
14161     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14162     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14163     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14164                               Op0, Op1);
14165     return SDValue(Sub.getNode(), 1);
14166   }
14167   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14168 }
14169
14170 /// Convert a comparison if required by the subtarget.
14171 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14172                                                  SelectionDAG &DAG) const {
14173   // If the subtarget does not support the FUCOMI instruction, floating-point
14174   // comparisons have to be converted.
14175   if (Subtarget->hasCMov() ||
14176       Cmp.getOpcode() != X86ISD::CMP ||
14177       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14178       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14179     return Cmp;
14180
14181   // The instruction selector will select an FUCOM instruction instead of
14182   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14183   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14184   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14185   SDLoc dl(Cmp);
14186   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14187   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14188   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14189                             DAG.getConstant(8, dl, MVT::i8));
14190   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14191
14192   // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14193   assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14194   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14195 }
14196
14197 /// The minimum architected relative accuracy is 2^-12. We need one
14198 /// Newton-Raphson step to have a good float result (24 bits of precision).
14199 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14200                                             DAGCombinerInfo &DCI,
14201                                             unsigned &RefinementSteps,
14202                                             bool &UseOneConstNR) const {
14203   EVT VT = Op.getValueType();
14204   const char *RecipOp;
14205
14206   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14207   // TODO: Add support for AVX512 (v16f32).
14208   // It is likely not profitable to do this for f64 because a double-precision
14209   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14210   // instructions: convert to single, rsqrtss, convert back to double, refine
14211   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14212   // along with FMA, this could be a throughput win.
14213   if (VT == MVT::f32 && Subtarget->hasSSE1())
14214     RecipOp = "sqrtf";
14215   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14216            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14217     RecipOp = "vec-sqrtf";
14218   else
14219     return SDValue();
14220
14221   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14222   if (!Recips.isEnabled(RecipOp))
14223     return SDValue();
14224
14225   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14226   UseOneConstNR = false;
14227   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14228 }
14229
14230 /// The minimum architected relative accuracy is 2^-12. We need one
14231 /// Newton-Raphson step to have a good float result (24 bits of precision).
14232 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14233                                             DAGCombinerInfo &DCI,
14234                                             unsigned &RefinementSteps) const {
14235   EVT VT = Op.getValueType();
14236   const char *RecipOp;
14237
14238   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14239   // TODO: Add support for AVX512 (v16f32).
14240   // It is likely not profitable to do this for f64 because a double-precision
14241   // reciprocal estimate with refinement on x86 prior to FMA requires
14242   // 15 instructions: convert to single, rcpss, convert back to double, refine
14243   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14244   // along with FMA, this could be a throughput win.
14245   if (VT == MVT::f32 && Subtarget->hasSSE1())
14246     RecipOp = "divf";
14247   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14248            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14249     RecipOp = "vec-divf";
14250   else
14251     return SDValue();
14252
14253   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14254   if (!Recips.isEnabled(RecipOp))
14255     return SDValue();
14256
14257   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14258   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14259 }
14260
14261 /// If we have at least two divisions that use the same divisor, convert to
14262 /// multplication by a reciprocal. This may need to be adjusted for a given
14263 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14264 /// This is because we still need one division to calculate the reciprocal and
14265 /// then we need two multiplies by that reciprocal as replacements for the
14266 /// original divisions.
14267 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14268   return 2;
14269 }
14270
14271 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14272 /// if it's possible.
14273 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14274                                      SDLoc dl, SelectionDAG &DAG) const {
14275   SDValue Op0 = And.getOperand(0);
14276   SDValue Op1 = And.getOperand(1);
14277   if (Op0.getOpcode() == ISD::TRUNCATE)
14278     Op0 = Op0.getOperand(0);
14279   if (Op1.getOpcode() == ISD::TRUNCATE)
14280     Op1 = Op1.getOperand(0);
14281
14282   SDValue LHS, RHS;
14283   if (Op1.getOpcode() == ISD::SHL)
14284     std::swap(Op0, Op1);
14285   if (Op0.getOpcode() == ISD::SHL) {
14286     if (isOneConstant(Op0.getOperand(0))) {
14287         // If we looked past a truncate, check that it's only truncating away
14288         // known zeros.
14289         unsigned BitWidth = Op0.getValueSizeInBits();
14290         unsigned AndBitWidth = And.getValueSizeInBits();
14291         if (BitWidth > AndBitWidth) {
14292           APInt Zeros, Ones;
14293           DAG.computeKnownBits(Op0, Zeros, Ones);
14294           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14295             return SDValue();
14296         }
14297         LHS = Op1;
14298         RHS = Op0.getOperand(1);
14299       }
14300   } else if (Op1.getOpcode() == ISD::Constant) {
14301     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14302     uint64_t AndRHSVal = AndRHS->getZExtValue();
14303     SDValue AndLHS = Op0;
14304
14305     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14306       LHS = AndLHS.getOperand(0);
14307       RHS = AndLHS.getOperand(1);
14308     }
14309
14310     // Use BT if the immediate can't be encoded in a TEST instruction.
14311     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14312       LHS = AndLHS;
14313       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14314     }
14315   }
14316
14317   if (LHS.getNode()) {
14318     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
14319     // instruction.  Since the shift amount is in-range-or-undefined, we know
14320     // that doing a bittest on the i32 value is ok.  We extend to i32 because
14321     // the encoding for the i16 version is larger than the i32 version.
14322     // Also promote i16 to i32 for performance / code size reason.
14323     if (LHS.getValueType() == MVT::i8 ||
14324         LHS.getValueType() == MVT::i16)
14325       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14326
14327     // If the operand types disagree, extend the shift amount to match.  Since
14328     // BT ignores high bits (like shifts) we can use anyextend.
14329     if (LHS.getValueType() != RHS.getValueType())
14330       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14331
14332     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14333     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14334     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14335                        DAG.getConstant(Cond, dl, MVT::i8), BT);
14336   }
14337
14338   return SDValue();
14339 }
14340
14341 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14342 /// mask CMPs.
14343 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14344                               SDValue &Op1) {
14345   unsigned SSECC;
14346   bool Swap = false;
14347
14348   // SSE Condition code mapping:
14349   //  0 - EQ
14350   //  1 - LT
14351   //  2 - LE
14352   //  3 - UNORD
14353   //  4 - NEQ
14354   //  5 - NLT
14355   //  6 - NLE
14356   //  7 - ORD
14357   switch (SetCCOpcode) {
14358   default: llvm_unreachable("Unexpected SETCC condition");
14359   case ISD::SETOEQ:
14360   case ISD::SETEQ:  SSECC = 0; break;
14361   case ISD::SETOGT:
14362   case ISD::SETGT:  Swap = true; // Fallthrough
14363   case ISD::SETLT:
14364   case ISD::SETOLT: SSECC = 1; break;
14365   case ISD::SETOGE:
14366   case ISD::SETGE:  Swap = true; // Fallthrough
14367   case ISD::SETLE:
14368   case ISD::SETOLE: SSECC = 2; break;
14369   case ISD::SETUO:  SSECC = 3; break;
14370   case ISD::SETUNE:
14371   case ISD::SETNE:  SSECC = 4; break;
14372   case ISD::SETULE: Swap = true; // Fallthrough
14373   case ISD::SETUGE: SSECC = 5; break;
14374   case ISD::SETULT: Swap = true; // Fallthrough
14375   case ISD::SETUGT: SSECC = 6; break;
14376   case ISD::SETO:   SSECC = 7; break;
14377   case ISD::SETUEQ:
14378   case ISD::SETONE: SSECC = 8; break;
14379   }
14380   if (Swap)
14381     std::swap(Op0, Op1);
14382
14383   return SSECC;
14384 }
14385
14386 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14387 // ones, and then concatenate the result back.
14388 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14389   MVT VT = Op.getSimpleValueType();
14390
14391   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14392          "Unsupported value type for operation");
14393
14394   unsigned NumElems = VT.getVectorNumElements();
14395   SDLoc dl(Op);
14396   SDValue CC = Op.getOperand(2);
14397
14398   // Extract the LHS vectors
14399   SDValue LHS = Op.getOperand(0);
14400   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14401   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14402
14403   // Extract the RHS vectors
14404   SDValue RHS = Op.getOperand(1);
14405   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14406   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14407
14408   // Issue the operation on the smaller types and concatenate the result back
14409   MVT EltVT = VT.getVectorElementType();
14410   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14411   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14412                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14413                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14414 }
14415
14416 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14417   SDValue Op0 = Op.getOperand(0);
14418   SDValue Op1 = Op.getOperand(1);
14419   SDValue CC = Op.getOperand(2);
14420   MVT VT = Op.getSimpleValueType();
14421   SDLoc dl(Op);
14422
14423   assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14424          "Unexpected type for boolean compare operation");
14425   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14426   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14427                                DAG.getConstant(-1, dl, VT));
14428   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14429                                DAG.getConstant(-1, dl, VT));
14430   switch (SetCCOpcode) {
14431   default: llvm_unreachable("Unexpected SETCC condition");
14432   case ISD::SETEQ:
14433     // (x == y) -> ~(x ^ y)
14434     return DAG.getNode(ISD::XOR, dl, VT,
14435                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14436                        DAG.getConstant(-1, dl, VT));
14437   case ISD::SETNE:
14438     // (x != y) -> (x ^ y)
14439     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14440   case ISD::SETUGT:
14441   case ISD::SETGT:
14442     // (x > y) -> (x & ~y)
14443     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14444   case ISD::SETULT:
14445   case ISD::SETLT:
14446     // (x < y) -> (~x & y)
14447     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14448   case ISD::SETULE:
14449   case ISD::SETLE:
14450     // (x <= y) -> (~x | y)
14451     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14452   case ISD::SETUGE:
14453   case ISD::SETGE:
14454     // (x >=y) -> (x | ~y)
14455     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14456   }
14457 }
14458
14459 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14460                                      const X86Subtarget *Subtarget) {
14461   SDValue Op0 = Op.getOperand(0);
14462   SDValue Op1 = Op.getOperand(1);
14463   SDValue CC = Op.getOperand(2);
14464   MVT VT = Op.getSimpleValueType();
14465   SDLoc dl(Op);
14466
14467   assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14468          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14469          "Cannot set masked compare for this operation");
14470
14471   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14472   unsigned  Opc = 0;
14473   bool Unsigned = false;
14474   bool Swap = false;
14475   unsigned SSECC;
14476   switch (SetCCOpcode) {
14477   default: llvm_unreachable("Unexpected SETCC condition");
14478   case ISD::SETNE:  SSECC = 4; break;
14479   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14480   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14481   case ISD::SETLT:  Swap = true; //fall-through
14482   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14483   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14484   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14485   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14486   case ISD::SETULE: Unsigned = true; //fall-through
14487   case ISD::SETLE:  SSECC = 2; break;
14488   }
14489
14490   if (Swap)
14491     std::swap(Op0, Op1);
14492   if (Opc)
14493     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14494   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14495   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14496                      DAG.getConstant(SSECC, dl, MVT::i8));
14497 }
14498
14499 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14500 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14501 /// return an empty value.
14502 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14503 {
14504   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14505   if (!BV)
14506     return SDValue();
14507
14508   MVT VT = Op1.getSimpleValueType();
14509   MVT EVT = VT.getVectorElementType();
14510   unsigned n = VT.getVectorNumElements();
14511   SmallVector<SDValue, 8> ULTOp1;
14512
14513   for (unsigned i = 0; i < n; ++i) {
14514     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14515     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14516       return SDValue();
14517
14518     // Avoid underflow.
14519     APInt Val = Elt->getAPIntValue();
14520     if (Val == 0)
14521       return SDValue();
14522
14523     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14524   }
14525
14526   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14527 }
14528
14529 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14530                            SelectionDAG &DAG) {
14531   SDValue Op0 = Op.getOperand(0);
14532   SDValue Op1 = Op.getOperand(1);
14533   SDValue CC = Op.getOperand(2);
14534   MVT VT = Op.getSimpleValueType();
14535   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14536   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14537   SDLoc dl(Op);
14538
14539   if (isFP) {
14540 #ifndef NDEBUG
14541     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14542     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14543 #endif
14544
14545     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14546     unsigned Opc = X86ISD::CMPP;
14547     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14548       assert(VT.getVectorNumElements() <= 16);
14549       Opc = X86ISD::CMPM;
14550     }
14551     // In the two special cases we can't handle, emit two comparisons.
14552     if (SSECC == 8) {
14553       unsigned CC0, CC1;
14554       unsigned CombineOpc;
14555       if (SetCCOpcode == ISD::SETUEQ) {
14556         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14557       } else {
14558         assert(SetCCOpcode == ISD::SETONE);
14559         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14560       }
14561
14562       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14563                                  DAG.getConstant(CC0, dl, MVT::i8));
14564       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14565                                  DAG.getConstant(CC1, dl, MVT::i8));
14566       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14567     }
14568     // Handle all other FP comparisons here.
14569     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14570                        DAG.getConstant(SSECC, dl, MVT::i8));
14571   }
14572
14573   MVT VTOp0 = Op0.getSimpleValueType();
14574   assert(VTOp0 == Op1.getSimpleValueType() &&
14575          "Expected operands with same type!");
14576   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14577          "Invalid number of packed elements for source and destination!");
14578
14579   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14580     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14581     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14582     // legalizer firstly checks if the first operand in input to the setcc has
14583     // a legal type. If so, then it promotes the return type to that same type.
14584     // Otherwise, the return type is promoted to the 'next legal type' which,
14585     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14586     //
14587     // We reach this code only if the following two conditions are met:
14588     // 1. Both return type and operand type have been promoted to wider types
14589     //    by the type legalizer.
14590     // 2. The original operand type has been promoted to a 256-bit vector.
14591     //
14592     // Note that condition 2. only applies for AVX targets.
14593     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14594     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14595   }
14596
14597   // The non-AVX512 code below works under the assumption that source and
14598   // destination types are the same.
14599   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14600          "Value types for source and destination must be the same!");
14601
14602   // Break 256-bit integer vector compare into smaller ones.
14603   if (VT.is256BitVector() && !Subtarget->hasInt256())
14604     return Lower256IntVSETCC(Op, DAG);
14605
14606   MVT OpVT = Op1.getSimpleValueType();
14607   if (OpVT.getVectorElementType() == MVT::i1)
14608     return LowerBoolVSETCC_AVX512(Op, DAG);
14609
14610   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14611   if (Subtarget->hasAVX512()) {
14612     if (Op1.getSimpleValueType().is512BitVector() ||
14613         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14614         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14615       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14616
14617     // In AVX-512 architecture setcc returns mask with i1 elements,
14618     // But there is no compare instruction for i8 and i16 elements in KNL.
14619     // We are not talking about 512-bit operands in this case, these
14620     // types are illegal.
14621     if (MaskResult &&
14622         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14623          OpVT.getVectorElementType().getSizeInBits() >= 8))
14624       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14625                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14626   }
14627
14628   // Lower using XOP integer comparisons.
14629   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14630        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14631     // Translate compare code to XOP PCOM compare mode.
14632     unsigned CmpMode = 0;
14633     switch (SetCCOpcode) {
14634     default: llvm_unreachable("Unexpected SETCC condition");
14635     case ISD::SETULT:
14636     case ISD::SETLT: CmpMode = 0x00; break;
14637     case ISD::SETULE:
14638     case ISD::SETLE: CmpMode = 0x01; break;
14639     case ISD::SETUGT:
14640     case ISD::SETGT: CmpMode = 0x02; break;
14641     case ISD::SETUGE:
14642     case ISD::SETGE: CmpMode = 0x03; break;
14643     case ISD::SETEQ: CmpMode = 0x04; break;
14644     case ISD::SETNE: CmpMode = 0x05; break;
14645     }
14646
14647     // Are we comparing unsigned or signed integers?
14648     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14649       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14650
14651     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14652                        DAG.getConstant(CmpMode, dl, MVT::i8));
14653   }
14654
14655   // We are handling one of the integer comparisons here.  Since SSE only has
14656   // GT and EQ comparisons for integer, swapping operands and multiple
14657   // operations may be required for some comparisons.
14658   unsigned Opc;
14659   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14660   bool Subus = false;
14661
14662   switch (SetCCOpcode) {
14663   default: llvm_unreachable("Unexpected SETCC condition");
14664   case ISD::SETNE:  Invert = true;
14665   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14666   case ISD::SETLT:  Swap = true;
14667   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14668   case ISD::SETGE:  Swap = true;
14669   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14670                     Invert = true; break;
14671   case ISD::SETULT: Swap = true;
14672   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14673                     FlipSigns = true; break;
14674   case ISD::SETUGE: Swap = true;
14675   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14676                     FlipSigns = true; Invert = true; break;
14677   }
14678
14679   // Special case: Use min/max operations for SETULE/SETUGE
14680   MVT VET = VT.getVectorElementType();
14681   bool hasMinMax =
14682        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14683     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14684
14685   if (hasMinMax) {
14686     switch (SetCCOpcode) {
14687     default: break;
14688     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14689     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14690     }
14691
14692     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14693   }
14694
14695   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14696   if (!MinMax && hasSubus) {
14697     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14698     // Op0 u<= Op1:
14699     //   t = psubus Op0, Op1
14700     //   pcmpeq t, <0..0>
14701     switch (SetCCOpcode) {
14702     default: break;
14703     case ISD::SETULT: {
14704       // If the comparison is against a constant we can turn this into a
14705       // setule.  With psubus, setule does not require a swap.  This is
14706       // beneficial because the constant in the register is no longer
14707       // destructed as the destination so it can be hoisted out of a loop.
14708       // Only do this pre-AVX since vpcmp* is no longer destructive.
14709       if (Subtarget->hasAVX())
14710         break;
14711       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14712       if (ULEOp1.getNode()) {
14713         Op1 = ULEOp1;
14714         Subus = true; Invert = false; Swap = false;
14715       }
14716       break;
14717     }
14718     // Psubus is better than flip-sign because it requires no inversion.
14719     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14720     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14721     }
14722
14723     if (Subus) {
14724       Opc = X86ISD::SUBUS;
14725       FlipSigns = false;
14726     }
14727   }
14728
14729   if (Swap)
14730     std::swap(Op0, Op1);
14731
14732   // Check that the operation in question is available (most are plain SSE2,
14733   // but PCMPGTQ and PCMPEQQ have different requirements).
14734   if (VT == MVT::v2i64) {
14735     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14736       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14737
14738       // First cast everything to the right type.
14739       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14740       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14741
14742       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14743       // bits of the inputs before performing those operations. The lower
14744       // compare is always unsigned.
14745       SDValue SB;
14746       if (FlipSigns) {
14747         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14748       } else {
14749         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14750         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14751         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14752                          Sign, Zero, Sign, Zero);
14753       }
14754       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14755       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14756
14757       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14758       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14759       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14760
14761       // Create masks for only the low parts/high parts of the 64 bit integers.
14762       static const int MaskHi[] = { 1, 1, 3, 3 };
14763       static const int MaskLo[] = { 0, 0, 2, 2 };
14764       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14765       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14766       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14767
14768       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14769       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14770
14771       if (Invert)
14772         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14773
14774       return DAG.getBitcast(VT, Result);
14775     }
14776
14777     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14778       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14779       // pcmpeqd + pshufd + pand.
14780       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14781
14782       // First cast everything to the right type.
14783       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14784       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14785
14786       // Do the compare.
14787       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14788
14789       // Make sure the lower and upper halves are both all-ones.
14790       static const int Mask[] = { 1, 0, 3, 2 };
14791       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14792       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14793
14794       if (Invert)
14795         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14796
14797       return DAG.getBitcast(VT, Result);
14798     }
14799   }
14800
14801   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14802   // bits of the inputs before performing those operations.
14803   if (FlipSigns) {
14804     MVT EltVT = VT.getVectorElementType();
14805     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14806                                  VT);
14807     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14808     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14809   }
14810
14811   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14812
14813   // If the logical-not of the result is required, perform that now.
14814   if (Invert)
14815     Result = DAG.getNOT(dl, Result, VT);
14816
14817   if (MinMax)
14818     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14819
14820   if (Subus)
14821     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14822                          getZeroVector(VT, Subtarget, DAG, dl));
14823
14824   return Result;
14825 }
14826
14827 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14828
14829   MVT VT = Op.getSimpleValueType();
14830
14831   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14832
14833   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14834          && "SetCC type must be 8-bit or 1-bit integer");
14835   SDValue Op0 = Op.getOperand(0);
14836   SDValue Op1 = Op.getOperand(1);
14837   SDLoc dl(Op);
14838   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14839
14840   // Optimize to BT if possible.
14841   // Lower (X & (1 << N)) == 0 to BT(X, N).
14842   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14843   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14844   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14845       isNullConstant(Op1) &&
14846       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14847     if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14848       if (VT == MVT::i1)
14849         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14850       return NewSetCC;
14851     }
14852   }
14853
14854   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14855   // these.
14856   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14857       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14858
14859     // If the input is a setcc, then reuse the input setcc or use a new one with
14860     // the inverted condition.
14861     if (Op0.getOpcode() == X86ISD::SETCC) {
14862       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14863       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14864       if (!Invert)
14865         return Op0;
14866
14867       CCode = X86::GetOppositeBranchCondition(CCode);
14868       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14869                                   DAG.getConstant(CCode, dl, MVT::i8),
14870                                   Op0.getOperand(1));
14871       if (VT == MVT::i1)
14872         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14873       return SetCC;
14874     }
14875   }
14876   if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14877       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14878
14879     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14880     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14881   }
14882
14883   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14884   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14885   if (X86CC == X86::COND_INVALID)
14886     return SDValue();
14887
14888   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14889   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14890   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14891                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14892   if (VT == MVT::i1)
14893     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14894   return SetCC;
14895 }
14896
14897 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14898   SDValue LHS = Op.getOperand(0);
14899   SDValue RHS = Op.getOperand(1);
14900   SDValue Carry = Op.getOperand(2);
14901   SDValue Cond = Op.getOperand(3);
14902   SDLoc DL(Op);
14903
14904   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14905   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14906
14907   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14908   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14909   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14910   return DAG.getNode(X86ISD::SETCC, DL, Op.getValueType(),
14911                      DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14912 }
14913
14914 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14915 static bool isX86LogicalCmp(SDValue Op) {
14916   unsigned Opc = Op.getNode()->getOpcode();
14917   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14918       Opc == X86ISD::SAHF)
14919     return true;
14920   if (Op.getResNo() == 1 &&
14921       (Opc == X86ISD::ADD ||
14922        Opc == X86ISD::SUB ||
14923        Opc == X86ISD::ADC ||
14924        Opc == X86ISD::SBB ||
14925        Opc == X86ISD::SMUL ||
14926        Opc == X86ISD::UMUL ||
14927        Opc == X86ISD::INC ||
14928        Opc == X86ISD::DEC ||
14929        Opc == X86ISD::OR ||
14930        Opc == X86ISD::XOR ||
14931        Opc == X86ISD::AND))
14932     return true;
14933
14934   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14935     return true;
14936
14937   return false;
14938 }
14939
14940 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14941   if (V.getOpcode() != ISD::TRUNCATE)
14942     return false;
14943
14944   SDValue VOp0 = V.getOperand(0);
14945   unsigned InBits = VOp0.getValueSizeInBits();
14946   unsigned Bits = V.getValueSizeInBits();
14947   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14948 }
14949
14950 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14951   bool addTest = true;
14952   SDValue Cond  = Op.getOperand(0);
14953   SDValue Op1 = Op.getOperand(1);
14954   SDValue Op2 = Op.getOperand(2);
14955   SDLoc DL(Op);
14956   MVT VT = Op1.getSimpleValueType();
14957   SDValue CC;
14958
14959   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14960   // are available or VBLENDV if AVX is available.
14961   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14962   if (Cond.getOpcode() == ISD::SETCC &&
14963       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14964        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14965       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
14966     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14967     int SSECC = translateX86FSETCC(
14968         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14969
14970     if (SSECC != 8) {
14971       if (Subtarget->hasAVX512()) {
14972         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14973                                   DAG.getConstant(SSECC, DL, MVT::i8));
14974         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14975       }
14976
14977       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14978                                 DAG.getConstant(SSECC, DL, MVT::i8));
14979
14980       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14981       // of 3 logic instructions for size savings and potentially speed.
14982       // Unfortunately, there is no scalar form of VBLENDV.
14983
14984       // If either operand is a constant, don't try this. We can expect to
14985       // optimize away at least one of the logic instructions later in that
14986       // case, so that sequence would be faster than a variable blend.
14987
14988       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14989       // uses XMM0 as the selection register. That may need just as many
14990       // instructions as the AND/ANDN/OR sequence due to register moves, so
14991       // don't bother.
14992
14993       if (Subtarget->hasAVX() &&
14994           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14995
14996         // Convert to vectors, do a VSELECT, and convert back to scalar.
14997         // All of the conversions should be optimized away.
14998
14999         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
15000         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
15001         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
15002         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
15003
15004         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
15005         VCmp = DAG.getBitcast(VCmpVT, VCmp);
15006
15007         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
15008
15009         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
15010                            VSel, DAG.getIntPtrConstant(0, DL));
15011       }
15012       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15013       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15014       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15015     }
15016   }
15017
15018   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
15019     SDValue Op1Scalar;
15020     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
15021       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
15022     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
15023       Op1Scalar = Op1.getOperand(0);
15024     SDValue Op2Scalar;
15025     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
15026       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
15027     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
15028       Op2Scalar = Op2.getOperand(0);
15029     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
15030       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
15031                                       Op1Scalar.getValueType(),
15032                                       Cond, Op1Scalar, Op2Scalar);
15033       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
15034         return DAG.getBitcast(VT, newSelect);
15035       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
15036       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
15037                          DAG.getIntPtrConstant(0, DL));
15038     }
15039   }
15040
15041   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
15042     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
15043     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15044                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
15045     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15046                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
15047     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
15048                                     Cond, Op1, Op2);
15049     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
15050   }
15051
15052   if (Cond.getOpcode() == ISD::SETCC) {
15053     SDValue NewCond = LowerSETCC(Cond, DAG);
15054     if (NewCond.getNode())
15055       Cond = NewCond;
15056   }
15057
15058   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15059   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15060   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15061   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15062   if (Cond.getOpcode() == X86ISD::SETCC &&
15063       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15064       isNullConstant(Cond.getOperand(1).getOperand(1))) {
15065     SDValue Cmp = Cond.getOperand(1);
15066
15067     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15068
15069     if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15070         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15071       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
15072
15073       SDValue CmpOp0 = Cmp.getOperand(0);
15074       // Apply further optimizations for special cases
15075       // (select (x != 0), -1, 0) -> neg & sbb
15076       // (select (x == 0), 0, -1) -> neg & sbb
15077       if (isNullConstant(Y) &&
15078             (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
15079           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15080           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15081                                     DAG.getConstant(0, DL,
15082                                                     CmpOp0.getValueType()),
15083                                     CmpOp0);
15084           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15085                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
15086                                     SDValue(Neg.getNode(), 1));
15087           return Res;
15088         }
15089
15090       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15091                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
15092       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15093
15094       SDValue Res =   // Res = 0 or -1.
15095         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15096                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
15097
15098       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
15099         Res = DAG.getNOT(DL, Res, Res.getValueType());
15100
15101       if (!isNullConstant(Op2))
15102         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15103       return Res;
15104     }
15105   }
15106
15107   // Look past (and (setcc_carry (cmp ...)), 1).
15108   if (Cond.getOpcode() == ISD::AND &&
15109       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15110       isOneConstant(Cond.getOperand(1)))
15111     Cond = Cond.getOperand(0);
15112
15113   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15114   // setting operand in place of the X86ISD::SETCC.
15115   unsigned CondOpcode = Cond.getOpcode();
15116   if (CondOpcode == X86ISD::SETCC ||
15117       CondOpcode == X86ISD::SETCC_CARRY) {
15118     CC = Cond.getOperand(0);
15119
15120     SDValue Cmp = Cond.getOperand(1);
15121     unsigned Opc = Cmp.getOpcode();
15122     MVT VT = Op.getSimpleValueType();
15123
15124     bool IllegalFPCMov = false;
15125     if (VT.isFloatingPoint() && !VT.isVector() &&
15126         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15127       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15128
15129     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15130         Opc == X86ISD::BT) { // FIXME
15131       Cond = Cmp;
15132       addTest = false;
15133     }
15134   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15135              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15136              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15137               Cond.getOperand(0).getValueType() != MVT::i8)) {
15138     SDValue LHS = Cond.getOperand(0);
15139     SDValue RHS = Cond.getOperand(1);
15140     unsigned X86Opcode;
15141     unsigned X86Cond;
15142     SDVTList VTs;
15143     switch (CondOpcode) {
15144     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15145     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15146     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15147     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15148     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15149     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15150     default: llvm_unreachable("unexpected overflowing operator");
15151     }
15152     if (CondOpcode == ISD::UMULO)
15153       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15154                           MVT::i32);
15155     else
15156       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15157
15158     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15159
15160     if (CondOpcode == ISD::UMULO)
15161       Cond = X86Op.getValue(2);
15162     else
15163       Cond = X86Op.getValue(1);
15164
15165     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15166     addTest = false;
15167   }
15168
15169   if (addTest) {
15170     // Look past the truncate if the high bits are known zero.
15171     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15172       Cond = Cond.getOperand(0);
15173
15174     // We know the result of AND is compared against zero. Try to match
15175     // it to BT.
15176     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15177       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
15178         CC = NewSetCC.getOperand(0);
15179         Cond = NewSetCC.getOperand(1);
15180         addTest = false;
15181       }
15182     }
15183   }
15184
15185   if (addTest) {
15186     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
15187     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15188   }
15189
15190   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15191   // a <  b ?  0 : -1 -> RES = setcc_carry
15192   // a >= b ? -1 :  0 -> RES = setcc_carry
15193   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15194   if (Cond.getOpcode() == X86ISD::SUB) {
15195     Cond = ConvertCmpIfNecessary(Cond, DAG);
15196     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15197
15198     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15199         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15200         (isNullConstant(Op1) || isNullConstant(Op2))) {
15201       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15202                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15203                                 Cond);
15204       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15205         return DAG.getNOT(DL, Res, Res.getValueType());
15206       return Res;
15207     }
15208   }
15209
15210   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15211   // widen the cmov and push the truncate through. This avoids introducing a new
15212   // branch during isel and doesn't add any extensions.
15213   if (Op.getValueType() == MVT::i8 &&
15214       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15215     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15216     if (T1.getValueType() == T2.getValueType() &&
15217         // Blacklist CopyFromReg to avoid partial register stalls.
15218         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15219       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15220       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15221       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15222     }
15223   }
15224
15225   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15226   // condition is true.
15227   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15228   SDValue Ops[] = { Op2, Op1, CC, Cond };
15229   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15230 }
15231
15232 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15233                                        const X86Subtarget *Subtarget,
15234                                        SelectionDAG &DAG) {
15235   MVT VT = Op->getSimpleValueType(0);
15236   SDValue In = Op->getOperand(0);
15237   MVT InVT = In.getSimpleValueType();
15238   MVT VTElt = VT.getVectorElementType();
15239   MVT InVTElt = InVT.getVectorElementType();
15240   SDLoc dl(Op);
15241
15242   // SKX processor
15243   if ((InVTElt == MVT::i1) &&
15244       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15245         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15246
15247        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15248         VTElt.getSizeInBits() <= 16)) ||
15249
15250        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15251         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15252
15253        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15254         VTElt.getSizeInBits() >= 32))))
15255     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15256
15257   unsigned int NumElts = VT.getVectorNumElements();
15258
15259   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15260     return SDValue();
15261
15262   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15263     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15264       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15265     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15266   }
15267
15268   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15269   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15270   SDValue NegOne =
15271    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15272                    ExtVT);
15273   SDValue Zero =
15274    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15275
15276   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15277   if (VT.is512BitVector())
15278     return V;
15279   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15280 }
15281
15282 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15283                                              const X86Subtarget *Subtarget,
15284                                              SelectionDAG &DAG) {
15285   SDValue In = Op->getOperand(0);
15286   MVT VT = Op->getSimpleValueType(0);
15287   MVT InVT = In.getSimpleValueType();
15288   assert(VT.getSizeInBits() == InVT.getSizeInBits());
15289
15290   MVT InSVT = InVT.getVectorElementType();
15291   assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15292
15293   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15294     return SDValue();
15295   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15296     return SDValue();
15297
15298   SDLoc dl(Op);
15299
15300   // SSE41 targets can use the pmovsx* instructions directly.
15301   if (Subtarget->hasSSE41())
15302     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15303
15304   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15305   SDValue Curr = In;
15306   MVT CurrVT = InVT;
15307
15308   // As SRAI is only available on i16/i32 types, we expand only up to i32
15309   // and handle i64 separately.
15310   while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15311     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15312     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15313     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15314     Curr = DAG.getBitcast(CurrVT, Curr);
15315   }
15316
15317   SDValue SignExt = Curr;
15318   if (CurrVT != InVT) {
15319     unsigned SignExtShift =
15320         CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15321     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15322                           DAG.getConstant(SignExtShift, dl, MVT::i8));
15323   }
15324
15325   if (CurrVT == VT)
15326     return SignExt;
15327
15328   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15329     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15330                                DAG.getConstant(31, dl, MVT::i8));
15331     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15332     return DAG.getBitcast(VT, Ext);
15333   }
15334
15335   return SDValue();
15336 }
15337
15338 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15339                                 SelectionDAG &DAG) {
15340   MVT VT = Op->getSimpleValueType(0);
15341   SDValue In = Op->getOperand(0);
15342   MVT InVT = In.getSimpleValueType();
15343   SDLoc dl(Op);
15344
15345   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15346     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15347
15348   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15349       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15350       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15351     return SDValue();
15352
15353   if (Subtarget->hasInt256())
15354     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15355
15356   // Optimize vectors in AVX mode
15357   // Sign extend  v8i16 to v8i32 and
15358   //              v4i32 to v4i64
15359   //
15360   // Divide input vector into two parts
15361   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15362   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15363   // concat the vectors to original VT
15364
15365   unsigned NumElems = InVT.getVectorNumElements();
15366   SDValue Undef = DAG.getUNDEF(InVT);
15367
15368   SmallVector<int,8> ShufMask1(NumElems, -1);
15369   for (unsigned i = 0; i != NumElems/2; ++i)
15370     ShufMask1[i] = i;
15371
15372   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15373
15374   SmallVector<int,8> ShufMask2(NumElems, -1);
15375   for (unsigned i = 0; i != NumElems/2; ++i)
15376     ShufMask2[i] = i + NumElems/2;
15377
15378   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15379
15380   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15381                                 VT.getVectorNumElements()/2);
15382
15383   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15384   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15385
15386   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15387 }
15388
15389 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15390 // may emit an illegal shuffle but the expansion is still better than scalar
15391 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15392 // we'll emit a shuffle and a arithmetic shift.
15393 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15394 // TODO: It is possible to support ZExt by zeroing the undef values during
15395 // the shuffle phase or after the shuffle.
15396 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15397                                  SelectionDAG &DAG) {
15398   MVT RegVT = Op.getSimpleValueType();
15399   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15400   assert(RegVT.isInteger() &&
15401          "We only custom lower integer vector sext loads.");
15402
15403   // Nothing useful we can do without SSE2 shuffles.
15404   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15405
15406   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15407   SDLoc dl(Ld);
15408   EVT MemVT = Ld->getMemoryVT();
15409   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15410   unsigned RegSz = RegVT.getSizeInBits();
15411
15412   ISD::LoadExtType Ext = Ld->getExtensionType();
15413
15414   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15415          && "Only anyext and sext are currently implemented.");
15416   assert(MemVT != RegVT && "Cannot extend to the same type");
15417   assert(MemVT.isVector() && "Must load a vector from memory");
15418
15419   unsigned NumElems = RegVT.getVectorNumElements();
15420   unsigned MemSz = MemVT.getSizeInBits();
15421   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15422
15423   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15424     // The only way in which we have a legal 256-bit vector result but not the
15425     // integer 256-bit operations needed to directly lower a sextload is if we
15426     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15427     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15428     // correctly legalized. We do this late to allow the canonical form of
15429     // sextload to persist throughout the rest of the DAG combiner -- it wants
15430     // to fold together any extensions it can, and so will fuse a sign_extend
15431     // of an sextload into a sextload targeting a wider value.
15432     SDValue Load;
15433     if (MemSz == 128) {
15434       // Just switch this to a normal load.
15435       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15436                                        "it must be a legal 128-bit vector "
15437                                        "type!");
15438       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15439                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15440                   Ld->isInvariant(), Ld->getAlignment());
15441     } else {
15442       assert(MemSz < 128 &&
15443              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15444       // Do an sext load to a 128-bit vector type. We want to use the same
15445       // number of elements, but elements half as wide. This will end up being
15446       // recursively lowered by this routine, but will succeed as we definitely
15447       // have all the necessary features if we're using AVX1.
15448       EVT HalfEltVT =
15449           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15450       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15451       Load =
15452           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15453                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15454                          Ld->isNonTemporal(), Ld->isInvariant(),
15455                          Ld->getAlignment());
15456     }
15457
15458     // Replace chain users with the new chain.
15459     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15460     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15461
15462     // Finally, do a normal sign-extend to the desired register.
15463     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15464   }
15465
15466   // All sizes must be a power of two.
15467   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15468          "Non-power-of-two elements are not custom lowered!");
15469
15470   // Attempt to load the original value using scalar loads.
15471   // Find the largest scalar type that divides the total loaded size.
15472   MVT SclrLoadTy = MVT::i8;
15473   for (MVT Tp : MVT::integer_valuetypes()) {
15474     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15475       SclrLoadTy = Tp;
15476     }
15477   }
15478
15479   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15480   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15481       (64 <= MemSz))
15482     SclrLoadTy = MVT::f64;
15483
15484   // Calculate the number of scalar loads that we need to perform
15485   // in order to load our vector from memory.
15486   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15487
15488   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15489          "Can only lower sext loads with a single scalar load!");
15490
15491   unsigned loadRegZize = RegSz;
15492   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15493     loadRegZize = 128;
15494
15495   // Represent our vector as a sequence of elements which are the
15496   // largest scalar that we can load.
15497   EVT LoadUnitVecVT = EVT::getVectorVT(
15498       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15499
15500   // Represent the data using the same element type that is stored in
15501   // memory. In practice, we ''widen'' MemVT.
15502   EVT WideVecVT =
15503       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15504                        loadRegZize / MemVT.getScalarSizeInBits());
15505
15506   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15507          "Invalid vector type");
15508
15509   // We can't shuffle using an illegal type.
15510   assert(TLI.isTypeLegal(WideVecVT) &&
15511          "We only lower types that form legal widened vector types");
15512
15513   SmallVector<SDValue, 8> Chains;
15514   SDValue Ptr = Ld->getBasePtr();
15515   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15516                                       TLI.getPointerTy(DAG.getDataLayout()));
15517   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15518
15519   for (unsigned i = 0; i < NumLoads; ++i) {
15520     // Perform a single load.
15521     SDValue ScalarLoad =
15522         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15523                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15524                     Ld->getAlignment());
15525     Chains.push_back(ScalarLoad.getValue(1));
15526     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15527     // another round of DAGCombining.
15528     if (i == 0)
15529       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15530     else
15531       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15532                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15533
15534     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15535   }
15536
15537   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15538
15539   // Bitcast the loaded value to a vector of the original element type, in
15540   // the size of the target vector type.
15541   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15542   unsigned SizeRatio = RegSz / MemSz;
15543
15544   if (Ext == ISD::SEXTLOAD) {
15545     // If we have SSE4.1, we can directly emit a VSEXT node.
15546     if (Subtarget->hasSSE41()) {
15547       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15548       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15549       return Sext;
15550     }
15551
15552     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15553     // lanes.
15554     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15555            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15556
15557     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15558     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15559     return Shuff;
15560   }
15561
15562   // Redistribute the loaded elements into the different locations.
15563   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15564   for (unsigned i = 0; i != NumElems; ++i)
15565     ShuffleVec[i * SizeRatio] = i;
15566
15567   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15568                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15569
15570   // Bitcast to the requested type.
15571   Shuff = DAG.getBitcast(RegVT, Shuff);
15572   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15573   return Shuff;
15574 }
15575
15576 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15577 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15578 // from the AND / OR.
15579 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15580   Opc = Op.getOpcode();
15581   if (Opc != ISD::OR && Opc != ISD::AND)
15582     return false;
15583   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15584           Op.getOperand(0).hasOneUse() &&
15585           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15586           Op.getOperand(1).hasOneUse());
15587 }
15588
15589 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15590 // 1 and that the SETCC node has a single use.
15591 static bool isXor1OfSetCC(SDValue Op) {
15592   if (Op.getOpcode() != ISD::XOR)
15593     return false;
15594   if (isOneConstant(Op.getOperand(1)))
15595     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15596            Op.getOperand(0).hasOneUse();
15597   return false;
15598 }
15599
15600 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15601   bool addTest = true;
15602   SDValue Chain = Op.getOperand(0);
15603   SDValue Cond  = Op.getOperand(1);
15604   SDValue Dest  = Op.getOperand(2);
15605   SDLoc dl(Op);
15606   SDValue CC;
15607   bool Inverted = false;
15608
15609   if (Cond.getOpcode() == ISD::SETCC) {
15610     // Check for setcc([su]{add,sub,mul}o == 0).
15611     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15612         isNullConstant(Cond.getOperand(1)) &&
15613         Cond.getOperand(0).getResNo() == 1 &&
15614         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15615          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15616          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15617          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15618          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15619          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15620       Inverted = true;
15621       Cond = Cond.getOperand(0);
15622     } else {
15623       SDValue NewCond = LowerSETCC(Cond, DAG);
15624       if (NewCond.getNode())
15625         Cond = NewCond;
15626     }
15627   }
15628 #if 0
15629   // FIXME: LowerXALUO doesn't handle these!!
15630   else if (Cond.getOpcode() == X86ISD::ADD  ||
15631            Cond.getOpcode() == X86ISD::SUB  ||
15632            Cond.getOpcode() == X86ISD::SMUL ||
15633            Cond.getOpcode() == X86ISD::UMUL)
15634     Cond = LowerXALUO(Cond, DAG);
15635 #endif
15636
15637   // Look pass (and (setcc_carry (cmp ...)), 1).
15638   if (Cond.getOpcode() == ISD::AND &&
15639       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15640       isOneConstant(Cond.getOperand(1)))
15641     Cond = Cond.getOperand(0);
15642
15643   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15644   // setting operand in place of the X86ISD::SETCC.
15645   unsigned CondOpcode = Cond.getOpcode();
15646   if (CondOpcode == X86ISD::SETCC ||
15647       CondOpcode == X86ISD::SETCC_CARRY) {
15648     CC = Cond.getOperand(0);
15649
15650     SDValue Cmp = Cond.getOperand(1);
15651     unsigned Opc = Cmp.getOpcode();
15652     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15653     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15654       Cond = Cmp;
15655       addTest = false;
15656     } else {
15657       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15658       default: break;
15659       case X86::COND_O:
15660       case X86::COND_B:
15661         // These can only come from an arithmetic instruction with overflow,
15662         // e.g. SADDO, UADDO.
15663         Cond = Cond.getNode()->getOperand(1);
15664         addTest = false;
15665         break;
15666       }
15667     }
15668   }
15669   CondOpcode = Cond.getOpcode();
15670   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15671       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15672       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15673        Cond.getOperand(0).getValueType() != MVT::i8)) {
15674     SDValue LHS = Cond.getOperand(0);
15675     SDValue RHS = Cond.getOperand(1);
15676     unsigned X86Opcode;
15677     unsigned X86Cond;
15678     SDVTList VTs;
15679     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15680     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15681     // X86ISD::INC).
15682     switch (CondOpcode) {
15683     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15684     case ISD::SADDO:
15685       if (isOneConstant(RHS)) {
15686           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15687           break;
15688         }
15689       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15690     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15691     case ISD::SSUBO:
15692       if (isOneConstant(RHS)) {
15693           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15694           break;
15695         }
15696       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15697     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15698     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15699     default: llvm_unreachable("unexpected overflowing operator");
15700     }
15701     if (Inverted)
15702       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15703     if (CondOpcode == ISD::UMULO)
15704       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15705                           MVT::i32);
15706     else
15707       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15708
15709     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15710
15711     if (CondOpcode == ISD::UMULO)
15712       Cond = X86Op.getValue(2);
15713     else
15714       Cond = X86Op.getValue(1);
15715
15716     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15717     addTest = false;
15718   } else {
15719     unsigned CondOpc;
15720     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15721       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15722       if (CondOpc == ISD::OR) {
15723         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15724         // two branches instead of an explicit OR instruction with a
15725         // separate test.
15726         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15727             isX86LogicalCmp(Cmp)) {
15728           CC = Cond.getOperand(0).getOperand(0);
15729           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15730                               Chain, Dest, CC, Cmp);
15731           CC = Cond.getOperand(1).getOperand(0);
15732           Cond = Cmp;
15733           addTest = false;
15734         }
15735       } else { // ISD::AND
15736         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15737         // two branches instead of an explicit AND instruction with a
15738         // separate test. However, we only do this if this block doesn't
15739         // have a fall-through edge, because this requires an explicit
15740         // jmp when the condition is false.
15741         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15742             isX86LogicalCmp(Cmp) &&
15743             Op.getNode()->hasOneUse()) {
15744           X86::CondCode CCode =
15745             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15746           CCode = X86::GetOppositeBranchCondition(CCode);
15747           CC = DAG.getConstant(CCode, dl, MVT::i8);
15748           SDNode *User = *Op.getNode()->use_begin();
15749           // Look for an unconditional branch following this conditional branch.
15750           // We need this because we need to reverse the successors in order
15751           // to implement FCMP_OEQ.
15752           if (User->getOpcode() == ISD::BR) {
15753             SDValue FalseBB = User->getOperand(1);
15754             SDNode *NewBR =
15755               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15756             assert(NewBR == User);
15757             (void)NewBR;
15758             Dest = FalseBB;
15759
15760             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15761                                 Chain, Dest, CC, Cmp);
15762             X86::CondCode CCode =
15763               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15764             CCode = X86::GetOppositeBranchCondition(CCode);
15765             CC = DAG.getConstant(CCode, dl, MVT::i8);
15766             Cond = Cmp;
15767             addTest = false;
15768           }
15769         }
15770       }
15771     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15772       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15773       // It should be transformed during dag combiner except when the condition
15774       // is set by a arithmetics with overflow node.
15775       X86::CondCode CCode =
15776         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15777       CCode = X86::GetOppositeBranchCondition(CCode);
15778       CC = DAG.getConstant(CCode, dl, MVT::i8);
15779       Cond = Cond.getOperand(0).getOperand(1);
15780       addTest = false;
15781     } else if (Cond.getOpcode() == ISD::SETCC &&
15782                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15783       // For FCMP_OEQ, we can emit
15784       // two branches instead of an explicit AND instruction with a
15785       // separate test. However, we only do this if this block doesn't
15786       // have a fall-through edge, because this requires an explicit
15787       // jmp when the condition is false.
15788       if (Op.getNode()->hasOneUse()) {
15789         SDNode *User = *Op.getNode()->use_begin();
15790         // Look for an unconditional branch following this conditional branch.
15791         // We need this because we need to reverse the successors in order
15792         // to implement FCMP_OEQ.
15793         if (User->getOpcode() == ISD::BR) {
15794           SDValue FalseBB = User->getOperand(1);
15795           SDNode *NewBR =
15796             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15797           assert(NewBR == User);
15798           (void)NewBR;
15799           Dest = FalseBB;
15800
15801           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15802                                     Cond.getOperand(0), Cond.getOperand(1));
15803           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15804           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15805           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15806                               Chain, Dest, CC, Cmp);
15807           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15808           Cond = Cmp;
15809           addTest = false;
15810         }
15811       }
15812     } else if (Cond.getOpcode() == ISD::SETCC &&
15813                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15814       // For FCMP_UNE, we can emit
15815       // two branches instead of an explicit AND instruction with a
15816       // separate test. However, we only do this if this block doesn't
15817       // have a fall-through edge, because this requires an explicit
15818       // jmp when the condition is false.
15819       if (Op.getNode()->hasOneUse()) {
15820         SDNode *User = *Op.getNode()->use_begin();
15821         // Look for an unconditional branch following this conditional branch.
15822         // We need this because we need to reverse the successors in order
15823         // to implement FCMP_UNE.
15824         if (User->getOpcode() == ISD::BR) {
15825           SDValue FalseBB = User->getOperand(1);
15826           SDNode *NewBR =
15827             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15828           assert(NewBR == User);
15829           (void)NewBR;
15830
15831           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15832                                     Cond.getOperand(0), Cond.getOperand(1));
15833           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15834           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15835           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15836                               Chain, Dest, CC, Cmp);
15837           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15838           Cond = Cmp;
15839           addTest = false;
15840           Dest = FalseBB;
15841         }
15842       }
15843     }
15844   }
15845
15846   if (addTest) {
15847     // Look pass the truncate if the high bits are known zero.
15848     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15849         Cond = Cond.getOperand(0);
15850
15851     // We know the result of AND is compared against zero. Try to match
15852     // it to BT.
15853     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15854       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15855         CC = NewSetCC.getOperand(0);
15856         Cond = NewSetCC.getOperand(1);
15857         addTest = false;
15858       }
15859     }
15860   }
15861
15862   if (addTest) {
15863     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15864     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15865     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15866   }
15867   Cond = ConvertCmpIfNecessary(Cond, DAG);
15868   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15869                      Chain, Dest, CC, Cond);
15870 }
15871
15872 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15873 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15874 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15875 // that the guard pages used by the OS virtual memory manager are allocated in
15876 // correct sequence.
15877 SDValue
15878 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15879                                            SelectionDAG &DAG) const {
15880   MachineFunction &MF = DAG.getMachineFunction();
15881   bool SplitStack = MF.shouldSplitStack();
15882   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15883                SplitStack;
15884   SDLoc dl(Op);
15885
15886   // Get the inputs.
15887   SDNode *Node = Op.getNode();
15888   SDValue Chain = Op.getOperand(0);
15889   SDValue Size  = Op.getOperand(1);
15890   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15891   EVT VT = Node->getValueType(0);
15892
15893   // Chain the dynamic stack allocation so that it doesn't modify the stack
15894   // pointer when other instructions are using the stack.
15895   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15896
15897   bool Is64Bit = Subtarget->is64Bit();
15898   MVT SPTy = getPointerTy(DAG.getDataLayout());
15899
15900   SDValue Result;
15901   if (!Lower) {
15902     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15903     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15904     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15905                     " not tell us which reg is the stack pointer!");
15906     EVT VT = Node->getValueType(0);
15907     SDValue Tmp3 = Node->getOperand(2);
15908
15909     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15910     Chain = SP.getValue(1);
15911     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15912     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15913     unsigned StackAlign = TFI.getStackAlignment();
15914     Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15915     if (Align > StackAlign)
15916       Result = DAG.getNode(ISD::AND, dl, VT, Result,
15917                          DAG.getConstant(-(uint64_t)Align, dl, VT));
15918     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15919   } else if (SplitStack) {
15920     MachineRegisterInfo &MRI = MF.getRegInfo();
15921
15922     if (Is64Bit) {
15923       // The 64 bit implementation of segmented stacks needs to clobber both r10
15924       // r11. This makes it impossible to use it along with nested parameters.
15925       const Function *F = MF.getFunction();
15926
15927       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15928            I != E; ++I)
15929         if (I->hasNestAttr())
15930           report_fatal_error("Cannot use segmented stacks with functions that "
15931                              "have nested arguments.");
15932     }
15933
15934     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15935     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15936     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15937     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15938                                 DAG.getRegister(Vreg, SPTy));
15939   } else {
15940     SDValue Flag;
15941     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15942
15943     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15944     Flag = Chain.getValue(1);
15945     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15946
15947     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15948
15949     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15950     unsigned SPReg = RegInfo->getStackRegister();
15951     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15952     Chain = SP.getValue(1);
15953
15954     if (Align) {
15955       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15956                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15957       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15958     }
15959
15960     Result = SP;
15961   }
15962
15963   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15964                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
15965
15966   SDValue Ops[2] = {Result, Chain};
15967   return DAG.getMergeValues(Ops, dl);
15968 }
15969
15970 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15971   MachineFunction &MF = DAG.getMachineFunction();
15972   auto PtrVT = getPointerTy(MF.getDataLayout());
15973   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15974
15975   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15976   SDLoc DL(Op);
15977
15978   if (!Subtarget->is64Bit() ||
15979       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15980     // vastart just stores the address of the VarArgsFrameIndex slot into the
15981     // memory location argument.
15982     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15983     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15984                         MachinePointerInfo(SV), false, false, 0);
15985   }
15986
15987   // __va_list_tag:
15988   //   gp_offset         (0 - 6 * 8)
15989   //   fp_offset         (48 - 48 + 8 * 16)
15990   //   overflow_arg_area (point to parameters coming in memory).
15991   //   reg_save_area
15992   SmallVector<SDValue, 8> MemOps;
15993   SDValue FIN = Op.getOperand(1);
15994   // Store gp_offset
15995   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15996                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15997                                                DL, MVT::i32),
15998                                FIN, MachinePointerInfo(SV), false, false, 0);
15999   MemOps.push_back(Store);
16000
16001   // Store fp_offset
16002   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16003   Store = DAG.getStore(Op.getOperand(0), DL,
16004                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
16005                                        MVT::i32),
16006                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
16007   MemOps.push_back(Store);
16008
16009   // Store ptr to overflow_arg_area
16010   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16011   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16012   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16013                        MachinePointerInfo(SV, 8),
16014                        false, false, 0);
16015   MemOps.push_back(Store);
16016
16017   // Store ptr to reg_save_area.
16018   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
16019       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
16020   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
16021   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
16022       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
16023   MemOps.push_back(Store);
16024   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16025 }
16026
16027 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16028   assert(Subtarget->is64Bit() &&
16029          "LowerVAARG only handles 64-bit va_arg!");
16030   assert(Op.getNode()->getNumOperands() == 4);
16031
16032   MachineFunction &MF = DAG.getMachineFunction();
16033   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
16034     // The Win64 ABI uses char* instead of a structure.
16035     return DAG.expandVAArg(Op.getNode());
16036
16037   SDValue Chain = Op.getOperand(0);
16038   SDValue SrcPtr = Op.getOperand(1);
16039   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16040   unsigned Align = Op.getConstantOperandVal(3);
16041   SDLoc dl(Op);
16042
16043   EVT ArgVT = Op.getNode()->getValueType(0);
16044   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16045   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
16046   uint8_t ArgMode;
16047
16048   // Decide which area this value should be read from.
16049   // TODO: Implement the AMD64 ABI in its entirety. This simple
16050   // selection mechanism works only for the basic types.
16051   if (ArgVT == MVT::f80) {
16052     llvm_unreachable("va_arg for f80 not yet implemented");
16053   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16054     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16055   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16056     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16057   } else {
16058     llvm_unreachable("Unhandled argument type in LowerVAARG");
16059   }
16060
16061   if (ArgMode == 2) {
16062     // Sanity Check: Make sure using fp_offset makes sense.
16063     assert(!Subtarget->useSoftFloat() &&
16064            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
16065            Subtarget->hasSSE1());
16066   }
16067
16068   // Insert VAARG_64 node into the DAG
16069   // VAARG_64 returns two values: Variable Argument Address, Chain
16070   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
16071                        DAG.getConstant(ArgMode, dl, MVT::i8),
16072                        DAG.getConstant(Align, dl, MVT::i32)};
16073   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
16074   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16075                                           VTs, InstOps, MVT::i64,
16076                                           MachinePointerInfo(SV),
16077                                           /*Align=*/0,
16078                                           /*Volatile=*/false,
16079                                           /*ReadMem=*/true,
16080                                           /*WriteMem=*/true);
16081   Chain = VAARG.getValue(1);
16082
16083   // Load the next argument and return it
16084   return DAG.getLoad(ArgVT, dl,
16085                      Chain,
16086                      VAARG,
16087                      MachinePointerInfo(),
16088                      false, false, false, 0);
16089 }
16090
16091 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16092                            SelectionDAG &DAG) {
16093   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
16094   // where a va_list is still an i8*.
16095   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16096   if (Subtarget->isCallingConvWin64(
16097         DAG.getMachineFunction().getFunction()->getCallingConv()))
16098     // Probably a Win64 va_copy.
16099     return DAG.expandVACopy(Op.getNode());
16100
16101   SDValue Chain = Op.getOperand(0);
16102   SDValue DstPtr = Op.getOperand(1);
16103   SDValue SrcPtr = Op.getOperand(2);
16104   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16105   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16106   SDLoc DL(Op);
16107
16108   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16109                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
16110                        false, false,
16111                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16112 }
16113
16114 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16115 // amount is a constant. Takes immediate version of shift as input.
16116 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16117                                           SDValue SrcOp, uint64_t ShiftAmt,
16118                                           SelectionDAG &DAG) {
16119   MVT ElementType = VT.getVectorElementType();
16120
16121   // Fold this packed shift into its first operand if ShiftAmt is 0.
16122   if (ShiftAmt == 0)
16123     return SrcOp;
16124
16125   // Check for ShiftAmt >= element width
16126   if (ShiftAmt >= ElementType.getSizeInBits()) {
16127     if (Opc == X86ISD::VSRAI)
16128       ShiftAmt = ElementType.getSizeInBits() - 1;
16129     else
16130       return DAG.getConstant(0, dl, VT);
16131   }
16132
16133   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16134          && "Unknown target vector shift-by-constant node");
16135
16136   // Fold this packed vector shift into a build vector if SrcOp is a
16137   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16138   if (VT == SrcOp.getSimpleValueType() &&
16139       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16140     SmallVector<SDValue, 8> Elts;
16141     unsigned NumElts = SrcOp->getNumOperands();
16142     ConstantSDNode *ND;
16143
16144     switch(Opc) {
16145     default: llvm_unreachable(nullptr);
16146     case X86ISD::VSHLI:
16147       for (unsigned i=0; i!=NumElts; ++i) {
16148         SDValue CurrentOp = SrcOp->getOperand(i);
16149         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16150           Elts.push_back(CurrentOp);
16151           continue;
16152         }
16153         ND = cast<ConstantSDNode>(CurrentOp);
16154         const APInt &C = ND->getAPIntValue();
16155         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
16156       }
16157       break;
16158     case X86ISD::VSRLI:
16159       for (unsigned i=0; i!=NumElts; ++i) {
16160         SDValue CurrentOp = SrcOp->getOperand(i);
16161         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16162           Elts.push_back(CurrentOp);
16163           continue;
16164         }
16165         ND = cast<ConstantSDNode>(CurrentOp);
16166         const APInt &C = ND->getAPIntValue();
16167         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
16168       }
16169       break;
16170     case X86ISD::VSRAI:
16171       for (unsigned i=0; i!=NumElts; ++i) {
16172         SDValue CurrentOp = SrcOp->getOperand(i);
16173         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16174           Elts.push_back(CurrentOp);
16175           continue;
16176         }
16177         ND = cast<ConstantSDNode>(CurrentOp);
16178         const APInt &C = ND->getAPIntValue();
16179         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
16180       }
16181       break;
16182     }
16183
16184     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16185   }
16186
16187   return DAG.getNode(Opc, dl, VT, SrcOp,
16188                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
16189 }
16190
16191 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16192 // may or may not be a constant. Takes immediate version of shift as input.
16193 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16194                                    SDValue SrcOp, SDValue ShAmt,
16195                                    SelectionDAG &DAG) {
16196   MVT SVT = ShAmt.getSimpleValueType();
16197   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16198
16199   // Catch shift-by-constant.
16200   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16201     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16202                                       CShAmt->getZExtValue(), DAG);
16203
16204   // Change opcode to non-immediate version
16205   switch (Opc) {
16206     default: llvm_unreachable("Unknown target vector shift node");
16207     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16208     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16209     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16210   }
16211
16212   const X86Subtarget &Subtarget =
16213       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16214   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16215       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16216     // Let the shuffle legalizer expand this shift amount node.
16217     SDValue Op0 = ShAmt.getOperand(0);
16218     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16219     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16220   } else {
16221     // Need to build a vector containing shift amount.
16222     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16223     SmallVector<SDValue, 4> ShOps;
16224     ShOps.push_back(ShAmt);
16225     if (SVT == MVT::i32) {
16226       ShOps.push_back(DAG.getConstant(0, dl, SVT));
16227       ShOps.push_back(DAG.getUNDEF(SVT));
16228     }
16229     ShOps.push_back(DAG.getUNDEF(SVT));
16230
16231     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16232     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16233   }
16234
16235   // The return type has to be a 128-bit type with the same element
16236   // type as the input type.
16237   MVT EltVT = VT.getVectorElementType();
16238   MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16239
16240   ShAmt = DAG.getBitcast(ShVT, ShAmt);
16241   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16242 }
16243
16244 /// \brief Return Mask with the necessary casting or extending
16245 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16246 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16247                            const X86Subtarget *Subtarget,
16248                            SelectionDAG &DAG, SDLoc dl) {
16249
16250   if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16251     // Mask should be extended
16252     Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16253                        MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16254   }
16255
16256   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16257     if (MaskVT == MVT::v64i1) {
16258       assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16259       // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16260       SDValue Lo, Hi;
16261       Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16262                           DAG.getConstant(0, dl, MVT::i32));
16263       Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16264                           DAG.getConstant(1, dl, MVT::i32));
16265
16266       Lo = DAG.getBitcast(MVT::v32i1, Lo);
16267       Hi = DAG.getBitcast(MVT::v32i1, Hi);
16268
16269       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16270     } else {
16271       // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16272       // and bitcast.
16273       MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16274       return DAG.getBitcast(MaskVT,
16275                             DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16276     }
16277
16278   } else {
16279     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16280                                      Mask.getSimpleValueType().getSizeInBits());
16281     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16282     // are extracted by EXTRACT_SUBVECTOR.
16283     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16284                        DAG.getBitcast(BitcastVT, Mask),
16285                        DAG.getIntPtrConstant(0, dl));
16286   }
16287 }
16288
16289 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16290 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16291 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16292 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16293                   SDValue PreservedSrc,
16294                   const X86Subtarget *Subtarget,
16295                   SelectionDAG &DAG) {
16296   MVT VT = Op.getSimpleValueType();
16297   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16298   unsigned OpcodeSelect = ISD::VSELECT;
16299   SDLoc dl(Op);
16300
16301   if (isAllOnesConstant(Mask))
16302     return Op;
16303
16304   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16305
16306   switch (Op.getOpcode()) {
16307   default: break;
16308   case X86ISD::PCMPEQM:
16309   case X86ISD::PCMPGTM:
16310   case X86ISD::CMPM:
16311   case X86ISD::CMPMU:
16312     return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16313   case X86ISD::VFPCLASS:
16314     case X86ISD::VFPCLASSS:
16315     return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16316   case X86ISD::VTRUNC:
16317   case X86ISD::VTRUNCS:
16318   case X86ISD::VTRUNCUS:
16319     // We can't use ISD::VSELECT here because it is not always "Legal"
16320     // for the destination type. For example vpmovqb require only AVX512
16321     // and vselect that can operate on byte element type require BWI
16322     OpcodeSelect = X86ISD::SELECT;
16323     break;
16324   }
16325   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16326     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16327   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16328 }
16329
16330 /// \brief Creates an SDNode for a predicated scalar operation.
16331 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16332 /// The mask is coming as MVT::i8 and it should be truncated
16333 /// to MVT::i1 while lowering masking intrinsics.
16334 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16335 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16336 /// for a scalar instruction.
16337 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16338                                     SDValue PreservedSrc,
16339                                     const X86Subtarget *Subtarget,
16340                                     SelectionDAG &DAG) {
16341   if (isAllOnesConstant(Mask))
16342     return Op;
16343
16344   MVT VT = Op.getSimpleValueType();
16345   SDLoc dl(Op);
16346   // The mask should be of type MVT::i1
16347   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16348
16349   if (Op.getOpcode() == X86ISD::FSETCC)
16350     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16351   if (Op.getOpcode() == X86ISD::VFPCLASS ||
16352       Op.getOpcode() == X86ISD::VFPCLASSS)
16353     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16354
16355   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16356     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16357   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16358 }
16359
16360 static int getSEHRegistrationNodeSize(const Function *Fn) {
16361   if (!Fn->hasPersonalityFn())
16362     report_fatal_error(
16363         "querying registration node size for function without personality");
16364   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16365   // WinEHStatePass for the full struct definition.
16366   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16367   case EHPersonality::MSVC_X86SEH: return 24;
16368   case EHPersonality::MSVC_CXX: return 16;
16369   default: break;
16370   }
16371   report_fatal_error(
16372       "can only recover FP for 32-bit MSVC EH personality functions");
16373 }
16374
16375 /// When the MSVC runtime transfers control to us, either to an outlined
16376 /// function or when returning to a parent frame after catching an exception, we
16377 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16378 /// Here's the math:
16379 ///   RegNodeBase = EntryEBP - RegNodeSize
16380 ///   ParentFP = RegNodeBase - ParentFrameOffset
16381 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16382 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16383 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16384                                    SDValue EntryEBP) {
16385   MachineFunction &MF = DAG.getMachineFunction();
16386   SDLoc dl;
16387
16388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16389   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16390
16391   // It's possible that the parent function no longer has a personality function
16392   // if the exceptional code was optimized away, in which case we just return
16393   // the incoming EBP.
16394   if (!Fn->hasPersonalityFn())
16395     return EntryEBP;
16396
16397   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16398   // registration, or the .set_setframe offset.
16399   MCSymbol *OffsetSym =
16400       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16401           GlobalValue::getRealLinkageName(Fn->getName()));
16402   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16403   SDValue ParentFrameOffset =
16404       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16405
16406   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
16407   // prologue to RBP in the parent function.
16408   const X86Subtarget &Subtarget =
16409       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16410   if (Subtarget.is64Bit())
16411     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
16412
16413   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16414   // RegNodeBase = EntryEBP - RegNodeSize
16415   // ParentFP = RegNodeBase - ParentFrameOffset
16416   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16417                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16418   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
16419 }
16420
16421 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16422                                        SelectionDAG &DAG) {
16423   SDLoc dl(Op);
16424   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16425   MVT VT = Op.getSimpleValueType();
16426   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16427   if (IntrData) {
16428     switch(IntrData->Type) {
16429     case INTR_TYPE_1OP:
16430       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16431     case INTR_TYPE_2OP:
16432       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16433         Op.getOperand(2));
16434     case INTR_TYPE_2OP_IMM8:
16435       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16436                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16437     case INTR_TYPE_3OP:
16438       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16439         Op.getOperand(2), Op.getOperand(3));
16440     case INTR_TYPE_4OP:
16441       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16442         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16443     case INTR_TYPE_1OP_MASK_RM: {
16444       SDValue Src = Op.getOperand(1);
16445       SDValue PassThru = Op.getOperand(2);
16446       SDValue Mask = Op.getOperand(3);
16447       SDValue RoundingMode;
16448       // We allways add rounding mode to the Node.
16449       // If the rounding mode is not specified, we add the
16450       // "current direction" mode.
16451       if (Op.getNumOperands() == 4)
16452         RoundingMode =
16453           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16454       else
16455         RoundingMode = Op.getOperand(4);
16456       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16457       if (IntrWithRoundingModeOpcode != 0)
16458         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16459             X86::STATIC_ROUNDING::CUR_DIRECTION)
16460           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16461                                       dl, Op.getValueType(), Src, RoundingMode),
16462                                       Mask, PassThru, Subtarget, DAG);
16463       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16464                                               RoundingMode),
16465                                   Mask, PassThru, Subtarget, DAG);
16466     }
16467     case INTR_TYPE_1OP_MASK: {
16468       SDValue Src = Op.getOperand(1);
16469       SDValue PassThru = Op.getOperand(2);
16470       SDValue Mask = Op.getOperand(3);
16471       // We add rounding mode to the Node when
16472       //   - RM Opcode is specified and
16473       //   - RM is not "current direction".
16474       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16475       if (IntrWithRoundingModeOpcode != 0) {
16476         SDValue Rnd = Op.getOperand(4);
16477         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16478         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16479           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16480                                       dl, Op.getValueType(),
16481                                       Src, Rnd),
16482                                       Mask, PassThru, Subtarget, DAG);
16483         }
16484       }
16485       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16486                                   Mask, PassThru, Subtarget, DAG);
16487     }
16488     case INTR_TYPE_SCALAR_MASK: {
16489       SDValue Src1 = Op.getOperand(1);
16490       SDValue Src2 = Op.getOperand(2);
16491       SDValue passThru = Op.getOperand(3);
16492       SDValue Mask = Op.getOperand(4);
16493       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16494                                   Mask, passThru, Subtarget, DAG);
16495     }
16496     case INTR_TYPE_SCALAR_MASK_RM: {
16497       SDValue Src1 = Op.getOperand(1);
16498       SDValue Src2 = Op.getOperand(2);
16499       SDValue Src0 = Op.getOperand(3);
16500       SDValue Mask = Op.getOperand(4);
16501       // There are 2 kinds of intrinsics in this group:
16502       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16503       // (2) With rounding mode and sae - 7 operands.
16504       if (Op.getNumOperands() == 6) {
16505         SDValue Sae  = Op.getOperand(5);
16506         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16507         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16508                                                 Sae),
16509                                     Mask, Src0, Subtarget, DAG);
16510       }
16511       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16512       SDValue RoundingMode  = Op.getOperand(5);
16513       SDValue Sae  = Op.getOperand(6);
16514       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16515                                               RoundingMode, Sae),
16516                                   Mask, Src0, Subtarget, DAG);
16517     }
16518     case INTR_TYPE_2OP_MASK:
16519     case INTR_TYPE_2OP_IMM8_MASK: {
16520       SDValue Src1 = Op.getOperand(1);
16521       SDValue Src2 = Op.getOperand(2);
16522       SDValue PassThru = Op.getOperand(3);
16523       SDValue Mask = Op.getOperand(4);
16524
16525       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16526         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16527
16528       // We specify 2 possible opcodes for intrinsics with rounding modes.
16529       // First, we check if the intrinsic may have non-default rounding mode,
16530       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16531       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16532       if (IntrWithRoundingModeOpcode != 0) {
16533         SDValue Rnd = Op.getOperand(5);
16534         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16535         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16536           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16537                                       dl, Op.getValueType(),
16538                                       Src1, Src2, Rnd),
16539                                       Mask, PassThru, Subtarget, DAG);
16540         }
16541       }
16542       // TODO: Intrinsics should have fast-math-flags to propagate.
16543       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16544                                   Mask, PassThru, Subtarget, DAG);
16545     }
16546     case INTR_TYPE_2OP_MASK_RM: {
16547       SDValue Src1 = Op.getOperand(1);
16548       SDValue Src2 = Op.getOperand(2);
16549       SDValue PassThru = Op.getOperand(3);
16550       SDValue Mask = Op.getOperand(4);
16551       // We specify 2 possible modes for intrinsics, with/without rounding
16552       // modes.
16553       // First, we check if the intrinsic have rounding mode (6 operands),
16554       // if not, we set rounding mode to "current".
16555       SDValue Rnd;
16556       if (Op.getNumOperands() == 6)
16557         Rnd = Op.getOperand(5);
16558       else
16559         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16560       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16561                                               Src1, Src2, Rnd),
16562                                   Mask, PassThru, Subtarget, DAG);
16563     }
16564     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16565       SDValue Src1 = Op.getOperand(1);
16566       SDValue Src2 = Op.getOperand(2);
16567       SDValue Src3 = Op.getOperand(3);
16568       SDValue PassThru = Op.getOperand(4);
16569       SDValue Mask = Op.getOperand(5);
16570       SDValue Sae  = Op.getOperand(6);
16571
16572       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16573                                               Src2, Src3, Sae),
16574                                   Mask, PassThru, Subtarget, DAG);
16575     }
16576     case INTR_TYPE_3OP_MASK_RM: {
16577       SDValue Src1 = Op.getOperand(1);
16578       SDValue Src2 = Op.getOperand(2);
16579       SDValue Imm = Op.getOperand(3);
16580       SDValue PassThru = Op.getOperand(4);
16581       SDValue Mask = Op.getOperand(5);
16582       // We specify 2 possible modes for intrinsics, with/without rounding
16583       // modes.
16584       // First, we check if the intrinsic have rounding mode (7 operands),
16585       // if not, we set rounding mode to "current".
16586       SDValue Rnd;
16587       if (Op.getNumOperands() == 7)
16588         Rnd = Op.getOperand(6);
16589       else
16590         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16591       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16592         Src1, Src2, Imm, Rnd),
16593         Mask, PassThru, Subtarget, DAG);
16594     }
16595     case INTR_TYPE_3OP_IMM8_MASK:
16596     case INTR_TYPE_3OP_MASK:
16597     case INSERT_SUBVEC: {
16598       SDValue Src1 = Op.getOperand(1);
16599       SDValue Src2 = Op.getOperand(2);
16600       SDValue Src3 = Op.getOperand(3);
16601       SDValue PassThru = Op.getOperand(4);
16602       SDValue Mask = Op.getOperand(5);
16603
16604       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16605         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16606       else if (IntrData->Type == INSERT_SUBVEC) {
16607         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16608         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16609         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16610         Imm *= Src2.getSimpleValueType().getVectorNumElements();
16611         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16612       }
16613
16614       // We specify 2 possible opcodes for intrinsics with rounding modes.
16615       // First, we check if the intrinsic may have non-default rounding mode,
16616       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16617       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16618       if (IntrWithRoundingModeOpcode != 0) {
16619         SDValue Rnd = Op.getOperand(6);
16620         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16621         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16622           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16623                                       dl, Op.getValueType(),
16624                                       Src1, Src2, Src3, Rnd),
16625                                       Mask, PassThru, Subtarget, DAG);
16626         }
16627       }
16628       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16629                                               Src1, Src2, Src3),
16630                                   Mask, PassThru, Subtarget, DAG);
16631     }
16632     case VPERM_3OP_MASKZ:
16633     case VPERM_3OP_MASK:{
16634       // Src2 is the PassThru
16635       SDValue Src1 = Op.getOperand(1);
16636       SDValue Src2 = Op.getOperand(2);
16637       SDValue Src3 = Op.getOperand(3);
16638       SDValue Mask = Op.getOperand(4);
16639       MVT VT = Op.getSimpleValueType();
16640       SDValue PassThru = SDValue();
16641
16642       // set PassThru element
16643       if (IntrData->Type == VPERM_3OP_MASKZ)
16644         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16645       else
16646         PassThru = DAG.getBitcast(VT, Src2);
16647
16648       // Swap Src1 and Src2 in the node creation
16649       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16650                                               dl, Op.getValueType(),
16651                                               Src2, Src1, Src3),
16652                                   Mask, PassThru, Subtarget, DAG);
16653     }
16654     case FMA_OP_MASK3:
16655     case FMA_OP_MASKZ:
16656     case FMA_OP_MASK: {
16657       SDValue Src1 = Op.getOperand(1);
16658       SDValue Src2 = Op.getOperand(2);
16659       SDValue Src3 = Op.getOperand(3);
16660       SDValue Mask = Op.getOperand(4);
16661       MVT VT = Op.getSimpleValueType();
16662       SDValue PassThru = SDValue();
16663
16664       // set PassThru element
16665       if (IntrData->Type == FMA_OP_MASKZ)
16666         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16667       else if (IntrData->Type == FMA_OP_MASK3)
16668         PassThru = Src3;
16669       else
16670         PassThru = Src1;
16671
16672       // We specify 2 possible opcodes for intrinsics with rounding modes.
16673       // First, we check if the intrinsic may have non-default rounding mode,
16674       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16675       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16676       if (IntrWithRoundingModeOpcode != 0) {
16677         SDValue Rnd = Op.getOperand(5);
16678         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16679             X86::STATIC_ROUNDING::CUR_DIRECTION)
16680           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16681                                                   dl, Op.getValueType(),
16682                                                   Src1, Src2, Src3, Rnd),
16683                                       Mask, PassThru, Subtarget, DAG);
16684       }
16685       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16686                                               dl, Op.getValueType(),
16687                                               Src1, Src2, Src3),
16688                                   Mask, PassThru, Subtarget, DAG);
16689     }
16690     case TERLOG_OP_MASK:
16691     case TERLOG_OP_MASKZ: {
16692       SDValue Src1 = Op.getOperand(1);
16693       SDValue Src2 = Op.getOperand(2);
16694       SDValue Src3 = Op.getOperand(3);
16695       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16696       SDValue Mask = Op.getOperand(5);
16697       MVT VT = Op.getSimpleValueType();
16698       SDValue PassThru = Src1;
16699       // Set PassThru element.
16700       if (IntrData->Type == TERLOG_OP_MASKZ)
16701         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16702
16703       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16704                                               Src1, Src2, Src3, Src4),
16705                                   Mask, PassThru, Subtarget, DAG);
16706     }
16707     case FPCLASS: {
16708       // FPclass intrinsics with mask
16709        SDValue Src1 = Op.getOperand(1);
16710        MVT VT = Src1.getSimpleValueType();
16711        MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16712        SDValue Imm = Op.getOperand(2);
16713        SDValue Mask = Op.getOperand(3);
16714        MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16715                                      Mask.getSimpleValueType().getSizeInBits());
16716        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16717        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16718                                                  DAG.getTargetConstant(0, dl, MaskVT),
16719                                                  Subtarget, DAG);
16720        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16721                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16722                                  DAG.getIntPtrConstant(0, dl));
16723        return DAG.getBitcast(Op.getValueType(), Res);
16724     }
16725     case FPCLASSS: {
16726       SDValue Src1 = Op.getOperand(1);
16727       SDValue Imm = Op.getOperand(2);
16728       SDValue Mask = Op.getOperand(3);
16729       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16730       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16731         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16732       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16733     }
16734     case CMP_MASK:
16735     case CMP_MASK_CC: {
16736       // Comparison intrinsics with masks.
16737       // Example of transformation:
16738       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16739       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16740       // (i8 (bitcast
16741       //   (v8i1 (insert_subvector undef,
16742       //           (v2i1 (and (PCMPEQM %a, %b),
16743       //                      (extract_subvector
16744       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16745       MVT VT = Op.getOperand(1).getSimpleValueType();
16746       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16747       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16748       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16749                                        Mask.getSimpleValueType().getSizeInBits());
16750       SDValue Cmp;
16751       if (IntrData->Type == CMP_MASK_CC) {
16752         SDValue CC = Op.getOperand(3);
16753         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16754         // We specify 2 possible opcodes for intrinsics with rounding modes.
16755         // First, we check if the intrinsic may have non-default rounding mode,
16756         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16757         if (IntrData->Opc1 != 0) {
16758           SDValue Rnd = Op.getOperand(5);
16759           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16760               X86::STATIC_ROUNDING::CUR_DIRECTION)
16761             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16762                               Op.getOperand(2), CC, Rnd);
16763         }
16764         //default rounding mode
16765         if(!Cmp.getNode())
16766             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16767                               Op.getOperand(2), CC);
16768
16769       } else {
16770         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16771         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16772                           Op.getOperand(2));
16773       }
16774       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16775                                              DAG.getTargetConstant(0, dl,
16776                                                                    MaskVT),
16777                                              Subtarget, DAG);
16778       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16779                                 DAG.getUNDEF(BitcastVT), CmpMask,
16780                                 DAG.getIntPtrConstant(0, dl));
16781       return DAG.getBitcast(Op.getValueType(), Res);
16782     }
16783     case CMP_MASK_SCALAR_CC: {
16784       SDValue Src1 = Op.getOperand(1);
16785       SDValue Src2 = Op.getOperand(2);
16786       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16787       SDValue Mask = Op.getOperand(4);
16788
16789       SDValue Cmp;
16790       if (IntrData->Opc1 != 0) {
16791         SDValue Rnd = Op.getOperand(5);
16792         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16793             X86::STATIC_ROUNDING::CUR_DIRECTION)
16794           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16795       }
16796       //default rounding mode
16797       if(!Cmp.getNode())
16798         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16799
16800       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16801                                              DAG.getTargetConstant(0, dl,
16802                                                                    MVT::i1),
16803                                              Subtarget, DAG);
16804
16805       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16806                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16807                          DAG.getValueType(MVT::i1));
16808     }
16809     case COMI: { // Comparison intrinsics
16810       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16811       SDValue LHS = Op.getOperand(1);
16812       SDValue RHS = Op.getOperand(2);
16813       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16814       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16815       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16816       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16817                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16818       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16819     }
16820     case COMI_RM: { // Comparison intrinsics with Sae
16821       SDValue LHS = Op.getOperand(1);
16822       SDValue RHS = Op.getOperand(2);
16823       SDValue CC = Op.getOperand(3);
16824       SDValue Sae = Op.getOperand(4);
16825       auto ComiType = TranslateX86ConstCondToX86CC(CC);
16826       // choose between ordered and unordered (comi/ucomi)
16827       unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16828       SDValue Cond;
16829       if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16830                                            X86::STATIC_ROUNDING::CUR_DIRECTION)
16831         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16832       else
16833         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16834       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16835         DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16836       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16837     }
16838     case VSHIFT:
16839       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16840                                  Op.getOperand(1), Op.getOperand(2), DAG);
16841     case VSHIFT_MASK:
16842       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16843                                                       Op.getSimpleValueType(),
16844                                                       Op.getOperand(1),
16845                                                       Op.getOperand(2), DAG),
16846                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16847                                   DAG);
16848     case COMPRESS_EXPAND_IN_REG: {
16849       SDValue Mask = Op.getOperand(3);
16850       SDValue DataToCompress = Op.getOperand(1);
16851       SDValue PassThru = Op.getOperand(2);
16852       if (isAllOnesConstant(Mask)) // return data as is
16853         return Op.getOperand(1);
16854
16855       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16856                                               DataToCompress),
16857                                   Mask, PassThru, Subtarget, DAG);
16858     }
16859     case BROADCASTM: {
16860       SDValue Mask = Op.getOperand(1);
16861       MVT MaskVT = MVT::getVectorVT(MVT::i1,
16862                                     Mask.getSimpleValueType().getSizeInBits());
16863       Mask = DAG.getBitcast(MaskVT, Mask);
16864       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16865     }
16866     case BLEND: {
16867       SDValue Mask = Op.getOperand(3);
16868       MVT VT = Op.getSimpleValueType();
16869       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16870       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16871       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16872                          Op.getOperand(2));
16873     }
16874     case KUNPCK: {
16875       MVT VT = Op.getSimpleValueType();
16876       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16877
16878       SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16879       SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16880       // Arguments should be swapped.
16881       SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16882                                 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16883                                 Src2, Src1);
16884       return DAG.getBitcast(VT, Res);
16885     }
16886     case CONVERT_TO_MASK: {
16887       MVT SrcVT = Op.getOperand(1).getSimpleValueType();
16888       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
16889       MVT BitcastVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits());
16890
16891       SDValue CvtMask = DAG.getNode(IntrData->Opc0, dl, MaskVT,
16892                                     Op.getOperand(1));
16893       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16894                                 DAG.getUNDEF(BitcastVT), CvtMask,
16895                                 DAG.getIntPtrConstant(0, dl));
16896       return DAG.getBitcast(Op.getValueType(), Res);
16897     }
16898     case CONVERT_MASK_TO_VEC: {
16899       SDValue Mask = Op.getOperand(1);
16900       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16901       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16902       return DAG.getNode(IntrData->Opc0, dl, VT, VMask);
16903     }
16904     case BRCST_SUBVEC_TO_VEC: {
16905       SDValue Src = Op.getOperand(1);
16906       SDValue Passthru = Op.getOperand(2);
16907       SDValue Mask = Op.getOperand(3);
16908       EVT resVT = Passthru.getValueType();
16909       SDValue subVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, resVT,
16910                                        DAG.getUNDEF(resVT), Src,
16911                                        DAG.getIntPtrConstant(0, dl));
16912       SDValue immVal;
16913       if (Src.getSimpleValueType().is256BitVector() && resVT.is512BitVector())
16914         immVal = DAG.getConstant(0x44, dl, MVT::i8);
16915       else
16916         immVal = DAG.getConstant(0, dl, MVT::i8);
16917       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16918                                               subVec, subVec, immVal),
16919                                   Mask, Passthru, Subtarget, DAG);
16920     }
16921     default:
16922       break;
16923     }
16924   }
16925
16926   switch (IntNo) {
16927   default: return SDValue();    // Don't custom lower most intrinsics.
16928
16929   case Intrinsic::x86_avx2_permd:
16930   case Intrinsic::x86_avx2_permps:
16931     // Operands intentionally swapped. Mask is last operand to intrinsic,
16932     // but second operand for node/instruction.
16933     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16934                        Op.getOperand(2), Op.getOperand(1));
16935
16936   // ptest and testp intrinsics. The intrinsic these come from are designed to
16937   // return an integer value, not just an instruction so lower it to the ptest
16938   // or testp pattern and a setcc for the result.
16939   case Intrinsic::x86_sse41_ptestz:
16940   case Intrinsic::x86_sse41_ptestc:
16941   case Intrinsic::x86_sse41_ptestnzc:
16942   case Intrinsic::x86_avx_ptestz_256:
16943   case Intrinsic::x86_avx_ptestc_256:
16944   case Intrinsic::x86_avx_ptestnzc_256:
16945   case Intrinsic::x86_avx_vtestz_ps:
16946   case Intrinsic::x86_avx_vtestc_ps:
16947   case Intrinsic::x86_avx_vtestnzc_ps:
16948   case Intrinsic::x86_avx_vtestz_pd:
16949   case Intrinsic::x86_avx_vtestc_pd:
16950   case Intrinsic::x86_avx_vtestnzc_pd:
16951   case Intrinsic::x86_avx_vtestz_ps_256:
16952   case Intrinsic::x86_avx_vtestc_ps_256:
16953   case Intrinsic::x86_avx_vtestnzc_ps_256:
16954   case Intrinsic::x86_avx_vtestz_pd_256:
16955   case Intrinsic::x86_avx_vtestc_pd_256:
16956   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16957     bool IsTestPacked = false;
16958     unsigned X86CC;
16959     switch (IntNo) {
16960     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16961     case Intrinsic::x86_avx_vtestz_ps:
16962     case Intrinsic::x86_avx_vtestz_pd:
16963     case Intrinsic::x86_avx_vtestz_ps_256:
16964     case Intrinsic::x86_avx_vtestz_pd_256:
16965       IsTestPacked = true; // Fallthrough
16966     case Intrinsic::x86_sse41_ptestz:
16967     case Intrinsic::x86_avx_ptestz_256:
16968       // ZF = 1
16969       X86CC = X86::COND_E;
16970       break;
16971     case Intrinsic::x86_avx_vtestc_ps:
16972     case Intrinsic::x86_avx_vtestc_pd:
16973     case Intrinsic::x86_avx_vtestc_ps_256:
16974     case Intrinsic::x86_avx_vtestc_pd_256:
16975       IsTestPacked = true; // Fallthrough
16976     case Intrinsic::x86_sse41_ptestc:
16977     case Intrinsic::x86_avx_ptestc_256:
16978       // CF = 1
16979       X86CC = X86::COND_B;
16980       break;
16981     case Intrinsic::x86_avx_vtestnzc_ps:
16982     case Intrinsic::x86_avx_vtestnzc_pd:
16983     case Intrinsic::x86_avx_vtestnzc_ps_256:
16984     case Intrinsic::x86_avx_vtestnzc_pd_256:
16985       IsTestPacked = true; // Fallthrough
16986     case Intrinsic::x86_sse41_ptestnzc:
16987     case Intrinsic::x86_avx_ptestnzc_256:
16988       // ZF and CF = 0
16989       X86CC = X86::COND_A;
16990       break;
16991     }
16992
16993     SDValue LHS = Op.getOperand(1);
16994     SDValue RHS = Op.getOperand(2);
16995     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16996     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16997     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16998     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16999     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17000   }
17001   case Intrinsic::x86_avx512_kortestz_w:
17002   case Intrinsic::x86_avx512_kortestc_w: {
17003     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17004     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
17005     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
17006     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17007     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17008     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17009     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17010   }
17011
17012   case Intrinsic::x86_sse42_pcmpistria128:
17013   case Intrinsic::x86_sse42_pcmpestria128:
17014   case Intrinsic::x86_sse42_pcmpistric128:
17015   case Intrinsic::x86_sse42_pcmpestric128:
17016   case Intrinsic::x86_sse42_pcmpistrio128:
17017   case Intrinsic::x86_sse42_pcmpestrio128:
17018   case Intrinsic::x86_sse42_pcmpistris128:
17019   case Intrinsic::x86_sse42_pcmpestris128:
17020   case Intrinsic::x86_sse42_pcmpistriz128:
17021   case Intrinsic::x86_sse42_pcmpestriz128: {
17022     unsigned Opcode;
17023     unsigned X86CC;
17024     switch (IntNo) {
17025     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17026     case Intrinsic::x86_sse42_pcmpistria128:
17027       Opcode = X86ISD::PCMPISTRI;
17028       X86CC = X86::COND_A;
17029       break;
17030     case Intrinsic::x86_sse42_pcmpestria128:
17031       Opcode = X86ISD::PCMPESTRI;
17032       X86CC = X86::COND_A;
17033       break;
17034     case Intrinsic::x86_sse42_pcmpistric128:
17035       Opcode = X86ISD::PCMPISTRI;
17036       X86CC = X86::COND_B;
17037       break;
17038     case Intrinsic::x86_sse42_pcmpestric128:
17039       Opcode = X86ISD::PCMPESTRI;
17040       X86CC = X86::COND_B;
17041       break;
17042     case Intrinsic::x86_sse42_pcmpistrio128:
17043       Opcode = X86ISD::PCMPISTRI;
17044       X86CC = X86::COND_O;
17045       break;
17046     case Intrinsic::x86_sse42_pcmpestrio128:
17047       Opcode = X86ISD::PCMPESTRI;
17048       X86CC = X86::COND_O;
17049       break;
17050     case Intrinsic::x86_sse42_pcmpistris128:
17051       Opcode = X86ISD::PCMPISTRI;
17052       X86CC = X86::COND_S;
17053       break;
17054     case Intrinsic::x86_sse42_pcmpestris128:
17055       Opcode = X86ISD::PCMPESTRI;
17056       X86CC = X86::COND_S;
17057       break;
17058     case Intrinsic::x86_sse42_pcmpistriz128:
17059       Opcode = X86ISD::PCMPISTRI;
17060       X86CC = X86::COND_E;
17061       break;
17062     case Intrinsic::x86_sse42_pcmpestriz128:
17063       Opcode = X86ISD::PCMPESTRI;
17064       X86CC = X86::COND_E;
17065       break;
17066     }
17067     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17068     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17069     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17070     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17071                                 DAG.getConstant(X86CC, dl, MVT::i8),
17072                                 SDValue(PCMP.getNode(), 1));
17073     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17074   }
17075
17076   case Intrinsic::x86_sse42_pcmpistri128:
17077   case Intrinsic::x86_sse42_pcmpestri128: {
17078     unsigned Opcode;
17079     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17080       Opcode = X86ISD::PCMPISTRI;
17081     else
17082       Opcode = X86ISD::PCMPESTRI;
17083
17084     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17085     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17086     return DAG.getNode(Opcode, dl, VTs, NewOps);
17087   }
17088
17089   case Intrinsic::x86_seh_lsda: {
17090     // Compute the symbol for the LSDA. We know it'll get emitted later.
17091     MachineFunction &MF = DAG.getMachineFunction();
17092     SDValue Op1 = Op.getOperand(1);
17093     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
17094     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
17095         GlobalValue::getRealLinkageName(Fn->getName()));
17096
17097     // Generate a simple absolute symbol reference. This intrinsic is only
17098     // supported on 32-bit Windows, which isn't PIC.
17099     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
17100     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
17101   }
17102
17103   case Intrinsic::x86_seh_recoverfp: {
17104     SDValue FnOp = Op.getOperand(1);
17105     SDValue IncomingFPOp = Op.getOperand(2);
17106     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
17107     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
17108     if (!Fn)
17109       report_fatal_error(
17110           "llvm.x86.seh.recoverfp must take a function as the first argument");
17111     return recoverFramePointer(DAG, Fn, IncomingFPOp);
17112   }
17113
17114   case Intrinsic::localaddress: {
17115     // Returns one of the stack, base, or frame pointer registers, depending on
17116     // which is used to reference local variables.
17117     MachineFunction &MF = DAG.getMachineFunction();
17118     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17119     unsigned Reg;
17120     if (RegInfo->hasBasePointer(MF))
17121       Reg = RegInfo->getBaseRegister();
17122     else // This function handles the SP or FP case.
17123       Reg = RegInfo->getPtrSizedFrameRegister(MF);
17124     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
17125   }
17126   }
17127 }
17128
17129 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17130                               SDValue Src, SDValue Mask, SDValue Base,
17131                               SDValue Index, SDValue ScaleOp, SDValue Chain,
17132                               const X86Subtarget * Subtarget) {
17133   SDLoc dl(Op);
17134   auto *C = cast<ConstantSDNode>(ScaleOp);
17135   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17136   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17137                              Index.getSimpleValueType().getVectorNumElements());
17138   SDValue MaskInReg;
17139   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17140   if (MaskC)
17141     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17142   else {
17143     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17144                                      Mask.getSimpleValueType().getSizeInBits());
17145
17146     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17147     // are extracted by EXTRACT_SUBVECTOR.
17148     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17149                             DAG.getBitcast(BitcastVT, Mask),
17150                             DAG.getIntPtrConstant(0, dl));
17151   }
17152   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17153   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17154   SDValue Segment = DAG.getRegister(0, MVT::i32);
17155   if (Src.getOpcode() == ISD::UNDEF)
17156     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
17157   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17158   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17159   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17160   return DAG.getMergeValues(RetOps, dl);
17161 }
17162
17163 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17164                                SDValue Src, SDValue Mask, SDValue Base,
17165                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
17166   SDLoc dl(Op);
17167   auto *C = cast<ConstantSDNode>(ScaleOp);
17168   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17169   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17170   SDValue Segment = DAG.getRegister(0, MVT::i32);
17171   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17172                              Index.getSimpleValueType().getVectorNumElements());
17173   SDValue MaskInReg;
17174   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17175   if (MaskC)
17176     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17177   else {
17178     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17179                                      Mask.getSimpleValueType().getSizeInBits());
17180
17181     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17182     // are extracted by EXTRACT_SUBVECTOR.
17183     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17184                             DAG.getBitcast(BitcastVT, Mask),
17185                             DAG.getIntPtrConstant(0, dl));
17186   }
17187   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17188   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17189   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17190   return SDValue(Res, 1);
17191 }
17192
17193 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17194                                SDValue Mask, SDValue Base, SDValue Index,
17195                                SDValue ScaleOp, SDValue Chain) {
17196   SDLoc dl(Op);
17197   auto *C = cast<ConstantSDNode>(ScaleOp);
17198   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17199   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17200   SDValue Segment = DAG.getRegister(0, MVT::i32);
17201   MVT MaskVT =
17202     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17203   SDValue MaskInReg;
17204   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17205   if (MaskC)
17206     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17207   else
17208     MaskInReg = DAG.getBitcast(MaskVT, Mask);
17209   //SDVTList VTs = DAG.getVTList(MVT::Other);
17210   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17211   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17212   return SDValue(Res, 0);
17213 }
17214
17215 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17216 // read performance monitor counters (x86_rdpmc).
17217 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17218                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17219                               SmallVectorImpl<SDValue> &Results) {
17220   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17221   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17222   SDValue LO, HI;
17223
17224   // The ECX register is used to select the index of the performance counter
17225   // to read.
17226   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17227                                    N->getOperand(2));
17228   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17229
17230   // Reads the content of a 64-bit performance counter and returns it in the
17231   // registers EDX:EAX.
17232   if (Subtarget->is64Bit()) {
17233     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17234     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17235                             LO.getValue(2));
17236   } else {
17237     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17238     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17239                             LO.getValue(2));
17240   }
17241   Chain = HI.getValue(1);
17242
17243   if (Subtarget->is64Bit()) {
17244     // The EAX register is loaded with the low-order 32 bits. The EDX register
17245     // is loaded with the supported high-order bits of the counter.
17246     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17247                               DAG.getConstant(32, DL, MVT::i8));
17248     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17249     Results.push_back(Chain);
17250     return;
17251   }
17252
17253   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17254   SDValue Ops[] = { LO, HI };
17255   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17256   Results.push_back(Pair);
17257   Results.push_back(Chain);
17258 }
17259
17260 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17261 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17262 // also used to custom lower READCYCLECOUNTER nodes.
17263 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17264                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17265                               SmallVectorImpl<SDValue> &Results) {
17266   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17267   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17268   SDValue LO, HI;
17269
17270   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17271   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17272   // and the EAX register is loaded with the low-order 32 bits.
17273   if (Subtarget->is64Bit()) {
17274     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17275     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17276                             LO.getValue(2));
17277   } else {
17278     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17279     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17280                             LO.getValue(2));
17281   }
17282   SDValue Chain = HI.getValue(1);
17283
17284   if (Opcode == X86ISD::RDTSCP_DAG) {
17285     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17286
17287     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17288     // the ECX register. Add 'ecx' explicitly to the chain.
17289     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17290                                      HI.getValue(2));
17291     // Explicitly store the content of ECX at the location passed in input
17292     // to the 'rdtscp' intrinsic.
17293     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17294                          MachinePointerInfo(), false, false, 0);
17295   }
17296
17297   if (Subtarget->is64Bit()) {
17298     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17299     // the EAX register is loaded with the low-order 32 bits.
17300     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17301                               DAG.getConstant(32, DL, MVT::i8));
17302     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17303     Results.push_back(Chain);
17304     return;
17305   }
17306
17307   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17308   SDValue Ops[] = { LO, HI };
17309   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17310   Results.push_back(Pair);
17311   Results.push_back(Chain);
17312 }
17313
17314 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17315                                      SelectionDAG &DAG) {
17316   SmallVector<SDValue, 2> Results;
17317   SDLoc DL(Op);
17318   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17319                           Results);
17320   return DAG.getMergeValues(Results, DL);
17321 }
17322
17323 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17324   MachineFunction &MF = DAG.getMachineFunction();
17325   SDValue Chain = Op.getOperand(0);
17326   SDValue RegNode = Op.getOperand(2);
17327   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17328   if (!EHInfo)
17329     report_fatal_error("EH registrations only live in functions using WinEH");
17330
17331   // Cast the operand to an alloca, and remember the frame index.
17332   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17333   if (!FINode)
17334     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17335   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17336
17337   // Return the chain operand without making any DAG nodes.
17338   return Chain;
17339 }
17340
17341 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17342 /// return truncate Store/MaskedStore Node
17343 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17344                                                SelectionDAG &DAG,
17345                                                MVT ElementType) {
17346   SDLoc dl(Op);
17347   SDValue Mask = Op.getOperand(4);
17348   SDValue DataToTruncate = Op.getOperand(3);
17349   SDValue Addr = Op.getOperand(2);
17350   SDValue Chain = Op.getOperand(0);
17351
17352   MVT VT  = DataToTruncate.getSimpleValueType();
17353   MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17354
17355   if (isAllOnesConstant(Mask)) // return just a truncate store
17356     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17357                              MachinePointerInfo(), SVT, false, false,
17358                              SVT.getScalarSizeInBits()/8);
17359
17360   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17361   MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17362                                    Mask.getSimpleValueType().getSizeInBits());
17363   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17364   // are extracted by EXTRACT_SUBVECTOR.
17365   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17366                               DAG.getBitcast(BitcastVT, Mask),
17367                               DAG.getIntPtrConstant(0, dl));
17368
17369   MachineMemOperand *MMO = DAG.getMachineFunction().
17370     getMachineMemOperand(MachinePointerInfo(),
17371                          MachineMemOperand::MOStore, SVT.getStoreSize(),
17372                          SVT.getScalarSizeInBits()/8);
17373
17374   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17375                             VMask, SVT, MMO, true);
17376 }
17377
17378 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17379                                       SelectionDAG &DAG) {
17380   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17381
17382   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17383   if (!IntrData) {
17384     if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17385       return MarkEHRegistrationNode(Op, DAG);
17386     if (IntNo == llvm::Intrinsic::x86_flags_read_u32 ||
17387         IntNo == llvm::Intrinsic::x86_flags_read_u64 ||
17388         IntNo == llvm::Intrinsic::x86_flags_write_u32 ||
17389         IntNo == llvm::Intrinsic::x86_flags_write_u64) {
17390       // We need a frame pointer because this will get lowered to a PUSH/POP
17391       // sequence.
17392       MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17393       MFI->setHasOpaqueSPAdjustment(true);
17394       // Don't do anything here, we will expand these intrinsics out later
17395       // during ExpandISelPseudos in EmitInstrWithCustomInserter.
17396       return SDValue();
17397     }
17398     return SDValue();
17399   }
17400
17401   SDLoc dl(Op);
17402   switch(IntrData->Type) {
17403   default: llvm_unreachable("Unknown Intrinsic Type");
17404   case RDSEED:
17405   case RDRAND: {
17406     // Emit the node with the right value type.
17407     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17408     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17409
17410     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17411     // Otherwise return the value from Rand, which is always 0, casted to i32.
17412     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17413                       DAG.getConstant(1, dl, Op->getValueType(1)),
17414                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
17415                       SDValue(Result.getNode(), 1) };
17416     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17417                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17418                                   Ops);
17419
17420     // Return { result, isValid, chain }.
17421     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17422                        SDValue(Result.getNode(), 2));
17423   }
17424   case GATHER: {
17425   //gather(v1, mask, index, base, scale);
17426     SDValue Chain = Op.getOperand(0);
17427     SDValue Src   = Op.getOperand(2);
17428     SDValue Base  = Op.getOperand(3);
17429     SDValue Index = Op.getOperand(4);
17430     SDValue Mask  = Op.getOperand(5);
17431     SDValue Scale = Op.getOperand(6);
17432     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17433                          Chain, Subtarget);
17434   }
17435   case SCATTER: {
17436   //scatter(base, mask, index, v1, scale);
17437     SDValue Chain = Op.getOperand(0);
17438     SDValue Base  = Op.getOperand(2);
17439     SDValue Mask  = Op.getOperand(3);
17440     SDValue Index = Op.getOperand(4);
17441     SDValue Src   = Op.getOperand(5);
17442     SDValue Scale = Op.getOperand(6);
17443     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17444                           Scale, Chain);
17445   }
17446   case PREFETCH: {
17447     SDValue Hint = Op.getOperand(6);
17448     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17449     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17450     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17451     SDValue Chain = Op.getOperand(0);
17452     SDValue Mask  = Op.getOperand(2);
17453     SDValue Index = Op.getOperand(3);
17454     SDValue Base  = Op.getOperand(4);
17455     SDValue Scale = Op.getOperand(5);
17456     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17457   }
17458   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17459   case RDTSC: {
17460     SmallVector<SDValue, 2> Results;
17461     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17462                             Results);
17463     return DAG.getMergeValues(Results, dl);
17464   }
17465   // Read Performance Monitoring Counters.
17466   case RDPMC: {
17467     SmallVector<SDValue, 2> Results;
17468     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17469     return DAG.getMergeValues(Results, dl);
17470   }
17471   // XTEST intrinsics.
17472   case XTEST: {
17473     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17474     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17475     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17476                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17477                                 InTrans);
17478     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17479     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17480                        Ret, SDValue(InTrans.getNode(), 1));
17481   }
17482   // ADC/ADCX/SBB
17483   case ADX: {
17484     SmallVector<SDValue, 2> Results;
17485     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17486     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17487     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17488                                 DAG.getConstant(-1, dl, MVT::i8));
17489     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17490                               Op.getOperand(4), GenCF.getValue(1));
17491     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17492                                  Op.getOperand(5), MachinePointerInfo(),
17493                                  false, false, 0);
17494     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17495                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17496                                 Res.getValue(1));
17497     Results.push_back(SetCC);
17498     Results.push_back(Store);
17499     return DAG.getMergeValues(Results, dl);
17500   }
17501   case COMPRESS_TO_MEM: {
17502     SDLoc dl(Op);
17503     SDValue Mask = Op.getOperand(4);
17504     SDValue DataToCompress = Op.getOperand(3);
17505     SDValue Addr = Op.getOperand(2);
17506     SDValue Chain = Op.getOperand(0);
17507
17508     MVT VT = DataToCompress.getSimpleValueType();
17509     if (isAllOnesConstant(Mask)) // return just a store
17510       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17511                           MachinePointerInfo(), false, false,
17512                           VT.getScalarSizeInBits()/8);
17513
17514     SDValue Compressed =
17515       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17516                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17517     return DAG.getStore(Chain, dl, Compressed, Addr,
17518                         MachinePointerInfo(), false, false,
17519                         VT.getScalarSizeInBits()/8);
17520   }
17521   case TRUNCATE_TO_MEM_VI8:
17522     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17523   case TRUNCATE_TO_MEM_VI16:
17524     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17525   case TRUNCATE_TO_MEM_VI32:
17526     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17527   case EXPAND_FROM_MEM: {
17528     SDLoc dl(Op);
17529     SDValue Mask = Op.getOperand(4);
17530     SDValue PassThru = Op.getOperand(3);
17531     SDValue Addr = Op.getOperand(2);
17532     SDValue Chain = Op.getOperand(0);
17533     MVT VT = Op.getSimpleValueType();
17534
17535     if (isAllOnesConstant(Mask)) // return just a load
17536       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17537                          false, VT.getScalarSizeInBits()/8);
17538
17539     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17540                                        false, false, false,
17541                                        VT.getScalarSizeInBits()/8);
17542
17543     SDValue Results[] = {
17544       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17545                            Mask, PassThru, Subtarget, DAG), Chain};
17546     return DAG.getMergeValues(Results, dl);
17547   }
17548   }
17549 }
17550
17551 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17552                                            SelectionDAG &DAG) const {
17553   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17554   MFI->setReturnAddressIsTaken(true);
17555
17556   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17557     return SDValue();
17558
17559   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17560   SDLoc dl(Op);
17561   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17562
17563   if (Depth > 0) {
17564     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17565     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17566     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17567     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17568                        DAG.getNode(ISD::ADD, dl, PtrVT,
17569                                    FrameAddr, Offset),
17570                        MachinePointerInfo(), false, false, false, 0);
17571   }
17572
17573   // Just load the return address.
17574   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17575   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17576                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17577 }
17578
17579 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17580   MachineFunction &MF = DAG.getMachineFunction();
17581   MachineFrameInfo *MFI = MF.getFrameInfo();
17582   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17583   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17584   EVT VT = Op.getValueType();
17585
17586   MFI->setFrameAddressIsTaken(true);
17587
17588   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17589     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17590     // is not possible to crawl up the stack without looking at the unwind codes
17591     // simultaneously.
17592     int FrameAddrIndex = FuncInfo->getFAIndex();
17593     if (!FrameAddrIndex) {
17594       // Set up a frame object for the return address.
17595       unsigned SlotSize = RegInfo->getSlotSize();
17596       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17597           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17598       FuncInfo->setFAIndex(FrameAddrIndex);
17599     }
17600     return DAG.getFrameIndex(FrameAddrIndex, VT);
17601   }
17602
17603   unsigned FrameReg =
17604       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17605   SDLoc dl(Op);  // FIXME probably not meaningful
17606   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17607   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17608           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17609          "Invalid Frame Register!");
17610   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17611   while (Depth--)
17612     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17613                             MachinePointerInfo(),
17614                             false, false, false, 0);
17615   return FrameAddr;
17616 }
17617
17618 // FIXME? Maybe this could be a TableGen attribute on some registers and
17619 // this table could be generated automatically from RegInfo.
17620 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17621                                               SelectionDAG &DAG) const {
17622   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17623   const MachineFunction &MF = DAG.getMachineFunction();
17624
17625   unsigned Reg = StringSwitch<unsigned>(RegName)
17626                        .Case("esp", X86::ESP)
17627                        .Case("rsp", X86::RSP)
17628                        .Case("ebp", X86::EBP)
17629                        .Case("rbp", X86::RBP)
17630                        .Default(0);
17631
17632   if (Reg == X86::EBP || Reg == X86::RBP) {
17633     if (!TFI.hasFP(MF))
17634       report_fatal_error("register " + StringRef(RegName) +
17635                          " is allocatable: function has no frame pointer");
17636 #ifndef NDEBUG
17637     else {
17638       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17639       unsigned FrameReg =
17640           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17641       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17642              "Invalid Frame Register!");
17643     }
17644 #endif
17645   }
17646
17647   if (Reg)
17648     return Reg;
17649
17650   report_fatal_error("Invalid register name global variable");
17651 }
17652
17653 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17654                                                      SelectionDAG &DAG) const {
17655   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17656   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17657 }
17658
17659 unsigned X86TargetLowering::getExceptionPointerRegister(
17660     const Constant *PersonalityFn) const {
17661   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17662     return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17663
17664   return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17665 }
17666
17667 unsigned X86TargetLowering::getExceptionSelectorRegister(
17668     const Constant *PersonalityFn) const {
17669   // Funclet personalities don't use selectors (the runtime does the selection).
17670   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17671   return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17672 }
17673
17674 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17675   SDValue Chain     = Op.getOperand(0);
17676   SDValue Offset    = Op.getOperand(1);
17677   SDValue Handler   = Op.getOperand(2);
17678   SDLoc dl      (Op);
17679
17680   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17681   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17682   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17683   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17684           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17685          "Invalid Frame Register!");
17686   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17687   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17688
17689   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17690                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17691                                                        dl));
17692   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17693   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17694                        false, false, 0);
17695   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17696
17697   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17698                      DAG.getRegister(StoreAddrReg, PtrVT));
17699 }
17700
17701 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17702                                                SelectionDAG &DAG) const {
17703   SDLoc DL(Op);
17704   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17705                      DAG.getVTList(MVT::i32, MVT::Other),
17706                      Op.getOperand(0), Op.getOperand(1));
17707 }
17708
17709 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17710                                                 SelectionDAG &DAG) const {
17711   SDLoc DL(Op);
17712   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17713                      Op.getOperand(0), Op.getOperand(1));
17714 }
17715
17716 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17717   return Op.getOperand(0);
17718 }
17719
17720 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17721                                                 SelectionDAG &DAG) const {
17722   SDValue Root = Op.getOperand(0);
17723   SDValue Trmp = Op.getOperand(1); // trampoline
17724   SDValue FPtr = Op.getOperand(2); // nested function
17725   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17726   SDLoc dl (Op);
17727
17728   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17729   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17730
17731   if (Subtarget->is64Bit()) {
17732     SDValue OutChains[6];
17733
17734     // Large code-model.
17735     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17736     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17737
17738     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17739     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17740
17741     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17742
17743     // Load the pointer to the nested function into R11.
17744     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17745     SDValue Addr = Trmp;
17746     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17747                                 Addr, MachinePointerInfo(TrmpAddr),
17748                                 false, false, 0);
17749
17750     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17751                        DAG.getConstant(2, dl, MVT::i64));
17752     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17753                                 MachinePointerInfo(TrmpAddr, 2),
17754                                 false, false, 2);
17755
17756     // Load the 'nest' parameter value into R10.
17757     // R10 is specified in X86CallingConv.td
17758     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17759     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17760                        DAG.getConstant(10, dl, MVT::i64));
17761     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17762                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17763                                 false, false, 0);
17764
17765     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17766                        DAG.getConstant(12, dl, MVT::i64));
17767     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17768                                 MachinePointerInfo(TrmpAddr, 12),
17769                                 false, false, 2);
17770
17771     // Jump to the nested function.
17772     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17773     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17774                        DAG.getConstant(20, dl, MVT::i64));
17775     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17776                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17777                                 false, false, 0);
17778
17779     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17780     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17781                        DAG.getConstant(22, dl, MVT::i64));
17782     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17783                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17784                                 false, false, 0);
17785
17786     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17787   } else {
17788     const Function *Func =
17789       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17790     CallingConv::ID CC = Func->getCallingConv();
17791     unsigned NestReg;
17792
17793     switch (CC) {
17794     default:
17795       llvm_unreachable("Unsupported calling convention");
17796     case CallingConv::C:
17797     case CallingConv::X86_StdCall: {
17798       // Pass 'nest' parameter in ECX.
17799       // Must be kept in sync with X86CallingConv.td
17800       NestReg = X86::ECX;
17801
17802       // Check that ECX wasn't needed by an 'inreg' parameter.
17803       FunctionType *FTy = Func->getFunctionType();
17804       const AttributeSet &Attrs = Func->getAttributes();
17805
17806       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17807         unsigned InRegCount = 0;
17808         unsigned Idx = 1;
17809
17810         for (FunctionType::param_iterator I = FTy->param_begin(),
17811              E = FTy->param_end(); I != E; ++I, ++Idx)
17812           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17813             auto &DL = DAG.getDataLayout();
17814             // FIXME: should only count parameters that are lowered to integers.
17815             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17816           }
17817
17818         if (InRegCount > 2) {
17819           report_fatal_error("Nest register in use - reduce number of inreg"
17820                              " parameters!");
17821         }
17822       }
17823       break;
17824     }
17825     case CallingConv::X86_FastCall:
17826     case CallingConv::X86_ThisCall:
17827     case CallingConv::Fast:
17828       // Pass 'nest' parameter in EAX.
17829       // Must be kept in sync with X86CallingConv.td
17830       NestReg = X86::EAX;
17831       break;
17832     }
17833
17834     SDValue OutChains[4];
17835     SDValue Addr, Disp;
17836
17837     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17838                        DAG.getConstant(10, dl, MVT::i32));
17839     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17840
17841     // This is storing the opcode for MOV32ri.
17842     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17843     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17844     OutChains[0] = DAG.getStore(Root, dl,
17845                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17846                                 Trmp, MachinePointerInfo(TrmpAddr),
17847                                 false, false, 0);
17848
17849     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17850                        DAG.getConstant(1, dl, MVT::i32));
17851     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17852                                 MachinePointerInfo(TrmpAddr, 1),
17853                                 false, false, 1);
17854
17855     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17856     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17857                        DAG.getConstant(5, dl, MVT::i32));
17858     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17859                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17860                                 false, false, 1);
17861
17862     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17863                        DAG.getConstant(6, dl, MVT::i32));
17864     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17865                                 MachinePointerInfo(TrmpAddr, 6),
17866                                 false, false, 1);
17867
17868     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17869   }
17870 }
17871
17872 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17873                                             SelectionDAG &DAG) const {
17874   /*
17875    The rounding mode is in bits 11:10 of FPSR, and has the following
17876    settings:
17877      00 Round to nearest
17878      01 Round to -inf
17879      10 Round to +inf
17880      11 Round to 0
17881
17882   FLT_ROUNDS, on the other hand, expects the following:
17883     -1 Undefined
17884      0 Round to 0
17885      1 Round to nearest
17886      2 Round to +inf
17887      3 Round to -inf
17888
17889   To perform the conversion, we do:
17890     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17891   */
17892
17893   MachineFunction &MF = DAG.getMachineFunction();
17894   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17895   unsigned StackAlignment = TFI.getStackAlignment();
17896   MVT VT = Op.getSimpleValueType();
17897   SDLoc DL(Op);
17898
17899   // Save FP Control Word to stack slot
17900   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17901   SDValue StackSlot =
17902       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17903
17904   MachineMemOperand *MMO =
17905       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17906                               MachineMemOperand::MOStore, 2, 2);
17907
17908   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17909   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17910                                           DAG.getVTList(MVT::Other),
17911                                           Ops, MVT::i16, MMO);
17912
17913   // Load FP Control Word from stack slot
17914   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17915                             MachinePointerInfo(), false, false, false, 0);
17916
17917   // Transform as necessary
17918   SDValue CWD1 =
17919     DAG.getNode(ISD::SRL, DL, MVT::i16,
17920                 DAG.getNode(ISD::AND, DL, MVT::i16,
17921                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17922                 DAG.getConstant(11, DL, MVT::i8));
17923   SDValue CWD2 =
17924     DAG.getNode(ISD::SRL, DL, MVT::i16,
17925                 DAG.getNode(ISD::AND, DL, MVT::i16,
17926                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17927                 DAG.getConstant(9, DL, MVT::i8));
17928
17929   SDValue RetVal =
17930     DAG.getNode(ISD::AND, DL, MVT::i16,
17931                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17932                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17933                             DAG.getConstant(1, DL, MVT::i16)),
17934                 DAG.getConstant(3, DL, MVT::i16));
17935
17936   return DAG.getNode((VT.getSizeInBits() < 16 ?
17937                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17938 }
17939
17940 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17941 //
17942 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17943 //    to 512-bit vector.
17944 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17945 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17946 //    split the vector, perform operation on it's Lo a Hi part and
17947 //    concatenate the results.
17948 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17949   SDLoc dl(Op);
17950   MVT VT = Op.getSimpleValueType();
17951   MVT EltVT = VT.getVectorElementType();
17952   unsigned NumElems = VT.getVectorNumElements();
17953
17954   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17955     // Extend to 512 bit vector.
17956     assert((VT.is256BitVector() || VT.is128BitVector()) &&
17957               "Unsupported value type for operation");
17958
17959     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17960     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17961                                  DAG.getUNDEF(NewVT),
17962                                  Op.getOperand(0),
17963                                  DAG.getIntPtrConstant(0, dl));
17964     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17965
17966     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17967                        DAG.getIntPtrConstant(0, dl));
17968   }
17969
17970   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17971           "Unsupported element type");
17972
17973   if (16 < NumElems) {
17974     // Split vector, it's Lo and Hi parts will be handled in next iteration.
17975     SDValue Lo, Hi;
17976     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17977     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17978
17979     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17980     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17981
17982     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17983   }
17984
17985   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17986
17987   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17988           "Unsupported value type for operation");
17989
17990   // Use native supported vector instruction vplzcntd.
17991   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17992   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17993   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17994   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17995
17996   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17997 }
17998
17999 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
18000                          SelectionDAG &DAG) {
18001   MVT VT = Op.getSimpleValueType();
18002   MVT OpVT = VT;
18003   unsigned NumBits = VT.getSizeInBits();
18004   SDLoc dl(Op);
18005
18006   if (VT.isVector() && Subtarget->hasAVX512())
18007     return LowerVectorCTLZ_AVX512(Op, DAG);
18008
18009   Op = Op.getOperand(0);
18010   if (VT == MVT::i8) {
18011     // Zero extend to i32 since there is not an i8 bsr.
18012     OpVT = MVT::i32;
18013     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18014   }
18015
18016   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
18017   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18018   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18019
18020   // If src is zero (i.e. bsr sets ZF), returns NumBits.
18021   SDValue Ops[] = {
18022     Op,
18023     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
18024     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18025     Op.getValue(1)
18026   };
18027   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
18028
18029   // Finally xor with NumBits-1.
18030   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18031                    DAG.getConstant(NumBits - 1, dl, OpVT));
18032
18033   if (VT == MVT::i8)
18034     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18035   return Op;
18036 }
18037
18038 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
18039                                     SelectionDAG &DAG) {
18040   MVT VT = Op.getSimpleValueType();
18041   EVT OpVT = VT;
18042   unsigned NumBits = VT.getSizeInBits();
18043   SDLoc dl(Op);
18044
18045   Op = Op.getOperand(0);
18046   if (VT == MVT::i8) {
18047     // Zero extend to i32 since there is not an i8 bsr.
18048     OpVT = MVT::i32;
18049     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18050   }
18051
18052   // Issue a bsr (scan bits in reverse).
18053   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18054   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18055
18056   // And xor with NumBits-1.
18057   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18058                    DAG.getConstant(NumBits - 1, dl, OpVT));
18059
18060   if (VT == MVT::i8)
18061     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18062   return Op;
18063 }
18064
18065 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18066   MVT VT = Op.getSimpleValueType();
18067   unsigned NumBits = VT.getScalarSizeInBits();
18068   SDLoc dl(Op);
18069
18070   if (VT.isVector()) {
18071     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18072
18073     SDValue N0 = Op.getOperand(0);
18074     SDValue Zero = DAG.getConstant(0, dl, VT);
18075
18076     // lsb(x) = (x & -x)
18077     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
18078                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
18079
18080     // cttz_undef(x) = (width - 1) - ctlz(lsb)
18081     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
18082         TLI.isOperationLegal(ISD::CTLZ, VT)) {
18083       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
18084       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
18085                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
18086     }
18087
18088     // cttz(x) = ctpop(lsb - 1)
18089     SDValue One = DAG.getConstant(1, dl, VT);
18090     return DAG.getNode(ISD::CTPOP, dl, VT,
18091                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
18092   }
18093
18094   assert(Op.getOpcode() == ISD::CTTZ &&
18095          "Only scalar CTTZ requires custom lowering");
18096
18097   // Issue a bsf (scan bits forward) which also sets EFLAGS.
18098   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18099   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
18100
18101   // If src is zero (i.e. bsf sets ZF), returns NumBits.
18102   SDValue Ops[] = {
18103     Op,
18104     DAG.getConstant(NumBits, dl, VT),
18105     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18106     Op.getValue(1)
18107   };
18108   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18109 }
18110
18111 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18112 // ones, and then concatenate the result back.
18113 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18114   MVT VT = Op.getSimpleValueType();
18115
18116   assert(VT.is256BitVector() && VT.isInteger() &&
18117          "Unsupported value type for operation");
18118
18119   unsigned NumElems = VT.getVectorNumElements();
18120   SDLoc dl(Op);
18121
18122   // Extract the LHS vectors
18123   SDValue LHS = Op.getOperand(0);
18124   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18125   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18126
18127   // Extract the RHS vectors
18128   SDValue RHS = Op.getOperand(1);
18129   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18130   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18131
18132   MVT EltVT = VT.getVectorElementType();
18133   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18134
18135   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18136                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18137                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18138 }
18139
18140 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18141   if (Op.getValueType() == MVT::i1)
18142     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18143                        Op.getOperand(0), Op.getOperand(1));
18144   assert(Op.getSimpleValueType().is256BitVector() &&
18145          Op.getSimpleValueType().isInteger() &&
18146          "Only handle AVX 256-bit vector integer operation");
18147   return Lower256IntArith(Op, DAG);
18148 }
18149
18150 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18151   if (Op.getValueType() == MVT::i1)
18152     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18153                        Op.getOperand(0), Op.getOperand(1));
18154   assert(Op.getSimpleValueType().is256BitVector() &&
18155          Op.getSimpleValueType().isInteger() &&
18156          "Only handle AVX 256-bit vector integer operation");
18157   return Lower256IntArith(Op, DAG);
18158 }
18159
18160 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
18161   assert(Op.getSimpleValueType().is256BitVector() &&
18162          Op.getSimpleValueType().isInteger() &&
18163          "Only handle AVX 256-bit vector integer operation");
18164   return Lower256IntArith(Op, DAG);
18165 }
18166
18167 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18168                         SelectionDAG &DAG) {
18169   SDLoc dl(Op);
18170   MVT VT = Op.getSimpleValueType();
18171
18172   if (VT == MVT::i1)
18173     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
18174
18175   // Decompose 256-bit ops into smaller 128-bit ops.
18176   if (VT.is256BitVector() && !Subtarget->hasInt256())
18177     return Lower256IntArith(Op, DAG);
18178
18179   SDValue A = Op.getOperand(0);
18180   SDValue B = Op.getOperand(1);
18181
18182   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
18183   // pairs, multiply and truncate.
18184   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
18185     if (Subtarget->hasInt256()) {
18186       if (VT == MVT::v32i8) {
18187         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
18188         SDValue Lo = DAG.getIntPtrConstant(0, dl);
18189         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
18190         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
18191         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
18192         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
18193         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18194         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18195                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18196                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18197       }
18198
18199       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18200       return DAG.getNode(
18201           ISD::TRUNCATE, dl, VT,
18202           DAG.getNode(ISD::MUL, dl, ExVT,
18203                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18204                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18205     }
18206
18207     assert(VT == MVT::v16i8 &&
18208            "Pre-AVX2 support only supports v16i8 multiplication");
18209     MVT ExVT = MVT::v8i16;
18210
18211     // Extract the lo parts and sign extend to i16
18212     SDValue ALo, BLo;
18213     if (Subtarget->hasSSE41()) {
18214       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18215       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18216     } else {
18217       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18218                               -1, 4, -1, 5, -1, 6, -1, 7};
18219       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18220       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18221       ALo = DAG.getBitcast(ExVT, ALo);
18222       BLo = DAG.getBitcast(ExVT, BLo);
18223       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18224       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18225     }
18226
18227     // Extract the hi parts and sign extend to i16
18228     SDValue AHi, BHi;
18229     if (Subtarget->hasSSE41()) {
18230       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
18231                               -1, -1, -1, -1, -1, -1, -1, -1};
18232       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18233       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18234       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18235       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18236     } else {
18237       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
18238                               -1, 12, -1, 13, -1, 14, -1, 15};
18239       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18240       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18241       AHi = DAG.getBitcast(ExVT, AHi);
18242       BHi = DAG.getBitcast(ExVT, BHi);
18243       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18244       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18245     }
18246
18247     // Multiply, mask the lower 8bits of the lo/hi results and pack
18248     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18249     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18250     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18251     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18252     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18253   }
18254
18255   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18256   if (VT == MVT::v4i32) {
18257     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18258            "Should not custom lower when pmuldq is available!");
18259
18260     // Extract the odd parts.
18261     static const int UnpackMask[] = { 1, -1, 3, -1 };
18262     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18263     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18264
18265     // Multiply the even parts.
18266     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18267     // Now multiply odd parts.
18268     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18269
18270     Evens = DAG.getBitcast(VT, Evens);
18271     Odds = DAG.getBitcast(VT, Odds);
18272
18273     // Merge the two vectors back together with a shuffle. This expands into 2
18274     // shuffles.
18275     static const int ShufMask[] = { 0, 4, 2, 6 };
18276     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18277   }
18278
18279   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18280          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18281
18282   //  Ahi = psrlqi(a, 32);
18283   //  Bhi = psrlqi(b, 32);
18284   //
18285   //  AloBlo = pmuludq(a, b);
18286   //  AloBhi = pmuludq(a, Bhi);
18287   //  AhiBlo = pmuludq(Ahi, b);
18288
18289   //  AloBhi = psllqi(AloBhi, 32);
18290   //  AhiBlo = psllqi(AhiBlo, 32);
18291   //  return AloBlo + AloBhi + AhiBlo;
18292
18293   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18294   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18295
18296   SDValue AhiBlo = Ahi;
18297   SDValue AloBhi = Bhi;
18298   // Bit cast to 32-bit vectors for MULUDQ
18299   MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18300                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18301   A = DAG.getBitcast(MulVT, A);
18302   B = DAG.getBitcast(MulVT, B);
18303   Ahi = DAG.getBitcast(MulVT, Ahi);
18304   Bhi = DAG.getBitcast(MulVT, Bhi);
18305
18306   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18307   // After shifting right const values the result may be all-zero.
18308   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18309     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18310     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18311   }
18312   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18313     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18314     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18315   }
18316
18317   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18318   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18319 }
18320
18321 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18322   assert(Subtarget->isTargetWin64() && "Unexpected target");
18323   EVT VT = Op.getValueType();
18324   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18325          "Unexpected return type for lowering");
18326
18327   RTLIB::Libcall LC;
18328   bool isSigned;
18329   switch (Op->getOpcode()) {
18330   default: llvm_unreachable("Unexpected request for libcall!");
18331   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18332   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18333   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18334   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18335   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18336   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18337   }
18338
18339   SDLoc dl(Op);
18340   SDValue InChain = DAG.getEntryNode();
18341
18342   TargetLowering::ArgListTy Args;
18343   TargetLowering::ArgListEntry Entry;
18344   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18345     EVT ArgVT = Op->getOperand(i).getValueType();
18346     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18347            "Unexpected argument type for lowering");
18348     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18349     Entry.Node = StackPtr;
18350     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18351                            false, false, 16);
18352     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18353     Entry.Ty = PointerType::get(ArgTy,0);
18354     Entry.isSExt = false;
18355     Entry.isZExt = false;
18356     Args.push_back(Entry);
18357   }
18358
18359   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18360                                          getPointerTy(DAG.getDataLayout()));
18361
18362   TargetLowering::CallLoweringInfo CLI(DAG);
18363   CLI.setDebugLoc(dl).setChain(InChain)
18364     .setCallee(getLibcallCallingConv(LC),
18365                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18366                Callee, std::move(Args), 0)
18367     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18368
18369   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18370   return DAG.getBitcast(VT, CallInfo.first);
18371 }
18372
18373 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18374                              SelectionDAG &DAG) {
18375   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18376   MVT VT = Op0.getSimpleValueType();
18377   SDLoc dl(Op);
18378
18379   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18380          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18381
18382   // PMULxD operations multiply each even value (starting at 0) of LHS with
18383   // the related value of RHS and produce a widen result.
18384   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18385   // => <2 x i64> <ae|cg>
18386   //
18387   // In other word, to have all the results, we need to perform two PMULxD:
18388   // 1. one with the even values.
18389   // 2. one with the odd values.
18390   // To achieve #2, with need to place the odd values at an even position.
18391   //
18392   // Place the odd value at an even position (basically, shift all values 1
18393   // step to the left):
18394   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18395   // <a|b|c|d> => <b|undef|d|undef>
18396   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18397   // <e|f|g|h> => <f|undef|h|undef>
18398   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18399
18400   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18401   // ints.
18402   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18403   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18404   unsigned Opcode =
18405       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18406   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18407   // => <2 x i64> <ae|cg>
18408   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18409   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18410   // => <2 x i64> <bf|dh>
18411   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18412
18413   // Shuffle it back into the right order.
18414   SDValue Highs, Lows;
18415   if (VT == MVT::v8i32) {
18416     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18417     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18418     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18419     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18420   } else {
18421     const int HighMask[] = {1, 5, 3, 7};
18422     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18423     const int LowMask[] = {0, 4, 2, 6};
18424     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18425   }
18426
18427   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18428   // unsigned multiply.
18429   if (IsSigned && !Subtarget->hasSSE41()) {
18430     SDValue ShAmt = DAG.getConstant(
18431         31, dl,
18432         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18433     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18434                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18435     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18436                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18437
18438     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18439     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18440   }
18441
18442   // The first result of MUL_LOHI is actually the low value, followed by the
18443   // high value.
18444   SDValue Ops[] = {Lows, Highs};
18445   return DAG.getMergeValues(Ops, dl);
18446 }
18447
18448 // Return true if the required (according to Opcode) shift-imm form is natively
18449 // supported by the Subtarget
18450 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18451                                         unsigned Opcode) {
18452   if (VT.getScalarSizeInBits() < 16)
18453     return false;
18454
18455   if (VT.is512BitVector() &&
18456       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18457     return true;
18458
18459   bool LShift = VT.is128BitVector() ||
18460     (VT.is256BitVector() && Subtarget->hasInt256());
18461
18462   bool AShift = LShift && (Subtarget->hasVLX() ||
18463     (VT != MVT::v2i64 && VT != MVT::v4i64));
18464   return (Opcode == ISD::SRA) ? AShift : LShift;
18465 }
18466
18467 // The shift amount is a variable, but it is the same for all vector lanes.
18468 // These instructions are defined together with shift-immediate.
18469 static
18470 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18471                                       unsigned Opcode) {
18472   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18473 }
18474
18475 // Return true if the required (according to Opcode) variable-shift form is
18476 // natively supported by the Subtarget
18477 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18478                                     unsigned Opcode) {
18479
18480   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18481     return false;
18482
18483   // vXi16 supported only on AVX-512, BWI
18484   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18485     return false;
18486
18487   if (VT.is512BitVector() || Subtarget->hasVLX())
18488     return true;
18489
18490   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18491   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18492   return (Opcode == ISD::SRA) ? AShift : LShift;
18493 }
18494
18495 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18496                                          const X86Subtarget *Subtarget) {
18497   MVT VT = Op.getSimpleValueType();
18498   SDLoc dl(Op);
18499   SDValue R = Op.getOperand(0);
18500   SDValue Amt = Op.getOperand(1);
18501
18502   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18503     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18504
18505   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18506     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18507     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18508     SDValue Ex = DAG.getBitcast(ExVT, R);
18509
18510     if (ShiftAmt >= 32) {
18511       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18512       SDValue Upper =
18513           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18514       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18515                                                  ShiftAmt - 32, DAG);
18516       if (VT == MVT::v2i64)
18517         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18518       if (VT == MVT::v4i64)
18519         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18520                                   {9, 1, 11, 3, 13, 5, 15, 7});
18521     } else {
18522       // SRA upper i32, SHL whole i64 and select lower i32.
18523       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18524                                                  ShiftAmt, DAG);
18525       SDValue Lower =
18526           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18527       Lower = DAG.getBitcast(ExVT, Lower);
18528       if (VT == MVT::v2i64)
18529         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18530       if (VT == MVT::v4i64)
18531         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18532                                   {8, 1, 10, 3, 12, 5, 14, 7});
18533     }
18534     return DAG.getBitcast(VT, Ex);
18535   };
18536
18537   // Optimize shl/srl/sra with constant shift amount.
18538   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18539     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18540       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18541
18542       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18543         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18544
18545       // i64 SRA needs to be performed as partial shifts.
18546       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18547           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18548         return ArithmeticShiftRight64(ShiftAmt);
18549
18550       if (VT == MVT::v16i8 ||
18551           (Subtarget->hasInt256() && VT == MVT::v32i8) ||
18552           VT == MVT::v64i8) {
18553         unsigned NumElts = VT.getVectorNumElements();
18554         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18555
18556         // Simple i8 add case
18557         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18558           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18559
18560         // ashr(R, 7)  === cmp_slt(R, 0)
18561         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18562           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18563           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18564         }
18565
18566         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18567         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18568           return SDValue();
18569
18570         if (Op.getOpcode() == ISD::SHL) {
18571           // Make a large shift.
18572           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18573                                                    R, ShiftAmt, DAG);
18574           SHL = DAG.getBitcast(VT, SHL);
18575           // Zero out the rightmost bits.
18576           return DAG.getNode(ISD::AND, dl, VT, SHL,
18577                              DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
18578         }
18579         if (Op.getOpcode() == ISD::SRL) {
18580           // Make a large shift.
18581           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18582                                                    R, ShiftAmt, DAG);
18583           SRL = DAG.getBitcast(VT, SRL);
18584           // Zero out the leftmost bits.
18585           return DAG.getNode(ISD::AND, dl, VT, SRL,
18586                              DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
18587         }
18588         if (Op.getOpcode() == ISD::SRA) {
18589           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18590           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18591
18592           SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
18593           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18594           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18595           return Res;
18596         }
18597         llvm_unreachable("Unknown shift opcode.");
18598       }
18599     }
18600   }
18601
18602   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18603   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18604       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18605
18606     // Peek through any splat that was introduced for i64 shift vectorization.
18607     int SplatIndex = -1;
18608     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18609       if (SVN->isSplat()) {
18610         SplatIndex = SVN->getSplatIndex();
18611         Amt = Amt.getOperand(0);
18612         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18613                "Splat shuffle referencing second operand");
18614       }
18615
18616     if (Amt.getOpcode() != ISD::BITCAST ||
18617         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18618       return SDValue();
18619
18620     Amt = Amt.getOperand(0);
18621     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18622                      VT.getVectorNumElements();
18623     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18624     uint64_t ShiftAmt = 0;
18625     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18626     for (unsigned i = 0; i != Ratio; ++i) {
18627       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18628       if (!C)
18629         return SDValue();
18630       // 6 == Log2(64)
18631       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18632     }
18633
18634     // Check remaining shift amounts (if not a splat).
18635     if (SplatIndex < 0) {
18636       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18637         uint64_t ShAmt = 0;
18638         for (unsigned j = 0; j != Ratio; ++j) {
18639           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18640           if (!C)
18641             return SDValue();
18642           // 6 == Log2(64)
18643           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18644         }
18645         if (ShAmt != ShiftAmt)
18646           return SDValue();
18647       }
18648     }
18649
18650     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18651       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18652
18653     if (Op.getOpcode() == ISD::SRA)
18654       return ArithmeticShiftRight64(ShiftAmt);
18655   }
18656
18657   return SDValue();
18658 }
18659
18660 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18661                                         const X86Subtarget* Subtarget) {
18662   MVT VT = Op.getSimpleValueType();
18663   SDLoc dl(Op);
18664   SDValue R = Op.getOperand(0);
18665   SDValue Amt = Op.getOperand(1);
18666
18667   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18668     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18669
18670   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18671     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18672
18673   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18674     SDValue BaseShAmt;
18675     MVT EltVT = VT.getVectorElementType();
18676
18677     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18678       // Check if this build_vector node is doing a splat.
18679       // If so, then set BaseShAmt equal to the splat value.
18680       BaseShAmt = BV->getSplatValue();
18681       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18682         BaseShAmt = SDValue();
18683     } else {
18684       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18685         Amt = Amt.getOperand(0);
18686
18687       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18688       if (SVN && SVN->isSplat()) {
18689         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18690         SDValue InVec = Amt.getOperand(0);
18691         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18692           assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18693                  "Unexpected shuffle index found!");
18694           BaseShAmt = InVec.getOperand(SplatIdx);
18695         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18696            if (ConstantSDNode *C =
18697                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18698              if (C->getZExtValue() == SplatIdx)
18699                BaseShAmt = InVec.getOperand(1);
18700            }
18701         }
18702
18703         if (!BaseShAmt)
18704           // Avoid introducing an extract element from a shuffle.
18705           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18706                                   DAG.getIntPtrConstant(SplatIdx, dl));
18707       }
18708     }
18709
18710     if (BaseShAmt.getNode()) {
18711       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18712       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18713         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18714       else if (EltVT.bitsLT(MVT::i32))
18715         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18716
18717       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18718     }
18719   }
18720
18721   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18722   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18723       Amt.getOpcode() == ISD::BITCAST &&
18724       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18725     Amt = Amt.getOperand(0);
18726     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18727                      VT.getVectorNumElements();
18728     std::vector<SDValue> Vals(Ratio);
18729     for (unsigned i = 0; i != Ratio; ++i)
18730       Vals[i] = Amt.getOperand(i);
18731     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18732       for (unsigned j = 0; j != Ratio; ++j)
18733         if (Vals[j] != Amt.getOperand(i + j))
18734           return SDValue();
18735     }
18736
18737     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18738       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18739   }
18740   return SDValue();
18741 }
18742
18743 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18744                           SelectionDAG &DAG) {
18745   MVT VT = Op.getSimpleValueType();
18746   SDLoc dl(Op);
18747   SDValue R = Op.getOperand(0);
18748   SDValue Amt = Op.getOperand(1);
18749
18750   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18751   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18752
18753   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18754     return V;
18755
18756   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18757     return V;
18758
18759   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18760     return Op;
18761
18762   // XOP has 128-bit variable logical/arithmetic shifts.
18763   // +ve/-ve Amt = shift left/right.
18764   if (Subtarget->hasXOP() &&
18765       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18766        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18767     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18768       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18769       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18770     }
18771     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18772       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18773     if (Op.getOpcode() == ISD::SRA)
18774       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18775   }
18776
18777   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18778   // shifts per-lane and then shuffle the partial results back together.
18779   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18780     // Splat the shift amounts so the scalar shifts above will catch it.
18781     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18782     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18783     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18784     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18785     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18786   }
18787
18788   // i64 vector arithmetic shift can be emulated with the transform:
18789   // M = lshr(SIGN_BIT, Amt)
18790   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18791   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18792       Op.getOpcode() == ISD::SRA) {
18793     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18794     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18795     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18796     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18797     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18798     return R;
18799   }
18800
18801   // If possible, lower this packed shift into a vector multiply instead of
18802   // expanding it into a sequence of scalar shifts.
18803   // Do this only if the vector shift count is a constant build_vector.
18804   if (Op.getOpcode() == ISD::SHL &&
18805       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18806        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18807       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18808     SmallVector<SDValue, 8> Elts;
18809     MVT SVT = VT.getVectorElementType();
18810     unsigned SVTBits = SVT.getSizeInBits();
18811     APInt One(SVTBits, 1);
18812     unsigned NumElems = VT.getVectorNumElements();
18813
18814     for (unsigned i=0; i !=NumElems; ++i) {
18815       SDValue Op = Amt->getOperand(i);
18816       if (Op->getOpcode() == ISD::UNDEF) {
18817         Elts.push_back(Op);
18818         continue;
18819       }
18820
18821       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18822       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18823       uint64_t ShAmt = C.getZExtValue();
18824       if (ShAmt >= SVTBits) {
18825         Elts.push_back(DAG.getUNDEF(SVT));
18826         continue;
18827       }
18828       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18829     }
18830     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18831     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18832   }
18833
18834   // Lower SHL with variable shift amount.
18835   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18836     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18837
18838     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18839                      DAG.getConstant(0x3f800000U, dl, VT));
18840     Op = DAG.getBitcast(MVT::v4f32, Op);
18841     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18842     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18843   }
18844
18845   // If possible, lower this shift as a sequence of two shifts by
18846   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18847   // Example:
18848   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18849   //
18850   // Could be rewritten as:
18851   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18852   //
18853   // The advantage is that the two shifts from the example would be
18854   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18855   // the vector shift into four scalar shifts plus four pairs of vector
18856   // insert/extract.
18857   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18858       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18859     unsigned TargetOpcode = X86ISD::MOVSS;
18860     bool CanBeSimplified;
18861     // The splat value for the first packed shift (the 'X' from the example).
18862     SDValue Amt1 = Amt->getOperand(0);
18863     // The splat value for the second packed shift (the 'Y' from the example).
18864     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18865                                         Amt->getOperand(2);
18866
18867     // See if it is possible to replace this node with a sequence of
18868     // two shifts followed by a MOVSS/MOVSD
18869     if (VT == MVT::v4i32) {
18870       // Check if it is legal to use a MOVSS.
18871       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18872                         Amt2 == Amt->getOperand(3);
18873       if (!CanBeSimplified) {
18874         // Otherwise, check if we can still simplify this node using a MOVSD.
18875         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18876                           Amt->getOperand(2) == Amt->getOperand(3);
18877         TargetOpcode = X86ISD::MOVSD;
18878         Amt2 = Amt->getOperand(2);
18879       }
18880     } else {
18881       // Do similar checks for the case where the machine value type
18882       // is MVT::v8i16.
18883       CanBeSimplified = Amt1 == Amt->getOperand(1);
18884       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18885         CanBeSimplified = Amt2 == Amt->getOperand(i);
18886
18887       if (!CanBeSimplified) {
18888         TargetOpcode = X86ISD::MOVSD;
18889         CanBeSimplified = true;
18890         Amt2 = Amt->getOperand(4);
18891         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18892           CanBeSimplified = Amt1 == Amt->getOperand(i);
18893         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18894           CanBeSimplified = Amt2 == Amt->getOperand(j);
18895       }
18896     }
18897
18898     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18899         isa<ConstantSDNode>(Amt2)) {
18900       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18901       MVT CastVT = MVT::v4i32;
18902       SDValue Splat1 =
18903         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18904       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18905       SDValue Splat2 =
18906         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18907       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18908       if (TargetOpcode == X86ISD::MOVSD)
18909         CastVT = MVT::v2i64;
18910       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18911       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18912       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18913                                             BitCast1, DAG);
18914       return DAG.getBitcast(VT, Result);
18915     }
18916   }
18917
18918   // v4i32 Non Uniform Shifts.
18919   // If the shift amount is constant we can shift each lane using the SSE2
18920   // immediate shifts, else we need to zero-extend each lane to the lower i64
18921   // and shift using the SSE2 variable shifts.
18922   // The separate results can then be blended together.
18923   if (VT == MVT::v4i32) {
18924     unsigned Opc = Op.getOpcode();
18925     SDValue Amt0, Amt1, Amt2, Amt3;
18926     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18927       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18928       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18929       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18930       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18931     } else {
18932       // ISD::SHL is handled above but we include it here for completeness.
18933       switch (Opc) {
18934       default:
18935         llvm_unreachable("Unknown target vector shift node");
18936       case ISD::SHL:
18937         Opc = X86ISD::VSHL;
18938         break;
18939       case ISD::SRL:
18940         Opc = X86ISD::VSRL;
18941         break;
18942       case ISD::SRA:
18943         Opc = X86ISD::VSRA;
18944         break;
18945       }
18946       // The SSE2 shifts use the lower i64 as the same shift amount for
18947       // all lanes and the upper i64 is ignored. These shuffle masks
18948       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18949       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18950       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18951       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18952       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18953       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18954     }
18955
18956     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18957     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18958     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18959     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18960     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18961     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18962     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18963   }
18964
18965   if (VT == MVT::v16i8 ||
18966       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18967     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18968     unsigned ShiftOpcode = Op->getOpcode();
18969
18970     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18971       // On SSE41 targets we make use of the fact that VSELECT lowers
18972       // to PBLENDVB which selects bytes based just on the sign bit.
18973       if (Subtarget->hasSSE41()) {
18974         V0 = DAG.getBitcast(VT, V0);
18975         V1 = DAG.getBitcast(VT, V1);
18976         Sel = DAG.getBitcast(VT, Sel);
18977         return DAG.getBitcast(SelVT,
18978                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18979       }
18980       // On pre-SSE41 targets we test for the sign bit by comparing to
18981       // zero - a negative value will set all bits of the lanes to true
18982       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18983       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18984       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18985       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18986     };
18987
18988     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18989     // We can safely do this using i16 shifts as we're only interested in
18990     // the 3 lower bits of each byte.
18991     Amt = DAG.getBitcast(ExtVT, Amt);
18992     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18993     Amt = DAG.getBitcast(VT, Amt);
18994
18995     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18996       // r = VSELECT(r, shift(r, 4), a);
18997       SDValue M =
18998           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18999       R = SignBitSelect(VT, Amt, M, R);
19000
19001       // a += a
19002       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19003
19004       // r = VSELECT(r, shift(r, 2), a);
19005       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19006       R = SignBitSelect(VT, Amt, M, R);
19007
19008       // a += a
19009       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19010
19011       // return VSELECT(r, shift(r, 1), a);
19012       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19013       R = SignBitSelect(VT, Amt, M, R);
19014       return R;
19015     }
19016
19017     if (Op->getOpcode() == ISD::SRA) {
19018       // For SRA we need to unpack each byte to the higher byte of a i16 vector
19019       // so we can correctly sign extend. We don't care what happens to the
19020       // lower byte.
19021       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
19022       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
19023       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
19024       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
19025       ALo = DAG.getBitcast(ExtVT, ALo);
19026       AHi = DAG.getBitcast(ExtVT, AHi);
19027       RLo = DAG.getBitcast(ExtVT, RLo);
19028       RHi = DAG.getBitcast(ExtVT, RHi);
19029
19030       // r = VSELECT(r, shift(r, 4), a);
19031       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19032                                 DAG.getConstant(4, dl, ExtVT));
19033       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19034                                 DAG.getConstant(4, dl, ExtVT));
19035       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19036       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19037
19038       // a += a
19039       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19040       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19041
19042       // r = VSELECT(r, shift(r, 2), a);
19043       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19044                         DAG.getConstant(2, dl, ExtVT));
19045       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19046                         DAG.getConstant(2, dl, ExtVT));
19047       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19048       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19049
19050       // a += a
19051       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19052       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19053
19054       // r = VSELECT(r, shift(r, 1), a);
19055       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19056                         DAG.getConstant(1, dl, ExtVT));
19057       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19058                         DAG.getConstant(1, dl, ExtVT));
19059       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19060       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19061
19062       // Logical shift the result back to the lower byte, leaving a zero upper
19063       // byte
19064       // meaning that we can safely pack with PACKUSWB.
19065       RLo =
19066           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
19067       RHi =
19068           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
19069       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
19070     }
19071   }
19072
19073   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
19074   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
19075   // solution better.
19076   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
19077     MVT ExtVT = MVT::v8i32;
19078     unsigned ExtOpc =
19079         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19080     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
19081     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
19082     return DAG.getNode(ISD::TRUNCATE, dl, VT,
19083                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
19084   }
19085
19086   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
19087     MVT ExtVT = MVT::v8i32;
19088     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19089     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
19090     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
19091     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
19092     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
19093     ALo = DAG.getBitcast(ExtVT, ALo);
19094     AHi = DAG.getBitcast(ExtVT, AHi);
19095     RLo = DAG.getBitcast(ExtVT, RLo);
19096     RHi = DAG.getBitcast(ExtVT, RHi);
19097     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
19098     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
19099     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
19100     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
19101     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
19102   }
19103
19104   if (VT == MVT::v8i16) {
19105     unsigned ShiftOpcode = Op->getOpcode();
19106
19107     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
19108       // On SSE41 targets we make use of the fact that VSELECT lowers
19109       // to PBLENDVB which selects bytes based just on the sign bit.
19110       if (Subtarget->hasSSE41()) {
19111         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
19112         V0 = DAG.getBitcast(ExtVT, V0);
19113         V1 = DAG.getBitcast(ExtVT, V1);
19114         Sel = DAG.getBitcast(ExtVT, Sel);
19115         return DAG.getBitcast(
19116             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
19117       }
19118       // On pre-SSE41 targets we splat the sign bit - a negative value will
19119       // set all bits of the lanes to true and VSELECT uses that in
19120       // its OR(AND(V0,C),AND(V1,~C)) lowering.
19121       SDValue C =
19122           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
19123       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
19124     };
19125
19126     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
19127     if (Subtarget->hasSSE41()) {
19128       // On SSE41 targets we need to replicate the shift mask in both
19129       // bytes for PBLENDVB.
19130       Amt = DAG.getNode(
19131           ISD::OR, dl, VT,
19132           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
19133           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
19134     } else {
19135       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
19136     }
19137
19138     // r = VSELECT(r, shift(r, 8), a);
19139     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
19140     R = SignBitSelect(Amt, M, R);
19141
19142     // a += a
19143     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19144
19145     // r = VSELECT(r, shift(r, 4), a);
19146     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19147     R = SignBitSelect(Amt, M, R);
19148
19149     // a += a
19150     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19151
19152     // r = VSELECT(r, shift(r, 2), a);
19153     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19154     R = SignBitSelect(Amt, M, R);
19155
19156     // a += a
19157     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19158
19159     // return VSELECT(r, shift(r, 1), a);
19160     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19161     R = SignBitSelect(Amt, M, R);
19162     return R;
19163   }
19164
19165   // Decompose 256-bit shifts into smaller 128-bit shifts.
19166   if (VT.is256BitVector()) {
19167     unsigned NumElems = VT.getVectorNumElements();
19168     MVT EltVT = VT.getVectorElementType();
19169     MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19170
19171     // Extract the two vectors
19172     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
19173     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
19174
19175     // Recreate the shift amount vectors
19176     SDValue Amt1, Amt2;
19177     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
19178       // Constant shift amount
19179       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
19180       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
19181       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
19182
19183       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
19184       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
19185     } else {
19186       // Variable shift amount
19187       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19188       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19189     }
19190
19191     // Issue new vector shifts for the smaller types
19192     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19193     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19194
19195     // Concatenate the result back
19196     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19197   }
19198
19199   return SDValue();
19200 }
19201
19202 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19203                            SelectionDAG &DAG) {
19204   MVT VT = Op.getSimpleValueType();
19205   SDLoc DL(Op);
19206   SDValue R = Op.getOperand(0);
19207   SDValue Amt = Op.getOperand(1);
19208
19209   assert(VT.isVector() && "Custom lowering only for vector rotates!");
19210   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19211   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19212
19213   // XOP has 128-bit vector variable + immediate rotates.
19214   // +ve/-ve Amt = rotate left/right.
19215
19216   // Split 256-bit integers.
19217   if (VT.is256BitVector())
19218     return Lower256IntArith(Op, DAG);
19219
19220   assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19221
19222   // Attempt to rotate by immediate.
19223   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19224     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19225       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19226       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19227       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19228                          DAG.getConstant(RotateAmt, DL, MVT::i8));
19229     }
19230   }
19231
19232   // Use general rotate by variable (per-element).
19233   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19234 }
19235
19236 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19237   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19238   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19239   // looks for this combo and may remove the "setcc" instruction if the "setcc"
19240   // has only one use.
19241   SDNode *N = Op.getNode();
19242   SDValue LHS = N->getOperand(0);
19243   SDValue RHS = N->getOperand(1);
19244   unsigned BaseOp = 0;
19245   unsigned Cond = 0;
19246   SDLoc DL(Op);
19247   switch (Op.getOpcode()) {
19248   default: llvm_unreachable("Unknown ovf instruction!");
19249   case ISD::SADDO:
19250     // A subtract of one will be selected as a INC. Note that INC doesn't
19251     // set CF, so we can't do this for UADDO.
19252     if (isOneConstant(RHS)) {
19253         BaseOp = X86ISD::INC;
19254         Cond = X86::COND_O;
19255         break;
19256       }
19257     BaseOp = X86ISD::ADD;
19258     Cond = X86::COND_O;
19259     break;
19260   case ISD::UADDO:
19261     BaseOp = X86ISD::ADD;
19262     Cond = X86::COND_B;
19263     break;
19264   case ISD::SSUBO:
19265     // A subtract of one will be selected as a DEC. Note that DEC doesn't
19266     // set CF, so we can't do this for USUBO.
19267     if (isOneConstant(RHS)) {
19268         BaseOp = X86ISD::DEC;
19269         Cond = X86::COND_O;
19270         break;
19271       }
19272     BaseOp = X86ISD::SUB;
19273     Cond = X86::COND_O;
19274     break;
19275   case ISD::USUBO:
19276     BaseOp = X86ISD::SUB;
19277     Cond = X86::COND_B;
19278     break;
19279   case ISD::SMULO:
19280     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19281     Cond = X86::COND_O;
19282     break;
19283   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19284     if (N->getValueType(0) == MVT::i8) {
19285       BaseOp = X86ISD::UMUL8;
19286       Cond = X86::COND_O;
19287       break;
19288     }
19289     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19290                                  MVT::i32);
19291     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19292
19293     SDValue SetCC =
19294       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19295                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
19296                   SDValue(Sum.getNode(), 2));
19297
19298     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19299   }
19300   }
19301
19302   // Also sets EFLAGS.
19303   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19304   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19305
19306   SDValue SetCC =
19307     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19308                 DAG.getConstant(Cond, DL, MVT::i32),
19309                 SDValue(Sum.getNode(), 1));
19310
19311   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19312 }
19313
19314 /// Returns true if the operand type is exactly twice the native width, and
19315 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19316 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19317 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19318 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19319   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19320
19321   if (OpWidth == 64)
19322     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19323   else if (OpWidth == 128)
19324     return Subtarget->hasCmpxchg16b();
19325   else
19326     return false;
19327 }
19328
19329 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19330   return needsCmpXchgNb(SI->getValueOperand()->getType());
19331 }
19332
19333 // Note: this turns large loads into lock cmpxchg8b/16b.
19334 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19335 TargetLowering::AtomicExpansionKind
19336 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19337   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19338   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19339                                                : AtomicExpansionKind::None;
19340 }
19341
19342 TargetLowering::AtomicExpansionKind
19343 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19344   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19345   Type *MemType = AI->getType();
19346
19347   // If the operand is too big, we must see if cmpxchg8/16b is available
19348   // and default to library calls otherwise.
19349   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19350     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19351                                    : AtomicExpansionKind::None;
19352   }
19353
19354   AtomicRMWInst::BinOp Op = AI->getOperation();
19355   switch (Op) {
19356   default:
19357     llvm_unreachable("Unknown atomic operation");
19358   case AtomicRMWInst::Xchg:
19359   case AtomicRMWInst::Add:
19360   case AtomicRMWInst::Sub:
19361     // It's better to use xadd, xsub or xchg for these in all cases.
19362     return AtomicExpansionKind::None;
19363   case AtomicRMWInst::Or:
19364   case AtomicRMWInst::And:
19365   case AtomicRMWInst::Xor:
19366     // If the atomicrmw's result isn't actually used, we can just add a "lock"
19367     // prefix to a normal instruction for these operations.
19368     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19369                             : AtomicExpansionKind::None;
19370   case AtomicRMWInst::Nand:
19371   case AtomicRMWInst::Max:
19372   case AtomicRMWInst::Min:
19373   case AtomicRMWInst::UMax:
19374   case AtomicRMWInst::UMin:
19375     // These always require a non-trivial set of data operations on x86. We must
19376     // use a cmpxchg loop.
19377     return AtomicExpansionKind::CmpXChg;
19378   }
19379 }
19380
19381 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19382   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19383   // no-sse2). There isn't any reason to disable it if the target processor
19384   // supports it.
19385   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19386 }
19387
19388 LoadInst *
19389 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19390   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19391   Type *MemType = AI->getType();
19392   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19393   // there is no benefit in turning such RMWs into loads, and it is actually
19394   // harmful as it introduces a mfence.
19395   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19396     return nullptr;
19397
19398   auto Builder = IRBuilder<>(AI);
19399   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19400   auto SynchScope = AI->getSynchScope();
19401   // We must restrict the ordering to avoid generating loads with Release or
19402   // ReleaseAcquire orderings.
19403   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19404   auto Ptr = AI->getPointerOperand();
19405
19406   // Before the load we need a fence. Here is an example lifted from
19407   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19408   // is required:
19409   // Thread 0:
19410   //   x.store(1, relaxed);
19411   //   r1 = y.fetch_add(0, release);
19412   // Thread 1:
19413   //   y.fetch_add(42, acquire);
19414   //   r2 = x.load(relaxed);
19415   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19416   // lowered to just a load without a fence. A mfence flushes the store buffer,
19417   // making the optimization clearly correct.
19418   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19419   // otherwise, we might be able to be more aggressive on relaxed idempotent
19420   // rmw. In practice, they do not look useful, so we don't try to be
19421   // especially clever.
19422   if (SynchScope == SingleThread)
19423     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19424     // the IR level, so we must wrap it in an intrinsic.
19425     return nullptr;
19426
19427   if (!hasMFENCE(*Subtarget))
19428     // FIXME: it might make sense to use a locked operation here but on a
19429     // different cache-line to prevent cache-line bouncing. In practice it
19430     // is probably a small win, and x86 processors without mfence are rare
19431     // enough that we do not bother.
19432     return nullptr;
19433
19434   Function *MFence =
19435       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19436   Builder.CreateCall(MFence, {});
19437
19438   // Finally we can emit the atomic load.
19439   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19440           AI->getType()->getPrimitiveSizeInBits());
19441   Loaded->setAtomic(Order, SynchScope);
19442   AI->replaceAllUsesWith(Loaded);
19443   AI->eraseFromParent();
19444   return Loaded;
19445 }
19446
19447 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19448                                  SelectionDAG &DAG) {
19449   SDLoc dl(Op);
19450   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19451     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19452   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19453     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19454
19455   // The only fence that needs an instruction is a sequentially-consistent
19456   // cross-thread fence.
19457   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19458     if (hasMFENCE(*Subtarget))
19459       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19460
19461     SDValue Chain = Op.getOperand(0);
19462     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19463     SDValue Ops[] = {
19464       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19465       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19466       DAG.getRegister(0, MVT::i32),            // Index
19467       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19468       DAG.getRegister(0, MVT::i32),            // Segment.
19469       Zero,
19470       Chain
19471     };
19472     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19473     return SDValue(Res, 0);
19474   }
19475
19476   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19477   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19478 }
19479
19480 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19481                              SelectionDAG &DAG) {
19482   MVT T = Op.getSimpleValueType();
19483   SDLoc DL(Op);
19484   unsigned Reg = 0;
19485   unsigned size = 0;
19486   switch(T.SimpleTy) {
19487   default: llvm_unreachable("Invalid value type!");
19488   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19489   case MVT::i16: Reg = X86::AX;  size = 2; break;
19490   case MVT::i32: Reg = X86::EAX; size = 4; break;
19491   case MVT::i64:
19492     assert(Subtarget->is64Bit() && "Node not type legal!");
19493     Reg = X86::RAX; size = 8;
19494     break;
19495   }
19496   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19497                                   Op.getOperand(2), SDValue());
19498   SDValue Ops[] = { cpIn.getValue(0),
19499                     Op.getOperand(1),
19500                     Op.getOperand(3),
19501                     DAG.getTargetConstant(size, DL, MVT::i8),
19502                     cpIn.getValue(1) };
19503   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19504   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19505   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19506                                            Ops, T, MMO);
19507
19508   SDValue cpOut =
19509     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19510   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19511                                       MVT::i32, cpOut.getValue(2));
19512   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19513                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19514                                 EFLAGS);
19515
19516   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19517   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19518   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19519   return SDValue();
19520 }
19521
19522 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19523                             SelectionDAG &DAG) {
19524   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19525   MVT DstVT = Op.getSimpleValueType();
19526
19527   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19528     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19529     if (DstVT != MVT::f64)
19530       // This conversion needs to be expanded.
19531       return SDValue();
19532
19533     SDValue InVec = Op->getOperand(0);
19534     SDLoc dl(Op);
19535     unsigned NumElts = SrcVT.getVectorNumElements();
19536     MVT SVT = SrcVT.getVectorElementType();
19537
19538     // Widen the vector in input in the case of MVT::v2i32.
19539     // Example: from MVT::v2i32 to MVT::v4i32.
19540     SmallVector<SDValue, 16> Elts;
19541     for (unsigned i = 0, e = NumElts; i != e; ++i)
19542       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19543                                  DAG.getIntPtrConstant(i, dl)));
19544
19545     // Explicitly mark the extra elements as Undef.
19546     Elts.append(NumElts, DAG.getUNDEF(SVT));
19547
19548     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19549     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19550     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19551     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19552                        DAG.getIntPtrConstant(0, dl));
19553   }
19554
19555   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19556          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19557   assert((DstVT == MVT::i64 ||
19558           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19559          "Unexpected custom BITCAST");
19560   // i64 <=> MMX conversions are Legal.
19561   if (SrcVT==MVT::i64 && DstVT.isVector())
19562     return Op;
19563   if (DstVT==MVT::i64 && SrcVT.isVector())
19564     return Op;
19565   // MMX <=> MMX conversions are Legal.
19566   if (SrcVT.isVector() && DstVT.isVector())
19567     return Op;
19568   // All other conversions need to be expanded.
19569   return SDValue();
19570 }
19571
19572 /// Compute the horizontal sum of bytes in V for the elements of VT.
19573 ///
19574 /// Requires V to be a byte vector and VT to be an integer vector type with
19575 /// wider elements than V's type. The width of the elements of VT determines
19576 /// how many bytes of V are summed horizontally to produce each element of the
19577 /// result.
19578 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19579                                       const X86Subtarget *Subtarget,
19580                                       SelectionDAG &DAG) {
19581   SDLoc DL(V);
19582   MVT ByteVecVT = V.getSimpleValueType();
19583   MVT EltVT = VT.getVectorElementType();
19584   int NumElts = VT.getVectorNumElements();
19585   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19586          "Expected value to have byte element type.");
19587   assert(EltVT != MVT::i8 &&
19588          "Horizontal byte sum only makes sense for wider elements!");
19589   unsigned VecSize = VT.getSizeInBits();
19590   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19591
19592   // PSADBW instruction horizontally add all bytes and leave the result in i64
19593   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19594   if (EltVT == MVT::i64) {
19595     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19596     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19597     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19598     return DAG.getBitcast(VT, V);
19599   }
19600
19601   if (EltVT == MVT::i32) {
19602     // We unpack the low half and high half into i32s interleaved with zeros so
19603     // that we can use PSADBW to horizontally sum them. The most useful part of
19604     // this is that it lines up the results of two PSADBW instructions to be
19605     // two v2i64 vectors which concatenated are the 4 population counts. We can
19606     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19607     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19608     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19609     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19610
19611     // Do the horizontal sums into two v2i64s.
19612     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19613     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19614     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19615                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19616     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19617                        DAG.getBitcast(ByteVecVT, High), Zeros);
19618
19619     // Merge them together.
19620     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19621     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19622                     DAG.getBitcast(ShortVecVT, Low),
19623                     DAG.getBitcast(ShortVecVT, High));
19624
19625     return DAG.getBitcast(VT, V);
19626   }
19627
19628   // The only element type left is i16.
19629   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19630
19631   // To obtain pop count for each i16 element starting from the pop count for
19632   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19633   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19634   // directly supported.
19635   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19636   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19637   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19638   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19639                   DAG.getBitcast(ByteVecVT, V));
19640   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19641 }
19642
19643 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19644                                         const X86Subtarget *Subtarget,
19645                                         SelectionDAG &DAG) {
19646   MVT VT = Op.getSimpleValueType();
19647   MVT EltVT = VT.getVectorElementType();
19648   unsigned VecSize = VT.getSizeInBits();
19649
19650   // Implement a lookup table in register by using an algorithm based on:
19651   // http://wm.ite.pl/articles/sse-popcount.html
19652   //
19653   // The general idea is that every lower byte nibble in the input vector is an
19654   // index into a in-register pre-computed pop count table. We then split up the
19655   // input vector in two new ones: (1) a vector with only the shifted-right
19656   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19657   // masked out higher ones) for each byte. PSHUB is used separately with both
19658   // to index the in-register table. Next, both are added and the result is a
19659   // i8 vector where each element contains the pop count for input byte.
19660   //
19661   // To obtain the pop count for elements != i8, we follow up with the same
19662   // approach and use additional tricks as described below.
19663   //
19664   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19665                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19666                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19667                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19668
19669   int NumByteElts = VecSize / 8;
19670   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19671   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19672   SmallVector<SDValue, 16> LUTVec;
19673   for (int i = 0; i < NumByteElts; ++i)
19674     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19675   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19676   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19677                                   DAG.getConstant(0x0F, DL, MVT::i8));
19678   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19679
19680   // High nibbles
19681   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19682   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19683   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19684
19685   // Low nibbles
19686   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19687
19688   // The input vector is used as the shuffle mask that index elements into the
19689   // LUT. After counting low and high nibbles, add the vector to obtain the
19690   // final pop count per i8 element.
19691   SDValue HighPopCnt =
19692       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19693   SDValue LowPopCnt =
19694       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19695   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19696
19697   if (EltVT == MVT::i8)
19698     return PopCnt;
19699
19700   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19701 }
19702
19703 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19704                                        const X86Subtarget *Subtarget,
19705                                        SelectionDAG &DAG) {
19706   MVT VT = Op.getSimpleValueType();
19707   assert(VT.is128BitVector() &&
19708          "Only 128-bit vector bitmath lowering supported.");
19709
19710   int VecSize = VT.getSizeInBits();
19711   MVT EltVT = VT.getVectorElementType();
19712   int Len = EltVT.getSizeInBits();
19713
19714   // This is the vectorized version of the "best" algorithm from
19715   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19716   // with a minor tweak to use a series of adds + shifts instead of vector
19717   // multiplications. Implemented for all integer vector types. We only use
19718   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19719   // much faster, even faster than using native popcnt instructions.
19720
19721   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19722     MVT VT = V.getSimpleValueType();
19723     SmallVector<SDValue, 32> Shifters(
19724         VT.getVectorNumElements(),
19725         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19726     return DAG.getNode(OpCode, DL, VT, V,
19727                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19728   };
19729   auto GetMask = [&](SDValue V, APInt Mask) {
19730     MVT VT = V.getSimpleValueType();
19731     SmallVector<SDValue, 32> Masks(
19732         VT.getVectorNumElements(),
19733         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19734     return DAG.getNode(ISD::AND, DL, VT, V,
19735                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19736   };
19737
19738   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19739   // x86, so set the SRL type to have elements at least i16 wide. This is
19740   // correct because all of our SRLs are followed immediately by a mask anyways
19741   // that handles any bits that sneak into the high bits of the byte elements.
19742   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19743
19744   SDValue V = Op;
19745
19746   // v = v - ((v >> 1) & 0x55555555...)
19747   SDValue Srl =
19748       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19749   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19750   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19751
19752   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19753   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19754   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19755   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19756   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19757
19758   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19759   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19760   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19761   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19762
19763   // At this point, V contains the byte-wise population count, and we are
19764   // merely doing a horizontal sum if necessary to get the wider element
19765   // counts.
19766   if (EltVT == MVT::i8)
19767     return V;
19768
19769   return LowerHorizontalByteSum(
19770       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19771       DAG);
19772 }
19773
19774 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19775                                 SelectionDAG &DAG) {
19776   MVT VT = Op.getSimpleValueType();
19777   // FIXME: Need to add AVX-512 support here!
19778   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19779          "Unknown CTPOP type to handle");
19780   SDLoc DL(Op.getNode());
19781   SDValue Op0 = Op.getOperand(0);
19782
19783   if (!Subtarget->hasSSSE3()) {
19784     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19785     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19786     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19787   }
19788
19789   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19790     unsigned NumElems = VT.getVectorNumElements();
19791
19792     // Extract each 128-bit vector, compute pop count and concat the result.
19793     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19794     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19795
19796     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19797                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19798                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19799   }
19800
19801   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19802 }
19803
19804 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19805                           SelectionDAG &DAG) {
19806   assert(Op.getSimpleValueType().isVector() &&
19807          "We only do custom lowering for vector population count.");
19808   return LowerVectorCTPOP(Op, Subtarget, DAG);
19809 }
19810
19811 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19812   SDNode *Node = Op.getNode();
19813   SDLoc dl(Node);
19814   EVT T = Node->getValueType(0);
19815   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19816                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19817   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19818                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19819                        Node->getOperand(0),
19820                        Node->getOperand(1), negOp,
19821                        cast<AtomicSDNode>(Node)->getMemOperand(),
19822                        cast<AtomicSDNode>(Node)->getOrdering(),
19823                        cast<AtomicSDNode>(Node)->getSynchScope());
19824 }
19825
19826 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19827   SDNode *Node = Op.getNode();
19828   SDLoc dl(Node);
19829   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19830
19831   // Convert seq_cst store -> xchg
19832   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19833   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19834   //        (The only way to get a 16-byte store is cmpxchg16b)
19835   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19836   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19837       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19838     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19839                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19840                                  Node->getOperand(0),
19841                                  Node->getOperand(1), Node->getOperand(2),
19842                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19843                                  cast<AtomicSDNode>(Node)->getOrdering(),
19844                                  cast<AtomicSDNode>(Node)->getSynchScope());
19845     return Swap.getValue(1);
19846   }
19847   // Other atomic stores have a simple pattern.
19848   return Op;
19849 }
19850
19851 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19852   MVT VT = Op.getNode()->getSimpleValueType(0);
19853
19854   // Let legalize expand this if it isn't a legal type yet.
19855   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19856     return SDValue();
19857
19858   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19859
19860   unsigned Opc;
19861   bool ExtraOp = false;
19862   switch (Op.getOpcode()) {
19863   default: llvm_unreachable("Invalid code");
19864   case ISD::ADDC: Opc = X86ISD::ADD; break;
19865   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19866   case ISD::SUBC: Opc = X86ISD::SUB; break;
19867   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19868   }
19869
19870   if (!ExtraOp)
19871     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19872                        Op.getOperand(1));
19873   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19874                      Op.getOperand(1), Op.getOperand(2));
19875 }
19876
19877 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19878                             SelectionDAG &DAG) {
19879   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19880
19881   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19882   // which returns the values as { float, float } (in XMM0) or
19883   // { double, double } (which is returned in XMM0, XMM1).
19884   SDLoc dl(Op);
19885   SDValue Arg = Op.getOperand(0);
19886   EVT ArgVT = Arg.getValueType();
19887   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19888
19889   TargetLowering::ArgListTy Args;
19890   TargetLowering::ArgListEntry Entry;
19891
19892   Entry.Node = Arg;
19893   Entry.Ty = ArgTy;
19894   Entry.isSExt = false;
19895   Entry.isZExt = false;
19896   Args.push_back(Entry);
19897
19898   bool isF64 = ArgVT == MVT::f64;
19899   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19900   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19901   // the results are returned via SRet in memory.
19902   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19903   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19904   SDValue Callee =
19905       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19906
19907   Type *RetTy = isF64
19908     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19909     : (Type*)VectorType::get(ArgTy, 4);
19910
19911   TargetLowering::CallLoweringInfo CLI(DAG);
19912   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19913     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19914
19915   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19916
19917   if (isF64)
19918     // Returned in xmm0 and xmm1.
19919     return CallResult.first;
19920
19921   // Returned in bits 0:31 and 32:64 xmm0.
19922   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19923                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19924   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19925                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19926   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19927   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19928 }
19929
19930 /// Widen a vector input to a vector of NVT.  The
19931 /// input vector must have the same element type as NVT.
19932 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
19933                             bool FillWithZeroes = false) {
19934   // Check if InOp already has the right width.
19935   MVT InVT = InOp.getSimpleValueType();
19936   if (InVT == NVT)
19937     return InOp;
19938
19939   if (InOp.isUndef())
19940     return DAG.getUNDEF(NVT);
19941
19942   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
19943          "input and widen element type must match");
19944
19945   unsigned InNumElts = InVT.getVectorNumElements();
19946   unsigned WidenNumElts = NVT.getVectorNumElements();
19947   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
19948          "Unexpected request for vector widening");
19949
19950   EVT EltVT = NVT.getVectorElementType();
19951
19952   SDLoc dl(InOp);
19953   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
19954       InOp.getNumOperands() == 2) {
19955     SDValue N1 = InOp.getOperand(1);
19956     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
19957         N1.isUndef()) {
19958       InOp = InOp.getOperand(0);
19959       InVT = InOp.getSimpleValueType();
19960       InNumElts = InVT.getVectorNumElements();
19961     }
19962   }
19963   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
19964       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
19965     SmallVector<SDValue, 16> Ops;
19966     for (unsigned i = 0; i < InNumElts; ++i)
19967       Ops.push_back(InOp.getOperand(i));
19968
19969     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
19970       DAG.getUNDEF(EltVT);
19971     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
19972       Ops.push_back(FillVal);
19973     return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
19974   }
19975   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
19976     DAG.getUNDEF(NVT);
19977   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
19978                      InOp, DAG.getIntPtrConstant(0, dl));
19979 }
19980
19981 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19982                              SelectionDAG &DAG) {
19983   assert(Subtarget->hasAVX512() &&
19984          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19985
19986   // X86 scatter kills mask register, so its type should be added to
19987   // the list of return values.
19988   // If the "scatter" has 2 return values, it is already handled.
19989   if (Op.getNode()->getNumValues() == 2)
19990     return Op;
19991
19992   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19993   SDValue Src = N->getValue();
19994   MVT VT = Src.getSimpleValueType();
19995   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19996   SDLoc dl(Op);
19997
19998   SDValue NewScatter;
19999   SDValue Index = N->getIndex();
20000   SDValue Mask = N->getMask();
20001   SDValue Chain = N->getChain();
20002   SDValue BasePtr = N->getBasePtr();
20003   MVT MemVT = N->getMemoryVT().getSimpleVT();
20004   MVT IndexVT = Index.getSimpleValueType();
20005   MVT MaskVT = Mask.getSimpleValueType();
20006
20007   if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
20008     // The v2i32 value was promoted to v2i64.
20009     // Now we "redo" the type legalizer's work and widen the original
20010     // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
20011     // with a shuffle.
20012     assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
20013            "Unexpected memory type");
20014     int ShuffleMask[] = {0, 2, -1, -1};
20015     Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
20016                                DAG.getUNDEF(MVT::v4i32), ShuffleMask);
20017     // Now we have 4 elements instead of 2.
20018     // Expand the index.
20019     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
20020     Index = ExtendToType(Index, NewIndexVT, DAG);
20021
20022     // Expand the mask with zeroes
20023     // Mask may be <2 x i64> or <2 x i1> at this moment
20024     assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
20025            "Unexpected mask type");
20026     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
20027     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20028     VT = MVT::v4i32;
20029   }
20030
20031   unsigned NumElts = VT.getVectorNumElements();
20032   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20033       !Index.getSimpleValueType().is512BitVector()) {
20034     // AVX512F supports only 512-bit vectors. Or data or index should
20035     // be 512 bit wide. If now the both index and data are 256-bit, but
20036     // the vector contains 8 elements, we just sign-extend the index
20037     if (IndexVT == MVT::v8i32)
20038       // Just extend index
20039       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20040     else {
20041       // The minimal number of elts in scatter is 8
20042       NumElts = 8;
20043       // Index
20044       MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20045       // Use original index here, do not modify the index twice
20046       Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
20047       if (IndexVT.getScalarType() == MVT::i32)
20048         Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20049
20050       // Mask
20051       // At this point we have promoted mask operand
20052       assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20053       MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20054       // Use the original mask here, do not modify the mask twice
20055       Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true);
20056
20057       // The value that should be stored
20058       MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20059       Src = ExtendToType(Src, NewVT, DAG);
20060     }
20061   }
20062   // If the mask is "wide" at this point - truncate it to i1 vector
20063   MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
20064   Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
20065
20066   // The mask is killed by scatter, add it to the values
20067   SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
20068   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
20069   NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
20070                                     N->getMemOperand());
20071   DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
20072   return SDValue(NewScatter.getNode(), 0);
20073 }
20074
20075 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
20076                           SelectionDAG &DAG) {
20077
20078   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
20079   MVT VT = Op.getSimpleValueType();
20080   SDValue Mask = N->getMask();
20081   SDLoc dl(Op);
20082
20083   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20084       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20085     // This operation is legal for targets with VLX, but without
20086     // VLX the vector should be widened to 512 bit
20087     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20088     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20089     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20090     SDValue Src0 = N->getSrc0();
20091     Src0 = ExtendToType(Src0, WideDataVT, DAG);
20092     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20093     SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
20094                                         N->getBasePtr(), Mask, Src0,
20095                                         N->getMemoryVT(), N->getMemOperand(),
20096                                         N->getExtensionType());
20097
20098     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20099                                  NewLoad.getValue(0),
20100                                  DAG.getIntPtrConstant(0, dl));
20101     SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
20102     return DAG.getMergeValues(RetOps, dl);
20103   }
20104   return Op;
20105 }
20106
20107 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
20108                            SelectionDAG &DAG) {
20109   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
20110   SDValue DataToStore = N->getValue();
20111   MVT VT = DataToStore.getSimpleValueType();
20112   SDValue Mask = N->getMask();
20113   SDLoc dl(Op);
20114
20115   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20116       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20117     // This operation is legal for targets with VLX, but without
20118     // VLX the vector should be widened to 512 bit
20119     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20120     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20121     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20122     DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
20123     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20124     return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
20125                               Mask, N->getMemoryVT(), N->getMemOperand(),
20126                               N->isTruncatingStore());
20127   }
20128   return Op;
20129 }
20130
20131 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
20132                             SelectionDAG &DAG) {
20133   assert(Subtarget->hasAVX512() &&
20134          "MGATHER/MSCATTER are supported on AVX-512 arch only");
20135
20136   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
20137   SDLoc dl(Op);
20138   MVT VT = Op.getSimpleValueType();
20139   SDValue Index = N->getIndex();
20140   SDValue Mask = N->getMask();
20141   SDValue Src0 = N->getValue();
20142   MVT IndexVT = Index.getSimpleValueType();
20143   MVT MaskVT = Mask.getSimpleValueType();
20144
20145   unsigned NumElts = VT.getVectorNumElements();
20146   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
20147
20148   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20149       !Index.getSimpleValueType().is512BitVector()) {
20150     // AVX512F supports only 512-bit vectors. Or data or index should
20151     // be 512 bit wide. If now the both index and data are 256-bit, but
20152     // the vector contains 8 elements, we just sign-extend the index
20153     if (NumElts == 8) {
20154       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20155       SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
20156                         N->getOperand(3), Index };
20157       DAG.UpdateNodeOperands(N, Ops);
20158       return Op;
20159     }
20160
20161     // Minimal number of elements in Gather
20162     NumElts = 8;
20163     // Index
20164     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20165     Index = ExtendToType(Index, NewIndexVT, DAG);
20166     if (IndexVT.getScalarType() == MVT::i32)
20167       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20168
20169     // Mask
20170     MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
20171     // At this point we have promoted mask operand
20172     assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20173     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20174     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20175     Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
20176
20177     // The pass-thru value
20178     MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20179     Src0 = ExtendToType(Src0, NewVT, DAG);
20180
20181     SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
20182     SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
20183                                             N->getMemoryVT(), dl, Ops,
20184                                             N->getMemOperand());
20185     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20186                                  NewGather.getValue(0),
20187                                  DAG.getIntPtrConstant(0, dl));
20188     SDValue RetOps[] = {Exract, NewGather.getValue(1)};
20189     return DAG.getMergeValues(RetOps, dl);
20190   }
20191   return Op;
20192 }
20193
20194 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
20195                                                     SelectionDAG &DAG) const {
20196   // TODO: Eventually, the lowering of these nodes should be informed by or
20197   // deferred to the GC strategy for the function in which they appear. For
20198   // now, however, they must be lowered to something. Since they are logically
20199   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20200   // require special handling for these nodes), lower them as literal NOOPs for
20201   // the time being.
20202   SmallVector<SDValue, 2> Ops;
20203
20204   Ops.push_back(Op.getOperand(0));
20205   if (Op->getGluedNode())
20206     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20207
20208   SDLoc OpDL(Op);
20209   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20210   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20211
20212   return NOOP;
20213 }
20214
20215 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
20216                                                   SelectionDAG &DAG) const {
20217   // TODO: Eventually, the lowering of these nodes should be informed by or
20218   // deferred to the GC strategy for the function in which they appear. For
20219   // now, however, they must be lowered to something. Since they are logically
20220   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20221   // require special handling for these nodes), lower them as literal NOOPs for
20222   // the time being.
20223   SmallVector<SDValue, 2> Ops;
20224
20225   Ops.push_back(Op.getOperand(0));
20226   if (Op->getGluedNode())
20227     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20228
20229   SDLoc OpDL(Op);
20230   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20231   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20232
20233   return NOOP;
20234 }
20235
20236 /// LowerOperation - Provide custom lowering hooks for some operations.
20237 ///
20238 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
20239   switch (Op.getOpcode()) {
20240   default: llvm_unreachable("Should not custom lower this!");
20241   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
20242   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
20243     return LowerCMP_SWAP(Op, Subtarget, DAG);
20244   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
20245   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
20246   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
20247   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
20248   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
20249   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
20250   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
20251   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
20252   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
20253   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
20254   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
20255   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
20256   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
20257   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
20258   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
20259   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
20260   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
20261   case ISD::SHL_PARTS:
20262   case ISD::SRA_PARTS:
20263   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
20264   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
20265   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
20266   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
20267   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
20268   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
20269   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
20270   case ISD::SIGN_EXTEND_VECTOR_INREG:
20271     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
20272   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
20273   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
20274   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
20275   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
20276   case ISD::FABS:
20277   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
20278   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
20279   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
20280   case ISD::SETCC:              return LowerSETCC(Op, DAG);
20281   case ISD::SETCCE:             return LowerSETCCE(Op, DAG);
20282   case ISD::SELECT:             return LowerSELECT(Op, DAG);
20283   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
20284   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
20285   case ISD::VASTART:            return LowerVASTART(Op, DAG);
20286   case ISD::VAARG:              return LowerVAARG(Op, DAG);
20287   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
20288   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
20289   case ISD::INTRINSIC_VOID:
20290   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
20291   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
20292   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
20293   case ISD::FRAME_TO_ARGS_OFFSET:
20294                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
20295   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
20296   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
20297   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
20298   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
20299   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
20300   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
20301   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
20302   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
20303   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
20304   case ISD::CTTZ:
20305   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
20306   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
20307   case ISD::UMUL_LOHI:
20308   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
20309   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
20310   case ISD::SRA:
20311   case ISD::SRL:
20312   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
20313   case ISD::SADDO:
20314   case ISD::UADDO:
20315   case ISD::SSUBO:
20316   case ISD::USUBO:
20317   case ISD::SMULO:
20318   case ISD::UMULO:              return LowerXALUO(Op, DAG);
20319   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20320   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
20321   case ISD::ADDC:
20322   case ISD::ADDE:
20323   case ISD::SUBC:
20324   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20325   case ISD::ADD:                return LowerADD(Op, DAG);
20326   case ISD::SUB:                return LowerSUB(Op, DAG);
20327   case ISD::SMAX:
20328   case ISD::SMIN:
20329   case ISD::UMAX:
20330   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
20331   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
20332   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
20333   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
20334   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
20335   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
20336   case ISD::GC_TRANSITION_START:
20337                                 return LowerGC_TRANSITION_START(Op, DAG);
20338   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
20339   }
20340 }
20341
20342 /// ReplaceNodeResults - Replace a node with an illegal result type
20343 /// with a new node built out of custom code.
20344 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20345                                            SmallVectorImpl<SDValue>&Results,
20346                                            SelectionDAG &DAG) const {
20347   SDLoc dl(N);
20348   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20349   switch (N->getOpcode()) {
20350   default:
20351     llvm_unreachable("Do not know how to custom type legalize this operation!");
20352   case X86ISD::AVG: {
20353     // Legalize types for X86ISD::AVG by expanding vectors.
20354     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20355
20356     auto InVT = N->getValueType(0);
20357     auto InVTSize = InVT.getSizeInBits();
20358     const unsigned RegSize =
20359         (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20360     assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20361            "512-bit vector requires AVX512");
20362     assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20363            "256-bit vector requires AVX2");
20364
20365     auto ElemVT = InVT.getVectorElementType();
20366     auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20367                                   RegSize / ElemVT.getSizeInBits());
20368     assert(RegSize % InVT.getSizeInBits() == 0);
20369     unsigned NumConcat = RegSize / InVT.getSizeInBits();
20370
20371     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20372     Ops[0] = N->getOperand(0);
20373     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20374     Ops[0] = N->getOperand(1);
20375     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20376
20377     SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20378     Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20379                                   DAG.getIntPtrConstant(0, dl)));
20380     return;
20381   }
20382   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20383   case X86ISD::FMINC:
20384   case X86ISD::FMIN:
20385   case X86ISD::FMAXC:
20386   case X86ISD::FMAX: {
20387     EVT VT = N->getValueType(0);
20388     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20389     SDValue UNDEF = DAG.getUNDEF(VT);
20390     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20391                               N->getOperand(0), UNDEF);
20392     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20393                               N->getOperand(1), UNDEF);
20394     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20395     return;
20396   }
20397   case ISD::SIGN_EXTEND_INREG:
20398   case ISD::ADDC:
20399   case ISD::ADDE:
20400   case ISD::SUBC:
20401   case ISD::SUBE:
20402     // We don't want to expand or promote these.
20403     return;
20404   case ISD::SDIV:
20405   case ISD::UDIV:
20406   case ISD::SREM:
20407   case ISD::UREM:
20408   case ISD::SDIVREM:
20409   case ISD::UDIVREM: {
20410     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20411     Results.push_back(V);
20412     return;
20413   }
20414   case ISD::FP_TO_SINT:
20415   case ISD::FP_TO_UINT: {
20416     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20417
20418     std::pair<SDValue,SDValue> Vals =
20419         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20420     SDValue FIST = Vals.first, StackSlot = Vals.second;
20421     if (FIST.getNode()) {
20422       EVT VT = N->getValueType(0);
20423       // Return a load from the stack slot.
20424       if (StackSlot.getNode())
20425         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20426                                       MachinePointerInfo(),
20427                                       false, false, false, 0));
20428       else
20429         Results.push_back(FIST);
20430     }
20431     return;
20432   }
20433   case ISD::UINT_TO_FP: {
20434     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20435     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20436         N->getValueType(0) != MVT::v2f32)
20437       return;
20438     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20439                                  N->getOperand(0));
20440     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20441                                      MVT::f64);
20442     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20443     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20444                              DAG.getBitcast(MVT::v2i64, VBias));
20445     Or = DAG.getBitcast(MVT::v2f64, Or);
20446     // TODO: Are there any fast-math-flags to propagate here?
20447     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20448     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20449     return;
20450   }
20451   case ISD::FP_ROUND: {
20452     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20453         return;
20454     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20455     Results.push_back(V);
20456     return;
20457   }
20458   case ISD::FP_EXTEND: {
20459     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20460     // No other ValueType for FP_EXTEND should reach this point.
20461     assert(N->getValueType(0) == MVT::v2f32 &&
20462            "Do not know how to legalize this Node");
20463     return;
20464   }
20465   case ISD::INTRINSIC_W_CHAIN: {
20466     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20467     switch (IntNo) {
20468     default : llvm_unreachable("Do not know how to custom type "
20469                                "legalize this intrinsic operation!");
20470     case Intrinsic::x86_rdtsc:
20471       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20472                                      Results);
20473     case Intrinsic::x86_rdtscp:
20474       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20475                                      Results);
20476     case Intrinsic::x86_rdpmc:
20477       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20478     }
20479   }
20480   case ISD::INTRINSIC_WO_CHAIN: {
20481     if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20482       Results.push_back(V);
20483     return;
20484   }
20485   case ISD::READCYCLECOUNTER: {
20486     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20487                                    Results);
20488   }
20489   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20490     EVT T = N->getValueType(0);
20491     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20492     bool Regs64bit = T == MVT::i128;
20493     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20494     SDValue cpInL, cpInH;
20495     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20496                         DAG.getConstant(0, dl, HalfT));
20497     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20498                         DAG.getConstant(1, dl, HalfT));
20499     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20500                              Regs64bit ? X86::RAX : X86::EAX,
20501                              cpInL, SDValue());
20502     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20503                              Regs64bit ? X86::RDX : X86::EDX,
20504                              cpInH, cpInL.getValue(1));
20505     SDValue swapInL, swapInH;
20506     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20507                           DAG.getConstant(0, dl, HalfT));
20508     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20509                           DAG.getConstant(1, dl, HalfT));
20510     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20511                                Regs64bit ? X86::RBX : X86::EBX,
20512                                swapInL, cpInH.getValue(1));
20513     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20514                                Regs64bit ? X86::RCX : X86::ECX,
20515                                swapInH, swapInL.getValue(1));
20516     SDValue Ops[] = { swapInH.getValue(0),
20517                       N->getOperand(1),
20518                       swapInH.getValue(1) };
20519     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20520     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20521     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20522                                   X86ISD::LCMPXCHG8_DAG;
20523     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20524     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20525                                         Regs64bit ? X86::RAX : X86::EAX,
20526                                         HalfT, Result.getValue(1));
20527     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20528                                         Regs64bit ? X86::RDX : X86::EDX,
20529                                         HalfT, cpOutL.getValue(2));
20530     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20531
20532     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20533                                         MVT::i32, cpOutH.getValue(2));
20534     SDValue Success =
20535         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20536                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20537     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20538
20539     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20540     Results.push_back(Success);
20541     Results.push_back(EFLAGS.getValue(1));
20542     return;
20543   }
20544   case ISD::ATOMIC_SWAP:
20545   case ISD::ATOMIC_LOAD_ADD:
20546   case ISD::ATOMIC_LOAD_SUB:
20547   case ISD::ATOMIC_LOAD_AND:
20548   case ISD::ATOMIC_LOAD_OR:
20549   case ISD::ATOMIC_LOAD_XOR:
20550   case ISD::ATOMIC_LOAD_NAND:
20551   case ISD::ATOMIC_LOAD_MIN:
20552   case ISD::ATOMIC_LOAD_MAX:
20553   case ISD::ATOMIC_LOAD_UMIN:
20554   case ISD::ATOMIC_LOAD_UMAX:
20555   case ISD::ATOMIC_LOAD: {
20556     // Delegate to generic TypeLegalization. Situations we can really handle
20557     // should have already been dealt with by AtomicExpandPass.cpp.
20558     break;
20559   }
20560   case ISD::BITCAST: {
20561     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20562     EVT DstVT = N->getValueType(0);
20563     EVT SrcVT = N->getOperand(0)->getValueType(0);
20564
20565     if (SrcVT != MVT::f64 ||
20566         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20567       return;
20568
20569     unsigned NumElts = DstVT.getVectorNumElements();
20570     EVT SVT = DstVT.getVectorElementType();
20571     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20572     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20573                                    MVT::v2f64, N->getOperand(0));
20574     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20575
20576     if (ExperimentalVectorWideningLegalization) {
20577       // If we are legalizing vectors by widening, we already have the desired
20578       // legal vector type, just return it.
20579       Results.push_back(ToVecInt);
20580       return;
20581     }
20582
20583     SmallVector<SDValue, 8> Elts;
20584     for (unsigned i = 0, e = NumElts; i != e; ++i)
20585       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20586                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
20587
20588     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20589   }
20590   }
20591 }
20592
20593 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20594   switch ((X86ISD::NodeType)Opcode) {
20595   case X86ISD::FIRST_NUMBER:       break;
20596   case X86ISD::BSF:                return "X86ISD::BSF";
20597   case X86ISD::BSR:                return "X86ISD::BSR";
20598   case X86ISD::SHLD:               return "X86ISD::SHLD";
20599   case X86ISD::SHRD:               return "X86ISD::SHRD";
20600   case X86ISD::FAND:               return "X86ISD::FAND";
20601   case X86ISD::FANDN:              return "X86ISD::FANDN";
20602   case X86ISD::FOR:                return "X86ISD::FOR";
20603   case X86ISD::FXOR:               return "X86ISD::FXOR";
20604   case X86ISD::FILD:               return "X86ISD::FILD";
20605   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
20606   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20607   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20608   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20609   case X86ISD::FLD:                return "X86ISD::FLD";
20610   case X86ISD::FST:                return "X86ISD::FST";
20611   case X86ISD::CALL:               return "X86ISD::CALL";
20612   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
20613   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
20614   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
20615   case X86ISD::BT:                 return "X86ISD::BT";
20616   case X86ISD::CMP:                return "X86ISD::CMP";
20617   case X86ISD::COMI:               return "X86ISD::COMI";
20618   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
20619   case X86ISD::CMPM:               return "X86ISD::CMPM";
20620   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
20621   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
20622   case X86ISD::SETCC:              return "X86ISD::SETCC";
20623   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
20624   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
20625   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
20626   case X86ISD::CMOV:               return "X86ISD::CMOV";
20627   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
20628   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
20629   case X86ISD::IRET:               return "X86ISD::IRET";
20630   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
20631   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
20632   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
20633   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
20634   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
20635   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
20636   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
20637   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
20638   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
20639   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
20640   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
20641   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
20642   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
20643   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
20644   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
20645   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
20646   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
20647   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
20648   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
20649   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
20650   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
20651   case X86ISD::HADD:               return "X86ISD::HADD";
20652   case X86ISD::HSUB:               return "X86ISD::HSUB";
20653   case X86ISD::FHADD:              return "X86ISD::FHADD";
20654   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
20655   case X86ISD::ABS:                return "X86ISD::ABS";
20656   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
20657   case X86ISD::FMAX:               return "X86ISD::FMAX";
20658   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
20659   case X86ISD::FMIN:               return "X86ISD::FMIN";
20660   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
20661   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20662   case X86ISD::FMINC:              return "X86ISD::FMINC";
20663   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20664   case X86ISD::FRCP:               return "X86ISD::FRCP";
20665   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
20666   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
20667   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20668   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20669   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20670   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20671   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20672   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20673   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20674   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20675   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20676   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20677   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20678   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20679   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20680   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20681   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20682   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20683   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20684   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20685   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20686   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20687   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20688   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20689   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20690   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20691   case X86ISD::CVT2MASK:           return "X86ISD::CVT2MASK";
20692   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20693   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20694   case X86ISD::VSHL:               return "X86ISD::VSHL";
20695   case X86ISD::VSRL:               return "X86ISD::VSRL";
20696   case X86ISD::VSRA:               return "X86ISD::VSRA";
20697   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20698   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20699   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20700   case X86ISD::CMPP:               return "X86ISD::CMPP";
20701   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20702   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20703   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20704   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20705   case X86ISD::ADD:                return "X86ISD::ADD";
20706   case X86ISD::SUB:                return "X86ISD::SUB";
20707   case X86ISD::ADC:                return "X86ISD::ADC";
20708   case X86ISD::SBB:                return "X86ISD::SBB";
20709   case X86ISD::SMUL:               return "X86ISD::SMUL";
20710   case X86ISD::UMUL:               return "X86ISD::UMUL";
20711   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20712   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20713   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20714   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20715   case X86ISD::INC:                return "X86ISD::INC";
20716   case X86ISD::DEC:                return "X86ISD::DEC";
20717   case X86ISD::OR:                 return "X86ISD::OR";
20718   case X86ISD::XOR:                return "X86ISD::XOR";
20719   case X86ISD::AND:                return "X86ISD::AND";
20720   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20721   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20722   case X86ISD::PTEST:              return "X86ISD::PTEST";
20723   case X86ISD::TESTP:              return "X86ISD::TESTP";
20724   case X86ISD::TESTM:              return "X86ISD::TESTM";
20725   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20726   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20727   case X86ISD::KTEST:              return "X86ISD::KTEST";
20728   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20729   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20730   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20731   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20732   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20733   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20734   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20735   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20736   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20737   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20738   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20739   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20740   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20741   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20742   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20743   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20744   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20745   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20746   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20747   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20748   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20749   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20750   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
20751   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20752   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20753   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20754   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20755   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20756   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20757   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20758   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20759   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20760   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20761   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20762   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20763   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20764   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20765   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20766   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20767   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20768   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20769   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20770   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20771   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20772   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20773   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20774   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20775   case X86ISD::SAHF:               return "X86ISD::SAHF";
20776   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20777   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20778   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20779   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20780   case X86ISD::VPROT:              return "X86ISD::VPROT";
20781   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20782   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20783   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20784   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20785   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20786   case X86ISD::FMADD:              return "X86ISD::FMADD";
20787   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20788   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20789   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20790   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20791   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20792   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20793   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20794   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20795   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20796   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20797   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20798   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20799   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20800   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20801   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20802   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20803   case X86ISD::XTEST:              return "X86ISD::XTEST";
20804   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20805   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20806   case X86ISD::SELECT:             return "X86ISD::SELECT";
20807   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20808   case X86ISD::RCP28:              return "X86ISD::RCP28";
20809   case X86ISD::EXP2:               return "X86ISD::EXP2";
20810   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20811   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20812   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20813   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20814   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20815   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20816   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20817   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20818   case X86ISD::ADDS:               return "X86ISD::ADDS";
20819   case X86ISD::SUBS:               return "X86ISD::SUBS";
20820   case X86ISD::AVG:                return "X86ISD::AVG";
20821   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20822   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20823   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20824   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20825   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20826   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20827   case X86ISD::VFPCLASSS:          return "X86ISD::VFPCLASSS";
20828   }
20829   return nullptr;
20830 }
20831
20832 // isLegalAddressingMode - Return true if the addressing mode represented
20833 // by AM is legal for this target, for a load/store of the specified type.
20834 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20835                                               const AddrMode &AM, Type *Ty,
20836                                               unsigned AS) const {
20837   // X86 supports extremely general addressing modes.
20838   CodeModel::Model M = getTargetMachine().getCodeModel();
20839   Reloc::Model R = getTargetMachine().getRelocationModel();
20840
20841   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20842   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20843     return false;
20844
20845   if (AM.BaseGV) {
20846     unsigned GVFlags =
20847       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20848
20849     // If a reference to this global requires an extra load, we can't fold it.
20850     if (isGlobalStubReference(GVFlags))
20851       return false;
20852
20853     // If BaseGV requires a register for the PIC base, we cannot also have a
20854     // BaseReg specified.
20855     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20856       return false;
20857
20858     // If lower 4G is not available, then we must use rip-relative addressing.
20859     if ((M != CodeModel::Small || R != Reloc::Static) &&
20860         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20861       return false;
20862   }
20863
20864   switch (AM.Scale) {
20865   case 0:
20866   case 1:
20867   case 2:
20868   case 4:
20869   case 8:
20870     // These scales always work.
20871     break;
20872   case 3:
20873   case 5:
20874   case 9:
20875     // These scales are formed with basereg+scalereg.  Only accept if there is
20876     // no basereg yet.
20877     if (AM.HasBaseReg)
20878       return false;
20879     break;
20880   default:  // Other stuff never works.
20881     return false;
20882   }
20883
20884   return true;
20885 }
20886
20887 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20888   unsigned Bits = Ty->getScalarSizeInBits();
20889
20890   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20891   // particularly cheaper than those without.
20892   if (Bits == 8)
20893     return false;
20894
20895   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20896   // variable shifts just as cheap as scalar ones.
20897   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20898     return false;
20899
20900   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20901   // fully general vector.
20902   return true;
20903 }
20904
20905 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20906   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20907     return false;
20908   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20909   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20910   return NumBits1 > NumBits2;
20911 }
20912
20913 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20914   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20915     return false;
20916
20917   if (!isTypeLegal(EVT::getEVT(Ty1)))
20918     return false;
20919
20920   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20921
20922   // Assuming the caller doesn't have a zeroext or signext return parameter,
20923   // truncation all the way down to i1 is valid.
20924   return true;
20925 }
20926
20927 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20928   return isInt<32>(Imm);
20929 }
20930
20931 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20932   // Can also use sub to handle negated immediates.
20933   return isInt<32>(Imm);
20934 }
20935
20936 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20937   if (!VT1.isInteger() || !VT2.isInteger())
20938     return false;
20939   unsigned NumBits1 = VT1.getSizeInBits();
20940   unsigned NumBits2 = VT2.getSizeInBits();
20941   return NumBits1 > NumBits2;
20942 }
20943
20944 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20945   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20946   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20947 }
20948
20949 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20950   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20951   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20952 }
20953
20954 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20955   EVT VT1 = Val.getValueType();
20956   if (isZExtFree(VT1, VT2))
20957     return true;
20958
20959   if (Val.getOpcode() != ISD::LOAD)
20960     return false;
20961
20962   if (!VT1.isSimple() || !VT1.isInteger() ||
20963       !VT2.isSimple() || !VT2.isInteger())
20964     return false;
20965
20966   switch (VT1.getSimpleVT().SimpleTy) {
20967   default: break;
20968   case MVT::i8:
20969   case MVT::i16:
20970   case MVT::i32:
20971     // X86 has 8, 16, and 32-bit zero-extending loads.
20972     return true;
20973   }
20974
20975   return false;
20976 }
20977
20978 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20979
20980 bool
20981 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20982   if (!Subtarget->hasAnyFMA())
20983     return false;
20984
20985   VT = VT.getScalarType();
20986
20987   if (!VT.isSimple())
20988     return false;
20989
20990   switch (VT.getSimpleVT().SimpleTy) {
20991   case MVT::f32:
20992   case MVT::f64:
20993     return true;
20994   default:
20995     break;
20996   }
20997
20998   return false;
20999 }
21000
21001 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
21002   // i16 instructions are longer (0x66 prefix) and potentially slower.
21003   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
21004 }
21005
21006 /// isShuffleMaskLegal - Targets can use this to indicate that they only
21007 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
21008 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
21009 /// are assumed to be legal.
21010 bool
21011 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
21012                                       EVT VT) const {
21013   if (!VT.isSimple())
21014     return false;
21015
21016   // Not for i1 vectors
21017   if (VT.getSimpleVT().getScalarType() == MVT::i1)
21018     return false;
21019
21020   // Very little shuffling can be done for 64-bit vectors right now.
21021   if (VT.getSimpleVT().getSizeInBits() == 64)
21022     return false;
21023
21024   // We only care that the types being shuffled are legal. The lowering can
21025   // handle any possible shuffle mask that results.
21026   return isTypeLegal(VT.getSimpleVT());
21027 }
21028
21029 bool
21030 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
21031                                           EVT VT) const {
21032   // Just delegate to the generic legality, clear masks aren't special.
21033   return isShuffleMaskLegal(Mask, VT);
21034 }
21035
21036 //===----------------------------------------------------------------------===//
21037 //                           X86 Scheduler Hooks
21038 //===----------------------------------------------------------------------===//
21039
21040 /// Utility function to emit xbegin specifying the start of an RTM region.
21041 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
21042                                      const TargetInstrInfo *TII) {
21043   DebugLoc DL = MI->getDebugLoc();
21044
21045   const BasicBlock *BB = MBB->getBasicBlock();
21046   MachineFunction::iterator I = ++MBB->getIterator();
21047
21048   // For the v = xbegin(), we generate
21049   //
21050   // thisMBB:
21051   //  xbegin sinkMBB
21052   //
21053   // mainMBB:
21054   //  eax = -1
21055   //
21056   // sinkMBB:
21057   //  v = eax
21058
21059   MachineBasicBlock *thisMBB = MBB;
21060   MachineFunction *MF = MBB->getParent();
21061   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21062   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21063   MF->insert(I, mainMBB);
21064   MF->insert(I, sinkMBB);
21065
21066   // Transfer the remainder of BB and its successor edges to sinkMBB.
21067   sinkMBB->splice(sinkMBB->begin(), MBB,
21068                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21069   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21070
21071   // thisMBB:
21072   //  xbegin sinkMBB
21073   //  # fallthrough to mainMBB
21074   //  # abortion to sinkMBB
21075   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
21076   thisMBB->addSuccessor(mainMBB);
21077   thisMBB->addSuccessor(sinkMBB);
21078
21079   // mainMBB:
21080   //  EAX = -1
21081   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
21082   mainMBB->addSuccessor(sinkMBB);
21083
21084   // sinkMBB:
21085   // EAX is live into the sinkMBB
21086   sinkMBB->addLiveIn(X86::EAX);
21087   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21088           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21089     .addReg(X86::EAX);
21090
21091   MI->eraseFromParent();
21092   return sinkMBB;
21093 }
21094
21095 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
21096 // or XMM0_V32I8 in AVX all of this code can be replaced with that
21097 // in the .td file.
21098 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
21099                                        const TargetInstrInfo *TII) {
21100   unsigned Opc;
21101   switch (MI->getOpcode()) {
21102   default: llvm_unreachable("illegal opcode!");
21103   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
21104   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
21105   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
21106   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
21107   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
21108   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
21109   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
21110   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
21111   }
21112
21113   DebugLoc dl = MI->getDebugLoc();
21114   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21115
21116   unsigned NumArgs = MI->getNumOperands();
21117   for (unsigned i = 1; i < NumArgs; ++i) {
21118     MachineOperand &Op = MI->getOperand(i);
21119     if (!(Op.isReg() && Op.isImplicit()))
21120       MIB.addOperand(Op);
21121   }
21122   if (MI->hasOneMemOperand())
21123     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21124
21125   BuildMI(*BB, MI, dl,
21126     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21127     .addReg(X86::XMM0);
21128
21129   MI->eraseFromParent();
21130   return BB;
21131 }
21132
21133 // FIXME: Custom handling because TableGen doesn't support multiple implicit
21134 // defs in an instruction pattern
21135 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
21136                                        const TargetInstrInfo *TII) {
21137   unsigned Opc;
21138   switch (MI->getOpcode()) {
21139   default: llvm_unreachable("illegal opcode!");
21140   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
21141   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
21142   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
21143   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
21144   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
21145   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
21146   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
21147   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
21148   }
21149
21150   DebugLoc dl = MI->getDebugLoc();
21151   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21152
21153   unsigned NumArgs = MI->getNumOperands(); // remove the results
21154   for (unsigned i = 1; i < NumArgs; ++i) {
21155     MachineOperand &Op = MI->getOperand(i);
21156     if (!(Op.isReg() && Op.isImplicit()))
21157       MIB.addOperand(Op);
21158   }
21159   if (MI->hasOneMemOperand())
21160     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21161
21162   BuildMI(*BB, MI, dl,
21163     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21164     .addReg(X86::ECX);
21165
21166   MI->eraseFromParent();
21167   return BB;
21168 }
21169
21170 static MachineBasicBlock *EmitWRPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21171                                      const X86Subtarget *Subtarget) {
21172   DebugLoc dl = MI->getDebugLoc();
21173   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21174
21175   // insert input VAL into EAX
21176   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
21177                            .addReg(MI->getOperand(0).getReg());
21178   // insert zero to ECX
21179   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21180                            .addReg(X86::ECX)
21181                            .addReg(X86::ECX);
21182   // insert zero to EDX
21183   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::EDX)
21184                            .addReg(X86::EDX)
21185                            .addReg(X86::EDX);
21186   // insert WRPKRU instruction
21187   BuildMI(*BB, MI, dl, TII->get(X86::WRPKRUr));
21188
21189   MI->eraseFromParent(); // The pseudo is gone now.
21190   return BB;
21191 }
21192
21193 static MachineBasicBlock *EmitRDPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21194                                      const X86Subtarget *Subtarget) {
21195   DebugLoc dl = MI->getDebugLoc();
21196   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21197
21198   // insert zero to ECX
21199   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21200                            .addReg(X86::ECX)
21201                            .addReg(X86::ECX);
21202   // insert RDPKRU instruction
21203   BuildMI(*BB, MI, dl, TII->get(X86::RDPKRUr));
21204   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21205                            .addReg(X86::EAX);
21206
21207   MI->eraseFromParent(); // The pseudo is gone now.
21208   return BB;
21209 }
21210
21211 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
21212                                       const X86Subtarget *Subtarget) {
21213   DebugLoc dl = MI->getDebugLoc();
21214   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21215   // Address into RAX/EAX, other two args into ECX, EDX.
21216   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
21217   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
21218   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
21219   for (int i = 0; i < X86::AddrNumOperands; ++i)
21220     MIB.addOperand(MI->getOperand(i));
21221
21222   unsigned ValOps = X86::AddrNumOperands;
21223   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
21224     .addReg(MI->getOperand(ValOps).getReg());
21225   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
21226     .addReg(MI->getOperand(ValOps+1).getReg());
21227
21228   // The instruction doesn't actually take any operands though.
21229   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
21230
21231   MI->eraseFromParent(); // The pseudo is gone now.
21232   return BB;
21233 }
21234
21235 MachineBasicBlock *
21236 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
21237                                                  MachineBasicBlock *MBB) const {
21238   // Emit va_arg instruction on X86-64.
21239
21240   // Operands to this pseudo-instruction:
21241   // 0  ) Output        : destination address (reg)
21242   // 1-5) Input         : va_list address (addr, i64mem)
21243   // 6  ) ArgSize       : Size (in bytes) of vararg type
21244   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
21245   // 8  ) Align         : Alignment of type
21246   // 9  ) EFLAGS (implicit-def)
21247
21248   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
21249   static_assert(X86::AddrNumOperands == 5,
21250                 "VAARG_64 assumes 5 address operands");
21251
21252   unsigned DestReg = MI->getOperand(0).getReg();
21253   MachineOperand &Base = MI->getOperand(1);
21254   MachineOperand &Scale = MI->getOperand(2);
21255   MachineOperand &Index = MI->getOperand(3);
21256   MachineOperand &Disp = MI->getOperand(4);
21257   MachineOperand &Segment = MI->getOperand(5);
21258   unsigned ArgSize = MI->getOperand(6).getImm();
21259   unsigned ArgMode = MI->getOperand(7).getImm();
21260   unsigned Align = MI->getOperand(8).getImm();
21261
21262   // Memory Reference
21263   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
21264   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21265   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21266
21267   // Machine Information
21268   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21269   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
21270   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
21271   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
21272   DebugLoc DL = MI->getDebugLoc();
21273
21274   // struct va_list {
21275   //   i32   gp_offset
21276   //   i32   fp_offset
21277   //   i64   overflow_area (address)
21278   //   i64   reg_save_area (address)
21279   // }
21280   // sizeof(va_list) = 24
21281   // alignment(va_list) = 8
21282
21283   unsigned TotalNumIntRegs = 6;
21284   unsigned TotalNumXMMRegs = 8;
21285   bool UseGPOffset = (ArgMode == 1);
21286   bool UseFPOffset = (ArgMode == 2);
21287   unsigned MaxOffset = TotalNumIntRegs * 8 +
21288                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
21289
21290   /* Align ArgSize to a multiple of 8 */
21291   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
21292   bool NeedsAlign = (Align > 8);
21293
21294   MachineBasicBlock *thisMBB = MBB;
21295   MachineBasicBlock *overflowMBB;
21296   MachineBasicBlock *offsetMBB;
21297   MachineBasicBlock *endMBB;
21298
21299   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
21300   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
21301   unsigned OffsetReg = 0;
21302
21303   if (!UseGPOffset && !UseFPOffset) {
21304     // If we only pull from the overflow region, we don't create a branch.
21305     // We don't need to alter control flow.
21306     OffsetDestReg = 0; // unused
21307     OverflowDestReg = DestReg;
21308
21309     offsetMBB = nullptr;
21310     overflowMBB = thisMBB;
21311     endMBB = thisMBB;
21312   } else {
21313     // First emit code to check if gp_offset (or fp_offset) is below the bound.
21314     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
21315     // If not, pull from overflow_area. (branch to overflowMBB)
21316     //
21317     //       thisMBB
21318     //         |     .
21319     //         |        .
21320     //     offsetMBB   overflowMBB
21321     //         |        .
21322     //         |     .
21323     //        endMBB
21324
21325     // Registers for the PHI in endMBB
21326     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
21327     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
21328
21329     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21330     MachineFunction *MF = MBB->getParent();
21331     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21332     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21333     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21334
21335     MachineFunction::iterator MBBIter = ++MBB->getIterator();
21336
21337     // Insert the new basic blocks
21338     MF->insert(MBBIter, offsetMBB);
21339     MF->insert(MBBIter, overflowMBB);
21340     MF->insert(MBBIter, endMBB);
21341
21342     // Transfer the remainder of MBB and its successor edges to endMBB.
21343     endMBB->splice(endMBB->begin(), thisMBB,
21344                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
21345     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
21346
21347     // Make offsetMBB and overflowMBB successors of thisMBB
21348     thisMBB->addSuccessor(offsetMBB);
21349     thisMBB->addSuccessor(overflowMBB);
21350
21351     // endMBB is a successor of both offsetMBB and overflowMBB
21352     offsetMBB->addSuccessor(endMBB);
21353     overflowMBB->addSuccessor(endMBB);
21354
21355     // Load the offset value into a register
21356     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21357     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21358       .addOperand(Base)
21359       .addOperand(Scale)
21360       .addOperand(Index)
21361       .addDisp(Disp, UseFPOffset ? 4 : 0)
21362       .addOperand(Segment)
21363       .setMemRefs(MMOBegin, MMOEnd);
21364
21365     // Check if there is enough room left to pull this argument.
21366     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21367       .addReg(OffsetReg)
21368       .addImm(MaxOffset + 8 - ArgSizeA8);
21369
21370     // Branch to "overflowMBB" if offset >= max
21371     // Fall through to "offsetMBB" otherwise
21372     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21373       .addMBB(overflowMBB);
21374   }
21375
21376   // In offsetMBB, emit code to use the reg_save_area.
21377   if (offsetMBB) {
21378     assert(OffsetReg != 0);
21379
21380     // Read the reg_save_area address.
21381     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21382     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21383       .addOperand(Base)
21384       .addOperand(Scale)
21385       .addOperand(Index)
21386       .addDisp(Disp, 16)
21387       .addOperand(Segment)
21388       .setMemRefs(MMOBegin, MMOEnd);
21389
21390     // Zero-extend the offset
21391     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21392       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21393         .addImm(0)
21394         .addReg(OffsetReg)
21395         .addImm(X86::sub_32bit);
21396
21397     // Add the offset to the reg_save_area to get the final address.
21398     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21399       .addReg(OffsetReg64)
21400       .addReg(RegSaveReg);
21401
21402     // Compute the offset for the next argument
21403     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21404     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21405       .addReg(OffsetReg)
21406       .addImm(UseFPOffset ? 16 : 8);
21407
21408     // Store it back into the va_list.
21409     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21410       .addOperand(Base)
21411       .addOperand(Scale)
21412       .addOperand(Index)
21413       .addDisp(Disp, UseFPOffset ? 4 : 0)
21414       .addOperand(Segment)
21415       .addReg(NextOffsetReg)
21416       .setMemRefs(MMOBegin, MMOEnd);
21417
21418     // Jump to endMBB
21419     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21420       .addMBB(endMBB);
21421   }
21422
21423   //
21424   // Emit code to use overflow area
21425   //
21426
21427   // Load the overflow_area address into a register.
21428   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21429   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21430     .addOperand(Base)
21431     .addOperand(Scale)
21432     .addOperand(Index)
21433     .addDisp(Disp, 8)
21434     .addOperand(Segment)
21435     .setMemRefs(MMOBegin, MMOEnd);
21436
21437   // If we need to align it, do so. Otherwise, just copy the address
21438   // to OverflowDestReg.
21439   if (NeedsAlign) {
21440     // Align the overflow address
21441     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21442     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21443
21444     // aligned_addr = (addr + (align-1)) & ~(align-1)
21445     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21446       .addReg(OverflowAddrReg)
21447       .addImm(Align-1);
21448
21449     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21450       .addReg(TmpReg)
21451       .addImm(~(uint64_t)(Align-1));
21452   } else {
21453     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21454       .addReg(OverflowAddrReg);
21455   }
21456
21457   // Compute the next overflow address after this argument.
21458   // (the overflow address should be kept 8-byte aligned)
21459   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21460   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21461     .addReg(OverflowDestReg)
21462     .addImm(ArgSizeA8);
21463
21464   // Store the new overflow address.
21465   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21466     .addOperand(Base)
21467     .addOperand(Scale)
21468     .addOperand(Index)
21469     .addDisp(Disp, 8)
21470     .addOperand(Segment)
21471     .addReg(NextAddrReg)
21472     .setMemRefs(MMOBegin, MMOEnd);
21473
21474   // If we branched, emit the PHI to the front of endMBB.
21475   if (offsetMBB) {
21476     BuildMI(*endMBB, endMBB->begin(), DL,
21477             TII->get(X86::PHI), DestReg)
21478       .addReg(OffsetDestReg).addMBB(offsetMBB)
21479       .addReg(OverflowDestReg).addMBB(overflowMBB);
21480   }
21481
21482   // Erase the pseudo instruction
21483   MI->eraseFromParent();
21484
21485   return endMBB;
21486 }
21487
21488 MachineBasicBlock *
21489 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21490                                                  MachineInstr *MI,
21491                                                  MachineBasicBlock *MBB) const {
21492   // Emit code to save XMM registers to the stack. The ABI says that the
21493   // number of registers to save is given in %al, so it's theoretically
21494   // possible to do an indirect jump trick to avoid saving all of them,
21495   // however this code takes a simpler approach and just executes all
21496   // of the stores if %al is non-zero. It's less code, and it's probably
21497   // easier on the hardware branch predictor, and stores aren't all that
21498   // expensive anyway.
21499
21500   // Create the new basic blocks. One block contains all the XMM stores,
21501   // and one block is the final destination regardless of whether any
21502   // stores were performed.
21503   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21504   MachineFunction *F = MBB->getParent();
21505   MachineFunction::iterator MBBIter = ++MBB->getIterator();
21506   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21507   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21508   F->insert(MBBIter, XMMSaveMBB);
21509   F->insert(MBBIter, EndMBB);
21510
21511   // Transfer the remainder of MBB and its successor edges to EndMBB.
21512   EndMBB->splice(EndMBB->begin(), MBB,
21513                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21514   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21515
21516   // The original block will now fall through to the XMM save block.
21517   MBB->addSuccessor(XMMSaveMBB);
21518   // The XMMSaveMBB will fall through to the end block.
21519   XMMSaveMBB->addSuccessor(EndMBB);
21520
21521   // Now add the instructions.
21522   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21523   DebugLoc DL = MI->getDebugLoc();
21524
21525   unsigned CountReg = MI->getOperand(0).getReg();
21526   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21527   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21528
21529   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21530     // If %al is 0, branch around the XMM save block.
21531     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21532     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21533     MBB->addSuccessor(EndMBB);
21534   }
21535
21536   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21537   // that was just emitted, but clearly shouldn't be "saved".
21538   assert((MI->getNumOperands() <= 3 ||
21539           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21540           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21541          && "Expected last argument to be EFLAGS");
21542   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21543   // In the XMM save block, save all the XMM argument registers.
21544   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21545     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21546     MachineMemOperand *MMO = F->getMachineMemOperand(
21547         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21548         MachineMemOperand::MOStore,
21549         /*Size=*/16, /*Align=*/16);
21550     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21551       .addFrameIndex(RegSaveFrameIndex)
21552       .addImm(/*Scale=*/1)
21553       .addReg(/*IndexReg=*/0)
21554       .addImm(/*Disp=*/Offset)
21555       .addReg(/*Segment=*/0)
21556       .addReg(MI->getOperand(i).getReg())
21557       .addMemOperand(MMO);
21558   }
21559
21560   MI->eraseFromParent();   // The pseudo instruction is gone now.
21561
21562   return EndMBB;
21563 }
21564
21565 // The EFLAGS operand of SelectItr might be missing a kill marker
21566 // because there were multiple uses of EFLAGS, and ISel didn't know
21567 // which to mark. Figure out whether SelectItr should have had a
21568 // kill marker, and set it if it should. Returns the correct kill
21569 // marker value.
21570 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21571                                      MachineBasicBlock* BB,
21572                                      const TargetRegisterInfo* TRI) {
21573   // Scan forward through BB for a use/def of EFLAGS.
21574   MachineBasicBlock::iterator miI(std::next(SelectItr));
21575   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21576     const MachineInstr& mi = *miI;
21577     if (mi.readsRegister(X86::EFLAGS))
21578       return false;
21579     if (mi.definesRegister(X86::EFLAGS))
21580       break; // Should have kill-flag - update below.
21581   }
21582
21583   // If we hit the end of the block, check whether EFLAGS is live into a
21584   // successor.
21585   if (miI == BB->end()) {
21586     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21587                                           sEnd = BB->succ_end();
21588          sItr != sEnd; ++sItr) {
21589       MachineBasicBlock* succ = *sItr;
21590       if (succ->isLiveIn(X86::EFLAGS))
21591         return false;
21592     }
21593   }
21594
21595   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21596   // out. SelectMI should have a kill flag on EFLAGS.
21597   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21598   return true;
21599 }
21600
21601 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21602 // together with other CMOV pseudo-opcodes into a single basic-block with
21603 // conditional jump around it.
21604 static bool isCMOVPseudo(MachineInstr *MI) {
21605   switch (MI->getOpcode()) {
21606   case X86::CMOV_FR32:
21607   case X86::CMOV_FR64:
21608   case X86::CMOV_GR8:
21609   case X86::CMOV_GR16:
21610   case X86::CMOV_GR32:
21611   case X86::CMOV_RFP32:
21612   case X86::CMOV_RFP64:
21613   case X86::CMOV_RFP80:
21614   case X86::CMOV_V2F64:
21615   case X86::CMOV_V2I64:
21616   case X86::CMOV_V4F32:
21617   case X86::CMOV_V4F64:
21618   case X86::CMOV_V4I64:
21619   case X86::CMOV_V16F32:
21620   case X86::CMOV_V8F32:
21621   case X86::CMOV_V8F64:
21622   case X86::CMOV_V8I64:
21623   case X86::CMOV_V8I1:
21624   case X86::CMOV_V16I1:
21625   case X86::CMOV_V32I1:
21626   case X86::CMOV_V64I1:
21627     return true;
21628
21629   default:
21630     return false;
21631   }
21632 }
21633
21634 MachineBasicBlock *
21635 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21636                                      MachineBasicBlock *BB) const {
21637   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21638   DebugLoc DL = MI->getDebugLoc();
21639
21640   // To "insert" a SELECT_CC instruction, we actually have to insert the
21641   // diamond control-flow pattern.  The incoming instruction knows the
21642   // destination vreg to set, the condition code register to branch on, the
21643   // true/false values to select between, and a branch opcode to use.
21644   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21645   MachineFunction::iterator It = ++BB->getIterator();
21646
21647   //  thisMBB:
21648   //  ...
21649   //   TrueVal = ...
21650   //   cmpTY ccX, r1, r2
21651   //   bCC copy1MBB
21652   //   fallthrough --> copy0MBB
21653   MachineBasicBlock *thisMBB = BB;
21654   MachineFunction *F = BB->getParent();
21655
21656   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21657   // as described above, by inserting a BB, and then making a PHI at the join
21658   // point to select the true and false operands of the CMOV in the PHI.
21659   //
21660   // The code also handles two different cases of multiple CMOV opcodes
21661   // in a row.
21662   //
21663   // Case 1:
21664   // In this case, there are multiple CMOVs in a row, all which are based on
21665   // the same condition setting (or the exact opposite condition setting).
21666   // In this case we can lower all the CMOVs using a single inserted BB, and
21667   // then make a number of PHIs at the join point to model the CMOVs. The only
21668   // trickiness here, is that in a case like:
21669   //
21670   // t2 = CMOV cond1 t1, f1
21671   // t3 = CMOV cond1 t2, f2
21672   //
21673   // when rewriting this into PHIs, we have to perform some renaming on the
21674   // temps since you cannot have a PHI operand refer to a PHI result earlier
21675   // in the same block.  The "simple" but wrong lowering would be:
21676   //
21677   // t2 = PHI t1(BB1), f1(BB2)
21678   // t3 = PHI t2(BB1), f2(BB2)
21679   //
21680   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21681   // renaming is to note that on the path through BB1, t2 is really just a
21682   // copy of t1, and do that renaming, properly generating:
21683   //
21684   // t2 = PHI t1(BB1), f1(BB2)
21685   // t3 = PHI t1(BB1), f2(BB2)
21686   //
21687   // Case 2, we lower cascaded CMOVs such as
21688   //
21689   //   (CMOV (CMOV F, T, cc1), T, cc2)
21690   //
21691   // to two successives branches.  For that, we look for another CMOV as the
21692   // following instruction.
21693   //
21694   // Without this, we would add a PHI between the two jumps, which ends up
21695   // creating a few copies all around. For instance, for
21696   //
21697   //    (sitofp (zext (fcmp une)))
21698   //
21699   // we would generate:
21700   //
21701   //         ucomiss %xmm1, %xmm0
21702   //         movss  <1.0f>, %xmm0
21703   //         movaps  %xmm0, %xmm1
21704   //         jne     .LBB5_2
21705   //         xorps   %xmm1, %xmm1
21706   // .LBB5_2:
21707   //         jp      .LBB5_4
21708   //         movaps  %xmm1, %xmm0
21709   // .LBB5_4:
21710   //         retq
21711   //
21712   // because this custom-inserter would have generated:
21713   //
21714   //   A
21715   //   | \
21716   //   |  B
21717   //   | /
21718   //   C
21719   //   | \
21720   //   |  D
21721   //   | /
21722   //   E
21723   //
21724   // A: X = ...; Y = ...
21725   // B: empty
21726   // C: Z = PHI [X, A], [Y, B]
21727   // D: empty
21728   // E: PHI [X, C], [Z, D]
21729   //
21730   // If we lower both CMOVs in a single step, we can instead generate:
21731   //
21732   //   A
21733   //   | \
21734   //   |  C
21735   //   | /|
21736   //   |/ |
21737   //   |  |
21738   //   |  D
21739   //   | /
21740   //   E
21741   //
21742   // A: X = ...; Y = ...
21743   // D: empty
21744   // E: PHI [X, A], [X, C], [Y, D]
21745   //
21746   // Which, in our sitofp/fcmp example, gives us something like:
21747   //
21748   //         ucomiss %xmm1, %xmm0
21749   //         movss  <1.0f>, %xmm0
21750   //         jne     .LBB5_4
21751   //         jp      .LBB5_4
21752   //         xorps   %xmm0, %xmm0
21753   // .LBB5_4:
21754   //         retq
21755   //
21756   MachineInstr *CascadedCMOV = nullptr;
21757   MachineInstr *LastCMOV = MI;
21758   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21759   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21760   MachineBasicBlock::iterator NextMIIt =
21761       std::next(MachineBasicBlock::iterator(MI));
21762
21763   // Check for case 1, where there are multiple CMOVs with the same condition
21764   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21765   // number of jumps the most.
21766
21767   if (isCMOVPseudo(MI)) {
21768     // See if we have a string of CMOVS with the same condition.
21769     while (NextMIIt != BB->end() &&
21770            isCMOVPseudo(NextMIIt) &&
21771            (NextMIIt->getOperand(3).getImm() == CC ||
21772             NextMIIt->getOperand(3).getImm() == OppCC)) {
21773       LastCMOV = &*NextMIIt;
21774       ++NextMIIt;
21775     }
21776   }
21777
21778   // This checks for case 2, but only do this if we didn't already find
21779   // case 1, as indicated by LastCMOV == MI.
21780   if (LastCMOV == MI &&
21781       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21782       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21783       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21784     CascadedCMOV = &*NextMIIt;
21785   }
21786
21787   MachineBasicBlock *jcc1MBB = nullptr;
21788
21789   // If we have a cascaded CMOV, we lower it to two successive branches to
21790   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21791   if (CascadedCMOV) {
21792     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21793     F->insert(It, jcc1MBB);
21794     jcc1MBB->addLiveIn(X86::EFLAGS);
21795   }
21796
21797   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21798   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21799   F->insert(It, copy0MBB);
21800   F->insert(It, sinkMBB);
21801
21802   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21803   // live into the sink and copy blocks.
21804   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21805
21806   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21807   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21808       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21809     copy0MBB->addLiveIn(X86::EFLAGS);
21810     sinkMBB->addLiveIn(X86::EFLAGS);
21811   }
21812
21813   // Transfer the remainder of BB and its successor edges to sinkMBB.
21814   sinkMBB->splice(sinkMBB->begin(), BB,
21815                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21816   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21817
21818   // Add the true and fallthrough blocks as its successors.
21819   if (CascadedCMOV) {
21820     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21821     BB->addSuccessor(jcc1MBB);
21822
21823     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21824     // jump to the sinkMBB.
21825     jcc1MBB->addSuccessor(copy0MBB);
21826     jcc1MBB->addSuccessor(sinkMBB);
21827   } else {
21828     BB->addSuccessor(copy0MBB);
21829   }
21830
21831   // The true block target of the first (or only) branch is always sinkMBB.
21832   BB->addSuccessor(sinkMBB);
21833
21834   // Create the conditional branch instruction.
21835   unsigned Opc = X86::GetCondBranchFromCond(CC);
21836   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21837
21838   if (CascadedCMOV) {
21839     unsigned Opc2 = X86::GetCondBranchFromCond(
21840         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21841     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21842   }
21843
21844   //  copy0MBB:
21845   //   %FalseValue = ...
21846   //   # fallthrough to sinkMBB
21847   copy0MBB->addSuccessor(sinkMBB);
21848
21849   //  sinkMBB:
21850   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21851   //  ...
21852   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21853   MachineBasicBlock::iterator MIItEnd =
21854     std::next(MachineBasicBlock::iterator(LastCMOV));
21855   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21856   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21857   MachineInstrBuilder MIB;
21858
21859   // As we are creating the PHIs, we have to be careful if there is more than
21860   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21861   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21862   // That also means that PHI construction must work forward from earlier to
21863   // later, and that the code must maintain a mapping from earlier PHI's
21864   // destination registers, and the registers that went into the PHI.
21865
21866   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21867     unsigned DestReg = MIIt->getOperand(0).getReg();
21868     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21869     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21870
21871     // If this CMOV we are generating is the opposite condition from
21872     // the jump we generated, then we have to swap the operands for the
21873     // PHI that is going to be generated.
21874     if (MIIt->getOperand(3).getImm() == OppCC)
21875         std::swap(Op1Reg, Op2Reg);
21876
21877     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21878       Op1Reg = RegRewriteTable[Op1Reg].first;
21879
21880     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21881       Op2Reg = RegRewriteTable[Op2Reg].second;
21882
21883     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21884                   TII->get(X86::PHI), DestReg)
21885           .addReg(Op1Reg).addMBB(copy0MBB)
21886           .addReg(Op2Reg).addMBB(thisMBB);
21887
21888     // Add this PHI to the rewrite table.
21889     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21890   }
21891
21892   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21893   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21894   if (CascadedCMOV) {
21895     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21896     // Copy the PHI result to the register defined by the second CMOV.
21897     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21898             DL, TII->get(TargetOpcode::COPY),
21899             CascadedCMOV->getOperand(0).getReg())
21900         .addReg(MI->getOperand(0).getReg());
21901     CascadedCMOV->eraseFromParent();
21902   }
21903
21904   // Now remove the CMOV(s).
21905   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21906     (MIIt++)->eraseFromParent();
21907
21908   return sinkMBB;
21909 }
21910
21911 MachineBasicBlock *
21912 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21913                                        MachineBasicBlock *BB) const {
21914   // Combine the following atomic floating-point modification pattern:
21915   //   a.store(reg OP a.load(acquire), release)
21916   // Transform them into:
21917   //   OPss (%gpr), %xmm
21918   //   movss %xmm, (%gpr)
21919   // Or sd equivalent for 64-bit operations.
21920   unsigned MOp, FOp;
21921   switch (MI->getOpcode()) {
21922   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21923   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21924   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21925   }
21926   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21927   DebugLoc DL = MI->getDebugLoc();
21928   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21929   MachineOperand MSrc = MI->getOperand(0);
21930   unsigned VSrc = MI->getOperand(5).getReg();
21931   const MachineOperand &Disp = MI->getOperand(3);
21932   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21933   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21934   if (hasDisp && MSrc.isReg())
21935     MSrc.setIsKill(false);
21936   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21937                                 .addOperand(/*Base=*/MSrc)
21938                                 .addImm(/*Scale=*/1)
21939                                 .addReg(/*Index=*/0)
21940                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21941                                 .addReg(0);
21942   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21943                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21944                           .addReg(VSrc)
21945                           .addOperand(/*Base=*/MSrc)
21946                           .addImm(/*Scale=*/1)
21947                           .addReg(/*Index=*/0)
21948                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21949                           .addReg(/*Segment=*/0);
21950   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21951   MI->eraseFromParent(); // The pseudo instruction is gone now.
21952   return BB;
21953 }
21954
21955 MachineBasicBlock *
21956 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21957                                         MachineBasicBlock *BB) const {
21958   MachineFunction *MF = BB->getParent();
21959   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21960   DebugLoc DL = MI->getDebugLoc();
21961   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21962
21963   assert(MF->shouldSplitStack());
21964
21965   const bool Is64Bit = Subtarget->is64Bit();
21966   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21967
21968   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21969   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21970
21971   // BB:
21972   //  ... [Till the alloca]
21973   // If stacklet is not large enough, jump to mallocMBB
21974   //
21975   // bumpMBB:
21976   //  Allocate by subtracting from RSP
21977   //  Jump to continueMBB
21978   //
21979   // mallocMBB:
21980   //  Allocate by call to runtime
21981   //
21982   // continueMBB:
21983   //  ...
21984   //  [rest of original BB]
21985   //
21986
21987   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21988   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21989   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21990
21991   MachineRegisterInfo &MRI = MF->getRegInfo();
21992   const TargetRegisterClass *AddrRegClass =
21993       getRegClassFor(getPointerTy(MF->getDataLayout()));
21994
21995   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21996     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21997     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21998     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21999     sizeVReg = MI->getOperand(1).getReg(),
22000     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
22001
22002   MachineFunction::iterator MBBIter = ++BB->getIterator();
22003
22004   MF->insert(MBBIter, bumpMBB);
22005   MF->insert(MBBIter, mallocMBB);
22006   MF->insert(MBBIter, continueMBB);
22007
22008   continueMBB->splice(continueMBB->begin(), BB,
22009                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
22010   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
22011
22012   // Add code to the main basic block to check if the stack limit has been hit,
22013   // and if so, jump to mallocMBB otherwise to bumpMBB.
22014   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
22015   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
22016     .addReg(tmpSPVReg).addReg(sizeVReg);
22017   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
22018     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
22019     .addReg(SPLimitVReg);
22020   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
22021
22022   // bumpMBB simply decreases the stack pointer, since we know the current
22023   // stacklet has enough space.
22024   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
22025     .addReg(SPLimitVReg);
22026   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
22027     .addReg(SPLimitVReg);
22028   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22029
22030   // Calls into a routine in libgcc to allocate more space from the heap.
22031   const uint32_t *RegMask =
22032       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
22033   if (IsLP64) {
22034     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
22035       .addReg(sizeVReg);
22036     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22037       .addExternalSymbol("__morestack_allocate_stack_space")
22038       .addRegMask(RegMask)
22039       .addReg(X86::RDI, RegState::Implicit)
22040       .addReg(X86::RAX, RegState::ImplicitDefine);
22041   } else if (Is64Bit) {
22042     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
22043       .addReg(sizeVReg);
22044     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22045       .addExternalSymbol("__morestack_allocate_stack_space")
22046       .addRegMask(RegMask)
22047       .addReg(X86::EDI, RegState::Implicit)
22048       .addReg(X86::EAX, RegState::ImplicitDefine);
22049   } else {
22050     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
22051       .addImm(12);
22052     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
22053     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
22054       .addExternalSymbol("__morestack_allocate_stack_space")
22055       .addRegMask(RegMask)
22056       .addReg(X86::EAX, RegState::ImplicitDefine);
22057   }
22058
22059   if (!Is64Bit)
22060     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
22061       .addImm(16);
22062
22063   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
22064     .addReg(IsLP64 ? X86::RAX : X86::EAX);
22065   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22066
22067   // Set up the CFG correctly.
22068   BB->addSuccessor(bumpMBB);
22069   BB->addSuccessor(mallocMBB);
22070   mallocMBB->addSuccessor(continueMBB);
22071   bumpMBB->addSuccessor(continueMBB);
22072
22073   // Take care of the PHI nodes.
22074   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
22075           MI->getOperand(0).getReg())
22076     .addReg(mallocPtrVReg).addMBB(mallocMBB)
22077     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
22078
22079   // Delete the original pseudo instruction.
22080   MI->eraseFromParent();
22081
22082   // And we're done.
22083   return continueMBB;
22084 }
22085
22086 MachineBasicBlock *
22087 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
22088                                         MachineBasicBlock *BB) const {
22089   assert(!Subtarget->isTargetMachO());
22090   DebugLoc DL = MI->getDebugLoc();
22091   MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
22092       *BB->getParent(), *BB, MI, DL, false);
22093   MachineBasicBlock *ResumeBB = ResumeMI->getParent();
22094   MI->eraseFromParent(); // The pseudo instruction is gone now.
22095   return ResumeBB;
22096 }
22097
22098 MachineBasicBlock *
22099 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
22100                                        MachineBasicBlock *BB) const {
22101   MachineFunction *MF = BB->getParent();
22102   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22103   MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
22104   DebugLoc DL = MI->getDebugLoc();
22105
22106   assert(!isAsynchronousEHPersonality(
22107              classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
22108          "SEH does not use catchret!");
22109
22110   // Only 32-bit EH needs to worry about manually restoring stack pointers.
22111   if (!Subtarget->is32Bit())
22112     return BB;
22113
22114   // C++ EH creates a new target block to hold the restore code, and wires up
22115   // the new block to the return destination with a normal JMP_4.
22116   MachineBasicBlock *RestoreMBB =
22117       MF->CreateMachineBasicBlock(BB->getBasicBlock());
22118   assert(BB->succ_size() == 1);
22119   MF->insert(std::next(BB->getIterator()), RestoreMBB);
22120   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
22121   BB->addSuccessor(RestoreMBB);
22122   MI->getOperand(0).setMBB(RestoreMBB);
22123
22124   auto RestoreMBBI = RestoreMBB->begin();
22125   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
22126   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
22127   return BB;
22128 }
22129
22130 MachineBasicBlock *
22131 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
22132                                        MachineBasicBlock *BB) const {
22133   MachineFunction *MF = BB->getParent();
22134   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
22135   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
22136   // Only 32-bit SEH requires special handling for catchpad.
22137   if (IsSEH && Subtarget->is32Bit()) {
22138     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22139     DebugLoc DL = MI->getDebugLoc();
22140     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
22141   }
22142   MI->eraseFromParent();
22143   return BB;
22144 }
22145
22146 MachineBasicBlock *
22147 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
22148                                       MachineBasicBlock *BB) const {
22149   // This is pretty easy.  We're taking the value that we received from
22150   // our load from the relocation, sticking it in either RDI (x86-64)
22151   // or EAX and doing an indirect call.  The return value will then
22152   // be in the normal return register.
22153   MachineFunction *F = BB->getParent();
22154   const X86InstrInfo *TII = Subtarget->getInstrInfo();
22155   DebugLoc DL = MI->getDebugLoc();
22156
22157   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
22158   assert(MI->getOperand(3).isGlobal() && "This should be a global");
22159
22160   // Get a register mask for the lowered call.
22161   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
22162   // proper register mask.
22163   const uint32_t *RegMask =
22164       Subtarget->is64Bit() ?
22165       Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
22166       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
22167   if (Subtarget->is64Bit()) {
22168     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22169                                       TII->get(X86::MOV64rm), X86::RDI)
22170     .addReg(X86::RIP)
22171     .addImm(0).addReg(0)
22172     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22173                       MI->getOperand(3).getTargetFlags())
22174     .addReg(0);
22175     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
22176     addDirectMem(MIB, X86::RDI);
22177     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
22178   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
22179     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22180                                       TII->get(X86::MOV32rm), X86::EAX)
22181     .addReg(0)
22182     .addImm(0).addReg(0)
22183     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22184                       MI->getOperand(3).getTargetFlags())
22185     .addReg(0);
22186     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22187     addDirectMem(MIB, X86::EAX);
22188     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22189   } else {
22190     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22191                                       TII->get(X86::MOV32rm), X86::EAX)
22192     .addReg(TII->getGlobalBaseReg(F))
22193     .addImm(0).addReg(0)
22194     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22195                       MI->getOperand(3).getTargetFlags())
22196     .addReg(0);
22197     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22198     addDirectMem(MIB, X86::EAX);
22199     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22200   }
22201
22202   MI->eraseFromParent(); // The pseudo instruction is gone now.
22203   return BB;
22204 }
22205
22206 MachineBasicBlock *
22207 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
22208                                     MachineBasicBlock *MBB) const {
22209   DebugLoc DL = MI->getDebugLoc();
22210   MachineFunction *MF = MBB->getParent();
22211   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22212   MachineRegisterInfo &MRI = MF->getRegInfo();
22213
22214   const BasicBlock *BB = MBB->getBasicBlock();
22215   MachineFunction::iterator I = ++MBB->getIterator();
22216
22217   // Memory Reference
22218   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22219   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22220
22221   unsigned DstReg;
22222   unsigned MemOpndSlot = 0;
22223
22224   unsigned CurOp = 0;
22225
22226   DstReg = MI->getOperand(CurOp++).getReg();
22227   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
22228   assert(RC->hasType(MVT::i32) && "Invalid destination!");
22229   unsigned mainDstReg = MRI.createVirtualRegister(RC);
22230   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
22231
22232   MemOpndSlot = CurOp;
22233
22234   MVT PVT = getPointerTy(MF->getDataLayout());
22235   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22236          "Invalid Pointer Size!");
22237
22238   // For v = setjmp(buf), we generate
22239   //
22240   // thisMBB:
22241   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
22242   //  SjLjSetup restoreMBB
22243   //
22244   // mainMBB:
22245   //  v_main = 0
22246   //
22247   // sinkMBB:
22248   //  v = phi(main, restore)
22249   //
22250   // restoreMBB:
22251   //  if base pointer being used, load it from frame
22252   //  v_restore = 1
22253
22254   MachineBasicBlock *thisMBB = MBB;
22255   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22256   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22257   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
22258   MF->insert(I, mainMBB);
22259   MF->insert(I, sinkMBB);
22260   MF->push_back(restoreMBB);
22261   restoreMBB->setHasAddressTaken();
22262
22263   MachineInstrBuilder MIB;
22264
22265   // Transfer the remainder of BB and its successor edges to sinkMBB.
22266   sinkMBB->splice(sinkMBB->begin(), MBB,
22267                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22268   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22269
22270   // thisMBB:
22271   unsigned PtrStoreOpc = 0;
22272   unsigned LabelReg = 0;
22273   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22274   Reloc::Model RM = MF->getTarget().getRelocationModel();
22275   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
22276                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
22277
22278   // Prepare IP either in reg or imm.
22279   if (!UseImmLabel) {
22280     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
22281     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
22282     LabelReg = MRI.createVirtualRegister(PtrRC);
22283     if (Subtarget->is64Bit()) {
22284       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
22285               .addReg(X86::RIP)
22286               .addImm(0)
22287               .addReg(0)
22288               .addMBB(restoreMBB)
22289               .addReg(0);
22290     } else {
22291       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
22292       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
22293               .addReg(XII->getGlobalBaseReg(MF))
22294               .addImm(0)
22295               .addReg(0)
22296               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
22297               .addReg(0);
22298     }
22299   } else
22300     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
22301   // Store IP
22302   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
22303   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22304     if (i == X86::AddrDisp)
22305       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
22306     else
22307       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
22308   }
22309   if (!UseImmLabel)
22310     MIB.addReg(LabelReg);
22311   else
22312     MIB.addMBB(restoreMBB);
22313   MIB.setMemRefs(MMOBegin, MMOEnd);
22314   // Setup
22315   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
22316           .addMBB(restoreMBB);
22317
22318   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22319   MIB.addRegMask(RegInfo->getNoPreservedMask());
22320   thisMBB->addSuccessor(mainMBB);
22321   thisMBB->addSuccessor(restoreMBB);
22322
22323   // mainMBB:
22324   //  EAX = 0
22325   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
22326   mainMBB->addSuccessor(sinkMBB);
22327
22328   // sinkMBB:
22329   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
22330           TII->get(X86::PHI), DstReg)
22331     .addReg(mainDstReg).addMBB(mainMBB)
22332     .addReg(restoreDstReg).addMBB(restoreMBB);
22333
22334   // restoreMBB:
22335   if (RegInfo->hasBasePointer(*MF)) {
22336     const bool Uses64BitFramePtr =
22337         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
22338     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
22339     X86FI->setRestoreBasePointer(MF);
22340     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
22341     unsigned BasePtr = RegInfo->getBaseRegister();
22342     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
22343     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
22344                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
22345       .setMIFlag(MachineInstr::FrameSetup);
22346   }
22347   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
22348   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
22349   restoreMBB->addSuccessor(sinkMBB);
22350
22351   MI->eraseFromParent();
22352   return sinkMBB;
22353 }
22354
22355 MachineBasicBlock *
22356 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22357                                      MachineBasicBlock *MBB) const {
22358   DebugLoc DL = MI->getDebugLoc();
22359   MachineFunction *MF = MBB->getParent();
22360   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22361   MachineRegisterInfo &MRI = MF->getRegInfo();
22362
22363   // Memory Reference
22364   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22365   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22366
22367   MVT PVT = getPointerTy(MF->getDataLayout());
22368   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22369          "Invalid Pointer Size!");
22370
22371   const TargetRegisterClass *RC =
22372     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22373   unsigned Tmp = MRI.createVirtualRegister(RC);
22374   // Since FP is only updated here but NOT referenced, it's treated as GPR.
22375   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22376   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22377   unsigned SP = RegInfo->getStackRegister();
22378
22379   MachineInstrBuilder MIB;
22380
22381   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22382   const int64_t SPOffset = 2 * PVT.getStoreSize();
22383
22384   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22385   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22386
22387   // Reload FP
22388   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22389   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22390     MIB.addOperand(MI->getOperand(i));
22391   MIB.setMemRefs(MMOBegin, MMOEnd);
22392   // Reload IP
22393   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22394   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22395     if (i == X86::AddrDisp)
22396       MIB.addDisp(MI->getOperand(i), LabelOffset);
22397     else
22398       MIB.addOperand(MI->getOperand(i));
22399   }
22400   MIB.setMemRefs(MMOBegin, MMOEnd);
22401   // Reload SP
22402   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22403   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22404     if (i == X86::AddrDisp)
22405       MIB.addDisp(MI->getOperand(i), SPOffset);
22406     else
22407       MIB.addOperand(MI->getOperand(i));
22408   }
22409   MIB.setMemRefs(MMOBegin, MMOEnd);
22410   // Jump
22411   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22412
22413   MI->eraseFromParent();
22414   return MBB;
22415 }
22416
22417 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22418 // accumulator loops. Writing back to the accumulator allows the coalescer
22419 // to remove extra copies in the loop.
22420 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
22421 MachineBasicBlock *
22422 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22423                                  MachineBasicBlock *MBB) const {
22424   MachineOperand &AddendOp = MI->getOperand(3);
22425
22426   // Bail out early if the addend isn't a register - we can't switch these.
22427   if (!AddendOp.isReg())
22428     return MBB;
22429
22430   MachineFunction &MF = *MBB->getParent();
22431   MachineRegisterInfo &MRI = MF.getRegInfo();
22432
22433   // Check whether the addend is defined by a PHI:
22434   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22435   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22436   if (!AddendDef.isPHI())
22437     return MBB;
22438
22439   // Look for the following pattern:
22440   // loop:
22441   //   %addend = phi [%entry, 0], [%loop, %result]
22442   //   ...
22443   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22444
22445   // Replace with:
22446   //   loop:
22447   //   %addend = phi [%entry, 0], [%loop, %result]
22448   //   ...
22449   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22450
22451   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22452     assert(AddendDef.getOperand(i).isReg());
22453     MachineOperand PHISrcOp = AddendDef.getOperand(i);
22454     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22455     if (&PHISrcInst == MI) {
22456       // Found a matching instruction.
22457       unsigned NewFMAOpc = 0;
22458       switch (MI->getOpcode()) {
22459         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22460         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22461         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22462         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22463         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22464         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22465         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22466         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22467         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22468         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22469         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22470         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22471         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22472         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22473         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22474         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22475         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22476         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22477         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22478         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22479
22480         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22481         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22482         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22483         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22484         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22485         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22486         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22487         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22488         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22489         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22490         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22491         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22492         default: llvm_unreachable("Unrecognized FMA variant.");
22493       }
22494
22495       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22496       MachineInstrBuilder MIB =
22497         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22498         .addOperand(MI->getOperand(0))
22499         .addOperand(MI->getOperand(3))
22500         .addOperand(MI->getOperand(2))
22501         .addOperand(MI->getOperand(1));
22502       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22503       MI->eraseFromParent();
22504     }
22505   }
22506
22507   return MBB;
22508 }
22509
22510 MachineBasicBlock *
22511 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22512                                                MachineBasicBlock *BB) const {
22513   switch (MI->getOpcode()) {
22514   default: llvm_unreachable("Unexpected instr type to insert");
22515   case X86::TAILJMPd64:
22516   case X86::TAILJMPr64:
22517   case X86::TAILJMPm64:
22518   case X86::TAILJMPd64_REX:
22519   case X86::TAILJMPr64_REX:
22520   case X86::TAILJMPm64_REX:
22521     llvm_unreachable("TAILJMP64 would not be touched here.");
22522   case X86::TCRETURNdi64:
22523   case X86::TCRETURNri64:
22524   case X86::TCRETURNmi64:
22525     return BB;
22526   case X86::WIN_ALLOCA:
22527     return EmitLoweredWinAlloca(MI, BB);
22528   case X86::CATCHRET:
22529     return EmitLoweredCatchRet(MI, BB);
22530   case X86::CATCHPAD:
22531     return EmitLoweredCatchPad(MI, BB);
22532   case X86::SEG_ALLOCA_32:
22533   case X86::SEG_ALLOCA_64:
22534     return EmitLoweredSegAlloca(MI, BB);
22535   case X86::TLSCall_32:
22536   case X86::TLSCall_64:
22537     return EmitLoweredTLSCall(MI, BB);
22538   case X86::CMOV_FR32:
22539   case X86::CMOV_FR64:
22540   case X86::CMOV_FR128:
22541   case X86::CMOV_GR8:
22542   case X86::CMOV_GR16:
22543   case X86::CMOV_GR32:
22544   case X86::CMOV_RFP32:
22545   case X86::CMOV_RFP64:
22546   case X86::CMOV_RFP80:
22547   case X86::CMOV_V2F64:
22548   case X86::CMOV_V2I64:
22549   case X86::CMOV_V4F32:
22550   case X86::CMOV_V4F64:
22551   case X86::CMOV_V4I64:
22552   case X86::CMOV_V16F32:
22553   case X86::CMOV_V8F32:
22554   case X86::CMOV_V8F64:
22555   case X86::CMOV_V8I64:
22556   case X86::CMOV_V8I1:
22557   case X86::CMOV_V16I1:
22558   case X86::CMOV_V32I1:
22559   case X86::CMOV_V64I1:
22560     return EmitLoweredSelect(MI, BB);
22561
22562   case X86::RDFLAGS32:
22563   case X86::RDFLAGS64: {
22564     DebugLoc DL = MI->getDebugLoc();
22565     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22566     unsigned PushF =
22567         MI->getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
22568     unsigned Pop =
22569         MI->getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
22570     BuildMI(*BB, MI, DL, TII->get(PushF));
22571     BuildMI(*BB, MI, DL, TII->get(Pop), MI->getOperand(0).getReg());
22572
22573     MI->eraseFromParent(); // The pseudo is gone now.
22574     return BB;
22575   }
22576
22577   case X86::WRFLAGS32:
22578   case X86::WRFLAGS64: {
22579     DebugLoc DL = MI->getDebugLoc();
22580     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22581     unsigned Push =
22582         MI->getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
22583     unsigned PopF =
22584         MI->getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
22585     BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI->getOperand(0).getReg());
22586     BuildMI(*BB, MI, DL, TII->get(PopF));
22587
22588     MI->eraseFromParent(); // The pseudo is gone now.
22589     return BB;
22590   }
22591
22592   case X86::RELEASE_FADD32mr:
22593   case X86::RELEASE_FADD64mr:
22594     return EmitLoweredAtomicFP(MI, BB);
22595
22596   case X86::FP32_TO_INT16_IN_MEM:
22597   case X86::FP32_TO_INT32_IN_MEM:
22598   case X86::FP32_TO_INT64_IN_MEM:
22599   case X86::FP64_TO_INT16_IN_MEM:
22600   case X86::FP64_TO_INT32_IN_MEM:
22601   case X86::FP64_TO_INT64_IN_MEM:
22602   case X86::FP80_TO_INT16_IN_MEM:
22603   case X86::FP80_TO_INT32_IN_MEM:
22604   case X86::FP80_TO_INT64_IN_MEM: {
22605     MachineFunction *F = BB->getParent();
22606     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22607     DebugLoc DL = MI->getDebugLoc();
22608
22609     // Change the floating point control register to use "round towards zero"
22610     // mode when truncating to an integer value.
22611     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22612     addFrameReference(BuildMI(*BB, MI, DL,
22613                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
22614
22615     // Load the old value of the high byte of the control word...
22616     unsigned OldCW =
22617       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22618     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22619                       CWFrameIdx);
22620
22621     // Set the high part to be round to zero...
22622     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22623       .addImm(0xC7F);
22624
22625     // Reload the modified control word now...
22626     addFrameReference(BuildMI(*BB, MI, DL,
22627                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22628
22629     // Restore the memory image of control word to original value
22630     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22631       .addReg(OldCW);
22632
22633     // Get the X86 opcode to use.
22634     unsigned Opc;
22635     switch (MI->getOpcode()) {
22636     default: llvm_unreachable("illegal opcode!");
22637     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22638     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22639     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22640     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22641     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22642     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22643     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22644     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22645     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22646     }
22647
22648     X86AddressMode AM;
22649     MachineOperand &Op = MI->getOperand(0);
22650     if (Op.isReg()) {
22651       AM.BaseType = X86AddressMode::RegBase;
22652       AM.Base.Reg = Op.getReg();
22653     } else {
22654       AM.BaseType = X86AddressMode::FrameIndexBase;
22655       AM.Base.FrameIndex = Op.getIndex();
22656     }
22657     Op = MI->getOperand(1);
22658     if (Op.isImm())
22659       AM.Scale = Op.getImm();
22660     Op = MI->getOperand(2);
22661     if (Op.isImm())
22662       AM.IndexReg = Op.getImm();
22663     Op = MI->getOperand(3);
22664     if (Op.isGlobal()) {
22665       AM.GV = Op.getGlobal();
22666     } else {
22667       AM.Disp = Op.getImm();
22668     }
22669     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22670                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22671
22672     // Reload the original control word now.
22673     addFrameReference(BuildMI(*BB, MI, DL,
22674                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22675
22676     MI->eraseFromParent();   // The pseudo instruction is gone now.
22677     return BB;
22678   }
22679     // String/text processing lowering.
22680   case X86::PCMPISTRM128REG:
22681   case X86::VPCMPISTRM128REG:
22682   case X86::PCMPISTRM128MEM:
22683   case X86::VPCMPISTRM128MEM:
22684   case X86::PCMPESTRM128REG:
22685   case X86::VPCMPESTRM128REG:
22686   case X86::PCMPESTRM128MEM:
22687   case X86::VPCMPESTRM128MEM:
22688     assert(Subtarget->hasSSE42() &&
22689            "Target must have SSE4.2 or AVX features enabled");
22690     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22691
22692   // String/text processing lowering.
22693   case X86::PCMPISTRIREG:
22694   case X86::VPCMPISTRIREG:
22695   case X86::PCMPISTRIMEM:
22696   case X86::VPCMPISTRIMEM:
22697   case X86::PCMPESTRIREG:
22698   case X86::VPCMPESTRIREG:
22699   case X86::PCMPESTRIMEM:
22700   case X86::VPCMPESTRIMEM:
22701     assert(Subtarget->hasSSE42() &&
22702            "Target must have SSE4.2 or AVX features enabled");
22703     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22704
22705   // Thread synchronization.
22706   case X86::MONITOR:
22707     return EmitMonitor(MI, BB, Subtarget);
22708   // PKU feature
22709   case X86::WRPKRU:
22710     return EmitWRPKRU(MI, BB, Subtarget);
22711   case X86::RDPKRU:
22712     return EmitRDPKRU(MI, BB, Subtarget);
22713   // xbegin
22714   case X86::XBEGIN:
22715     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22716
22717   case X86::VASTART_SAVE_XMM_REGS:
22718     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22719
22720   case X86::VAARG_64:
22721     return EmitVAARG64WithCustomInserter(MI, BB);
22722
22723   case X86::EH_SjLj_SetJmp32:
22724   case X86::EH_SjLj_SetJmp64:
22725     return emitEHSjLjSetJmp(MI, BB);
22726
22727   case X86::EH_SjLj_LongJmp32:
22728   case X86::EH_SjLj_LongJmp64:
22729     return emitEHSjLjLongJmp(MI, BB);
22730
22731   case TargetOpcode::STATEPOINT:
22732     // As an implementation detail, STATEPOINT shares the STACKMAP format at
22733     // this point in the process.  We diverge later.
22734     return emitPatchPoint(MI, BB);
22735
22736   case TargetOpcode::STACKMAP:
22737   case TargetOpcode::PATCHPOINT:
22738     return emitPatchPoint(MI, BB);
22739
22740   case X86::VFMADDPDr213r:
22741   case X86::VFMADDPSr213r:
22742   case X86::VFMADDSDr213r:
22743   case X86::VFMADDSSr213r:
22744   case X86::VFMSUBPDr213r:
22745   case X86::VFMSUBPSr213r:
22746   case X86::VFMSUBSDr213r:
22747   case X86::VFMSUBSSr213r:
22748   case X86::VFNMADDPDr213r:
22749   case X86::VFNMADDPSr213r:
22750   case X86::VFNMADDSDr213r:
22751   case X86::VFNMADDSSr213r:
22752   case X86::VFNMSUBPDr213r:
22753   case X86::VFNMSUBPSr213r:
22754   case X86::VFNMSUBSDr213r:
22755   case X86::VFNMSUBSSr213r:
22756   case X86::VFMADDSUBPDr213r:
22757   case X86::VFMADDSUBPSr213r:
22758   case X86::VFMSUBADDPDr213r:
22759   case X86::VFMSUBADDPSr213r:
22760   case X86::VFMADDPDr213rY:
22761   case X86::VFMADDPSr213rY:
22762   case X86::VFMSUBPDr213rY:
22763   case X86::VFMSUBPSr213rY:
22764   case X86::VFNMADDPDr213rY:
22765   case X86::VFNMADDPSr213rY:
22766   case X86::VFNMSUBPDr213rY:
22767   case X86::VFNMSUBPSr213rY:
22768   case X86::VFMADDSUBPDr213rY:
22769   case X86::VFMADDSUBPSr213rY:
22770   case X86::VFMSUBADDPDr213rY:
22771   case X86::VFMSUBADDPSr213rY:
22772     return emitFMA3Instr(MI, BB);
22773   }
22774 }
22775
22776 //===----------------------------------------------------------------------===//
22777 //                           X86 Optimization Hooks
22778 //===----------------------------------------------------------------------===//
22779
22780 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22781                                                       APInt &KnownZero,
22782                                                       APInt &KnownOne,
22783                                                       const SelectionDAG &DAG,
22784                                                       unsigned Depth) const {
22785   unsigned BitWidth = KnownZero.getBitWidth();
22786   unsigned Opc = Op.getOpcode();
22787   assert((Opc >= ISD::BUILTIN_OP_END ||
22788           Opc == ISD::INTRINSIC_WO_CHAIN ||
22789           Opc == ISD::INTRINSIC_W_CHAIN ||
22790           Opc == ISD::INTRINSIC_VOID) &&
22791          "Should use MaskedValueIsZero if you don't know whether Op"
22792          " is a target node!");
22793
22794   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
22795   switch (Opc) {
22796   default: break;
22797   case X86ISD::ADD:
22798   case X86ISD::SUB:
22799   case X86ISD::ADC:
22800   case X86ISD::SBB:
22801   case X86ISD::SMUL:
22802   case X86ISD::UMUL:
22803   case X86ISD::INC:
22804   case X86ISD::DEC:
22805   case X86ISD::OR:
22806   case X86ISD::XOR:
22807   case X86ISD::AND:
22808     // These nodes' second result is a boolean.
22809     if (Op.getResNo() == 0)
22810       break;
22811     // Fallthrough
22812   case X86ISD::SETCC:
22813     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22814     break;
22815   case ISD::INTRINSIC_WO_CHAIN: {
22816     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22817     unsigned NumLoBits = 0;
22818     switch (IntId) {
22819     default: break;
22820     case Intrinsic::x86_sse_movmsk_ps:
22821     case Intrinsic::x86_avx_movmsk_ps_256:
22822     case Intrinsic::x86_sse2_movmsk_pd:
22823     case Intrinsic::x86_avx_movmsk_pd_256:
22824     case Intrinsic::x86_mmx_pmovmskb:
22825     case Intrinsic::x86_sse2_pmovmskb_128:
22826     case Intrinsic::x86_avx2_pmovmskb: {
22827       // High bits of movmskp{s|d}, pmovmskb are known zero.
22828       switch (IntId) {
22829         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22830         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22831         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22832         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22833         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22834         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22835         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22836         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22837       }
22838       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22839       break;
22840     }
22841     }
22842     break;
22843   }
22844   }
22845 }
22846
22847 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22848   SDValue Op,
22849   const SelectionDAG &,
22850   unsigned Depth) const {
22851   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22852   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22853     return Op.getValueType().getScalarSizeInBits();
22854
22855   // Fallback case.
22856   return 1;
22857 }
22858
22859 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22860 /// node is a GlobalAddress + offset.
22861 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22862                                        const GlobalValue* &GA,
22863                                        int64_t &Offset) const {
22864   if (N->getOpcode() == X86ISD::Wrapper) {
22865     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22866       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22867       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22868       return true;
22869     }
22870   }
22871   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22872 }
22873
22874 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22875 /// FIXME: This could be expanded to support 512 bit vectors as well.
22876 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22877                                         TargetLowering::DAGCombinerInfo &DCI,
22878                                         const X86Subtarget* Subtarget) {
22879   SDLoc dl(N);
22880   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22881   SDValue V1 = SVOp->getOperand(0);
22882   SDValue V2 = SVOp->getOperand(1);
22883   MVT VT = SVOp->getSimpleValueType(0);
22884   unsigned NumElems = VT.getVectorNumElements();
22885
22886   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22887       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22888     //
22889     //                   0,0,0,...
22890     //                      |
22891     //    V      UNDEF    BUILD_VECTOR    UNDEF
22892     //     \      /           \           /
22893     //  CONCAT_VECTOR         CONCAT_VECTOR
22894     //         \                  /
22895     //          \                /
22896     //          RESULT: V + zero extended
22897     //
22898     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22899         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22900         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22901       return SDValue();
22902
22903     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22904       return SDValue();
22905
22906     // To match the shuffle mask, the first half of the mask should
22907     // be exactly the first vector, and all the rest a splat with the
22908     // first element of the second one.
22909     for (unsigned i = 0; i != NumElems/2; ++i)
22910       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22911           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22912         return SDValue();
22913
22914     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22915     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22916       if (Ld->hasNUsesOfValue(1, 0)) {
22917         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22918         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22919         SDValue ResNode =
22920           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22921                                   Ld->getMemoryVT(),
22922                                   Ld->getPointerInfo(),
22923                                   Ld->getAlignment(),
22924                                   false/*isVolatile*/, true/*ReadMem*/,
22925                                   false/*WriteMem*/);
22926
22927         // Make sure the newly-created LOAD is in the same position as Ld in
22928         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22929         // and update uses of Ld's output chain to use the TokenFactor.
22930         if (Ld->hasAnyUseOfValue(1)) {
22931           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22932                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22933           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22934           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22935                                  SDValue(ResNode.getNode(), 1));
22936         }
22937
22938         return DAG.getBitcast(VT, ResNode);
22939       }
22940     }
22941
22942     // Emit a zeroed vector and insert the desired subvector on its
22943     // first half.
22944     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22945     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22946     return DCI.CombineTo(N, InsV);
22947   }
22948
22949   return SDValue();
22950 }
22951
22952 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22953 /// possible.
22954 ///
22955 /// This is the leaf of the recursive combinine below. When we have found some
22956 /// chain of single-use x86 shuffle instructions and accumulated the combined
22957 /// shuffle mask represented by them, this will try to pattern match that mask
22958 /// into either a single instruction if there is a special purpose instruction
22959 /// for this operation, or into a PSHUFB instruction which is a fully general
22960 /// instruction but should only be used to replace chains over a certain depth.
22961 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22962                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22963                                    TargetLowering::DAGCombinerInfo &DCI,
22964                                    const X86Subtarget *Subtarget) {
22965   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22966
22967   // Find the operand that enters the chain. Note that multiple uses are OK
22968   // here, we're not going to remove the operand we find.
22969   SDValue Input = Op.getOperand(0);
22970   while (Input.getOpcode() == ISD::BITCAST)
22971     Input = Input.getOperand(0);
22972
22973   MVT VT = Input.getSimpleValueType();
22974   MVT RootVT = Root.getSimpleValueType();
22975   SDLoc DL(Root);
22976
22977   if (Mask.size() == 1) {
22978     int Index = Mask[0];
22979     assert((Index >= 0 || Index == SM_SentinelUndef ||
22980             Index == SM_SentinelZero) &&
22981            "Invalid shuffle index found!");
22982
22983     // We may end up with an accumulated mask of size 1 as a result of
22984     // widening of shuffle operands (see function canWidenShuffleElements).
22985     // If the only shuffle index is equal to SM_SentinelZero then propagate
22986     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22987     // mask, and therefore the entire chain of shuffles can be folded away.
22988     if (Index == SM_SentinelZero)
22989       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22990     else
22991       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22992                     /*AddTo*/ true);
22993     return true;
22994   }
22995
22996   // Use the float domain if the operand type is a floating point type.
22997   bool FloatDomain = VT.isFloatingPoint();
22998
22999   // For floating point shuffles, we don't have free copies in the shuffle
23000   // instructions or the ability to load as part of the instruction, so
23001   // canonicalize their shuffles to UNPCK or MOV variants.
23002   //
23003   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
23004   // vectors because it can have a load folded into it that UNPCK cannot. This
23005   // doesn't preclude something switching to the shorter encoding post-RA.
23006   //
23007   // FIXME: Should teach these routines about AVX vector widths.
23008   if (FloatDomain && VT.is128BitVector()) {
23009     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
23010       bool Lo = Mask.equals({0, 0});
23011       unsigned Shuffle;
23012       MVT ShuffleVT;
23013       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
23014       // is no slower than UNPCKLPD but has the option to fold the input operand
23015       // into even an unaligned memory load.
23016       if (Lo && Subtarget->hasSSE3()) {
23017         Shuffle = X86ISD::MOVDDUP;
23018         ShuffleVT = MVT::v2f64;
23019       } else {
23020         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
23021         // than the UNPCK variants.
23022         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
23023         ShuffleVT = MVT::v4f32;
23024       }
23025       if (Depth == 1 && Root->getOpcode() == Shuffle)
23026         return false; // Nothing to do!
23027       Op = DAG.getBitcast(ShuffleVT, Input);
23028       DCI.AddToWorklist(Op.getNode());
23029       if (Shuffle == X86ISD::MOVDDUP)
23030         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23031       else
23032         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23033       DCI.AddToWorklist(Op.getNode());
23034       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23035                     /*AddTo*/ true);
23036       return true;
23037     }
23038     if (Subtarget->hasSSE3() &&
23039         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
23040       bool Lo = Mask.equals({0, 0, 2, 2});
23041       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
23042       MVT ShuffleVT = MVT::v4f32;
23043       if (Depth == 1 && Root->getOpcode() == Shuffle)
23044         return false; // Nothing to do!
23045       Op = DAG.getBitcast(ShuffleVT, Input);
23046       DCI.AddToWorklist(Op.getNode());
23047       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23048       DCI.AddToWorklist(Op.getNode());
23049       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23050                     /*AddTo*/ true);
23051       return true;
23052     }
23053     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
23054       bool Lo = Mask.equals({0, 0, 1, 1});
23055       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23056       MVT ShuffleVT = MVT::v4f32;
23057       if (Depth == 1 && Root->getOpcode() == Shuffle)
23058         return false; // Nothing to do!
23059       Op = DAG.getBitcast(ShuffleVT, Input);
23060       DCI.AddToWorklist(Op.getNode());
23061       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23062       DCI.AddToWorklist(Op.getNode());
23063       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23064                     /*AddTo*/ true);
23065       return true;
23066     }
23067   }
23068
23069   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
23070   // variants as none of these have single-instruction variants that are
23071   // superior to the UNPCK formulation.
23072   if (!FloatDomain && VT.is128BitVector() &&
23073       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23074        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
23075        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
23076        Mask.equals(
23077            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
23078     bool Lo = Mask[0] == 0;
23079     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23080     if (Depth == 1 && Root->getOpcode() == Shuffle)
23081       return false; // Nothing to do!
23082     MVT ShuffleVT;
23083     switch (Mask.size()) {
23084     case 8:
23085       ShuffleVT = MVT::v8i16;
23086       break;
23087     case 16:
23088       ShuffleVT = MVT::v16i8;
23089       break;
23090     default:
23091       llvm_unreachable("Impossible mask size!");
23092     };
23093     Op = DAG.getBitcast(ShuffleVT, Input);
23094     DCI.AddToWorklist(Op.getNode());
23095     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23096     DCI.AddToWorklist(Op.getNode());
23097     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23098                   /*AddTo*/ true);
23099     return true;
23100   }
23101
23102   // Don't try to re-form single instruction chains under any circumstances now
23103   // that we've done encoding canonicalization for them.
23104   if (Depth < 2)
23105     return false;
23106
23107   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
23108   // can replace them with a single PSHUFB instruction profitably. Intel's
23109   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
23110   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
23111   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
23112     SmallVector<SDValue, 16> PSHUFBMask;
23113     int NumBytes = VT.getSizeInBits() / 8;
23114     int Ratio = NumBytes / Mask.size();
23115     for (int i = 0; i < NumBytes; ++i) {
23116       if (Mask[i / Ratio] == SM_SentinelUndef) {
23117         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
23118         continue;
23119       }
23120       int M = Mask[i / Ratio] != SM_SentinelZero
23121                   ? Ratio * Mask[i / Ratio] + i % Ratio
23122                   : 255;
23123       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
23124     }
23125     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
23126     Op = DAG.getBitcast(ByteVT, Input);
23127     DCI.AddToWorklist(Op.getNode());
23128     SDValue PSHUFBMaskOp =
23129         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
23130     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
23131     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
23132     DCI.AddToWorklist(Op.getNode());
23133     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23134                   /*AddTo*/ true);
23135     return true;
23136   }
23137
23138   // Failed to find any combines.
23139   return false;
23140 }
23141
23142 /// \brief Fully generic combining of x86 shuffle instructions.
23143 ///
23144 /// This should be the last combine run over the x86 shuffle instructions. Once
23145 /// they have been fully optimized, this will recursively consider all chains
23146 /// of single-use shuffle instructions, build a generic model of the cumulative
23147 /// shuffle operation, and check for simpler instructions which implement this
23148 /// operation. We use this primarily for two purposes:
23149 ///
23150 /// 1) Collapse generic shuffles to specialized single instructions when
23151 ///    equivalent. In most cases, this is just an encoding size win, but
23152 ///    sometimes we will collapse multiple generic shuffles into a single
23153 ///    special-purpose shuffle.
23154 /// 2) Look for sequences of shuffle instructions with 3 or more total
23155 ///    instructions, and replace them with the slightly more expensive SSSE3
23156 ///    PSHUFB instruction if available. We do this as the last combining step
23157 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
23158 ///    a suitable short sequence of other instructions. The PHUFB will either
23159 ///    use a register or have to read from memory and so is slightly (but only
23160 ///    slightly) more expensive than the other shuffle instructions.
23161 ///
23162 /// Because this is inherently a quadratic operation (for each shuffle in
23163 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
23164 /// This should never be an issue in practice as the shuffle lowering doesn't
23165 /// produce sequences of more than 8 instructions.
23166 ///
23167 /// FIXME: We will currently miss some cases where the redundant shuffling
23168 /// would simplify under the threshold for PSHUFB formation because of
23169 /// combine-ordering. To fix this, we should do the redundant instruction
23170 /// combining in this recursive walk.
23171 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
23172                                           ArrayRef<int> RootMask,
23173                                           int Depth, bool HasPSHUFB,
23174                                           SelectionDAG &DAG,
23175                                           TargetLowering::DAGCombinerInfo &DCI,
23176                                           const X86Subtarget *Subtarget) {
23177   // Bound the depth of our recursive combine because this is ultimately
23178   // quadratic in nature.
23179   if (Depth > 8)
23180     return false;
23181
23182   // Directly rip through bitcasts to find the underlying operand.
23183   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
23184     Op = Op.getOperand(0);
23185
23186   MVT VT = Op.getSimpleValueType();
23187   if (!VT.isVector())
23188     return false; // Bail if we hit a non-vector.
23189
23190   assert(Root.getSimpleValueType().isVector() &&
23191          "Shuffles operate on vector types!");
23192   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
23193          "Can only combine shuffles of the same vector register size.");
23194
23195   if (!isTargetShuffle(Op.getOpcode()))
23196     return false;
23197   SmallVector<int, 16> OpMask;
23198   bool IsUnary;
23199   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, true, OpMask, IsUnary);
23200   // We only can combine unary shuffles which we can decode the mask for.
23201   if (!HaveMask || !IsUnary)
23202     return false;
23203
23204   assert(VT.getVectorNumElements() == OpMask.size() &&
23205          "Different mask size from vector size!");
23206   assert(((RootMask.size() > OpMask.size() &&
23207            RootMask.size() % OpMask.size() == 0) ||
23208           (OpMask.size() > RootMask.size() &&
23209            OpMask.size() % RootMask.size() == 0) ||
23210           OpMask.size() == RootMask.size()) &&
23211          "The smaller number of elements must divide the larger.");
23212   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
23213   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
23214   assert(((RootRatio == 1 && OpRatio == 1) ||
23215           (RootRatio == 1) != (OpRatio == 1)) &&
23216          "Must not have a ratio for both incoming and op masks!");
23217
23218   SmallVector<int, 16> Mask;
23219   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
23220
23221   // Merge this shuffle operation's mask into our accumulated mask. Note that
23222   // this shuffle's mask will be the first applied to the input, followed by the
23223   // root mask to get us all the way to the root value arrangement. The reason
23224   // for this order is that we are recursing up the operation chain.
23225   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
23226     int RootIdx = i / RootRatio;
23227     if (RootMask[RootIdx] < 0) {
23228       // This is a zero or undef lane, we're done.
23229       Mask.push_back(RootMask[RootIdx]);
23230       continue;
23231     }
23232
23233     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
23234     int OpIdx = RootMaskedIdx / OpRatio;
23235     if (OpMask[OpIdx] < 0) {
23236       // The incoming lanes are zero or undef, it doesn't matter which ones we
23237       // are using.
23238       Mask.push_back(OpMask[OpIdx]);
23239       continue;
23240     }
23241
23242     // Ok, we have non-zero lanes, map them through.
23243     Mask.push_back(OpMask[OpIdx] * OpRatio +
23244                    RootMaskedIdx % OpRatio);
23245   }
23246
23247   // See if we can recurse into the operand to combine more things.
23248   switch (Op.getOpcode()) {
23249   case X86ISD::PSHUFB:
23250     HasPSHUFB = true;
23251   case X86ISD::PSHUFD:
23252   case X86ISD::PSHUFHW:
23253   case X86ISD::PSHUFLW:
23254     if (Op.getOperand(0).hasOneUse() &&
23255         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23256                                       HasPSHUFB, DAG, DCI, Subtarget))
23257       return true;
23258     break;
23259
23260   case X86ISD::UNPCKL:
23261   case X86ISD::UNPCKH:
23262     assert(Op.getOperand(0) == Op.getOperand(1) &&
23263            "We only combine unary shuffles!");
23264     // We can't check for single use, we have to check that this shuffle is the
23265     // only user.
23266     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
23267         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23268                                       HasPSHUFB, DAG, DCI, Subtarget))
23269       return true;
23270     break;
23271   }
23272
23273   // Minor canonicalization of the accumulated shuffle mask to make it easier
23274   // to match below. All this does is detect masks with squential pairs of
23275   // elements, and shrink them to the half-width mask. It does this in a loop
23276   // so it will reduce the size of the mask to the minimal width mask which
23277   // performs an equivalent shuffle.
23278   SmallVector<int, 16> WidenedMask;
23279   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
23280     Mask = std::move(WidenedMask);
23281     WidenedMask.clear();
23282   }
23283
23284   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
23285                                 Subtarget);
23286 }
23287
23288 /// \brief Get the PSHUF-style mask from PSHUF node.
23289 ///
23290 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
23291 /// PSHUF-style masks that can be reused with such instructions.
23292 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
23293   MVT VT = N.getSimpleValueType();
23294   SmallVector<int, 4> Mask;
23295   bool IsUnary;
23296   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, false, Mask, IsUnary);
23297   (void)HaveMask;
23298   assert(HaveMask);
23299
23300   // If we have more than 128-bits, only the low 128-bits of shuffle mask
23301   // matter. Check that the upper masks are repeats and remove them.
23302   if (VT.getSizeInBits() > 128) {
23303     int LaneElts = 128 / VT.getScalarSizeInBits();
23304 #ifndef NDEBUG
23305     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
23306       for (int j = 0; j < LaneElts; ++j)
23307         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
23308                "Mask doesn't repeat in high 128-bit lanes!");
23309 #endif
23310     Mask.resize(LaneElts);
23311   }
23312
23313   switch (N.getOpcode()) {
23314   case X86ISD::PSHUFD:
23315     return Mask;
23316   case X86ISD::PSHUFLW:
23317     Mask.resize(4);
23318     return Mask;
23319   case X86ISD::PSHUFHW:
23320     Mask.erase(Mask.begin(), Mask.begin() + 4);
23321     for (int &M : Mask)
23322       M -= 4;
23323     return Mask;
23324   default:
23325     llvm_unreachable("No valid shuffle instruction found!");
23326   }
23327 }
23328
23329 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
23330 ///
23331 /// We walk up the chain and look for a combinable shuffle, skipping over
23332 /// shuffles that we could hoist this shuffle's transformation past without
23333 /// altering anything.
23334 static SDValue
23335 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23336                              SelectionDAG &DAG,
23337                              TargetLowering::DAGCombinerInfo &DCI) {
23338   assert(N.getOpcode() == X86ISD::PSHUFD &&
23339          "Called with something other than an x86 128-bit half shuffle!");
23340   SDLoc DL(N);
23341
23342   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23343   // of the shuffles in the chain so that we can form a fresh chain to replace
23344   // this one.
23345   SmallVector<SDValue, 8> Chain;
23346   SDValue V = N.getOperand(0);
23347   for (; V.hasOneUse(); V = V.getOperand(0)) {
23348     switch (V.getOpcode()) {
23349     default:
23350       return SDValue(); // Nothing combined!
23351
23352     case ISD::BITCAST:
23353       // Skip bitcasts as we always know the type for the target specific
23354       // instructions.
23355       continue;
23356
23357     case X86ISD::PSHUFD:
23358       // Found another dword shuffle.
23359       break;
23360
23361     case X86ISD::PSHUFLW:
23362       // Check that the low words (being shuffled) are the identity in the
23363       // dword shuffle, and the high words are self-contained.
23364       if (Mask[0] != 0 || Mask[1] != 1 ||
23365           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23366         return SDValue();
23367
23368       Chain.push_back(V);
23369       continue;
23370
23371     case X86ISD::PSHUFHW:
23372       // Check that the high words (being shuffled) are the identity in the
23373       // dword shuffle, and the low words are self-contained.
23374       if (Mask[2] != 2 || Mask[3] != 3 ||
23375           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23376         return SDValue();
23377
23378       Chain.push_back(V);
23379       continue;
23380
23381     case X86ISD::UNPCKL:
23382     case X86ISD::UNPCKH:
23383       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23384       // shuffle into a preceding word shuffle.
23385       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23386           V.getSimpleValueType().getVectorElementType() != MVT::i16)
23387         return SDValue();
23388
23389       // Search for a half-shuffle which we can combine with.
23390       unsigned CombineOp =
23391           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23392       if (V.getOperand(0) != V.getOperand(1) ||
23393           !V->isOnlyUserOf(V.getOperand(0).getNode()))
23394         return SDValue();
23395       Chain.push_back(V);
23396       V = V.getOperand(0);
23397       do {
23398         switch (V.getOpcode()) {
23399         default:
23400           return SDValue(); // Nothing to combine.
23401
23402         case X86ISD::PSHUFLW:
23403         case X86ISD::PSHUFHW:
23404           if (V.getOpcode() == CombineOp)
23405             break;
23406
23407           Chain.push_back(V);
23408
23409           // Fallthrough!
23410         case ISD::BITCAST:
23411           V = V.getOperand(0);
23412           continue;
23413         }
23414         break;
23415       } while (V.hasOneUse());
23416       break;
23417     }
23418     // Break out of the loop if we break out of the switch.
23419     break;
23420   }
23421
23422   if (!V.hasOneUse())
23423     // We fell out of the loop without finding a viable combining instruction.
23424     return SDValue();
23425
23426   // Merge this node's mask and our incoming mask.
23427   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23428   for (int &M : Mask)
23429     M = VMask[M];
23430   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23431                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23432
23433   // Rebuild the chain around this new shuffle.
23434   while (!Chain.empty()) {
23435     SDValue W = Chain.pop_back_val();
23436
23437     if (V.getValueType() != W.getOperand(0).getValueType())
23438       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23439
23440     switch (W.getOpcode()) {
23441     default:
23442       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23443
23444     case X86ISD::UNPCKL:
23445     case X86ISD::UNPCKH:
23446       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23447       break;
23448
23449     case X86ISD::PSHUFD:
23450     case X86ISD::PSHUFLW:
23451     case X86ISD::PSHUFHW:
23452       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23453       break;
23454     }
23455   }
23456   if (V.getValueType() != N.getValueType())
23457     V = DAG.getBitcast(N.getValueType(), V);
23458
23459   // Return the new chain to replace N.
23460   return V;
23461 }
23462
23463 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23464 /// pshufhw.
23465 ///
23466 /// We walk up the chain, skipping shuffles of the other half and looking
23467 /// through shuffles which switch halves trying to find a shuffle of the same
23468 /// pair of dwords.
23469 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23470                                         SelectionDAG &DAG,
23471                                         TargetLowering::DAGCombinerInfo &DCI) {
23472   assert(
23473       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23474       "Called with something other than an x86 128-bit half shuffle!");
23475   SDLoc DL(N);
23476   unsigned CombineOpcode = N.getOpcode();
23477
23478   // Walk up a single-use chain looking for a combinable shuffle.
23479   SDValue V = N.getOperand(0);
23480   for (; V.hasOneUse(); V = V.getOperand(0)) {
23481     switch (V.getOpcode()) {
23482     default:
23483       return false; // Nothing combined!
23484
23485     case ISD::BITCAST:
23486       // Skip bitcasts as we always know the type for the target specific
23487       // instructions.
23488       continue;
23489
23490     case X86ISD::PSHUFLW:
23491     case X86ISD::PSHUFHW:
23492       if (V.getOpcode() == CombineOpcode)
23493         break;
23494
23495       // Other-half shuffles are no-ops.
23496       continue;
23497     }
23498     // Break out of the loop if we break out of the switch.
23499     break;
23500   }
23501
23502   if (!V.hasOneUse())
23503     // We fell out of the loop without finding a viable combining instruction.
23504     return false;
23505
23506   // Combine away the bottom node as its shuffle will be accumulated into
23507   // a preceding shuffle.
23508   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23509
23510   // Record the old value.
23511   SDValue Old = V;
23512
23513   // Merge this node's mask and our incoming mask (adjusted to account for all
23514   // the pshufd instructions encountered).
23515   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23516   for (int &M : Mask)
23517     M = VMask[M];
23518   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23519                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23520
23521   // Check that the shuffles didn't cancel each other out. If not, we need to
23522   // combine to the new one.
23523   if (Old != V)
23524     // Replace the combinable shuffle with the combined one, updating all users
23525     // so that we re-evaluate the chain here.
23526     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23527
23528   return true;
23529 }
23530
23531 /// \brief Try to combine x86 target specific shuffles.
23532 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23533                                            TargetLowering::DAGCombinerInfo &DCI,
23534                                            const X86Subtarget *Subtarget) {
23535   SDLoc DL(N);
23536   MVT VT = N.getSimpleValueType();
23537   SmallVector<int, 4> Mask;
23538
23539   switch (N.getOpcode()) {
23540   case X86ISD::PSHUFD:
23541   case X86ISD::PSHUFLW:
23542   case X86ISD::PSHUFHW:
23543     Mask = getPSHUFShuffleMask(N);
23544     assert(Mask.size() == 4);
23545     break;
23546   case X86ISD::UNPCKL: {
23547     // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23548     // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23549     // moves upper half elements into the lower half part. For example:
23550     //
23551     // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23552     //     undef:v16i8
23553     // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23554     //
23555     // will be combined to:
23556     //
23557     // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23558
23559     // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23560     // happen due to advanced instructions.
23561     if (!VT.is128BitVector())
23562       return SDValue();
23563
23564     auto Op0 = N.getOperand(0);
23565     auto Op1 = N.getOperand(1);
23566     if (Op0.getOpcode() == ISD::UNDEF &&
23567         Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23568       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23569
23570       unsigned NumElts = VT.getVectorNumElements();
23571       SmallVector<int, 8> ExpectedMask(NumElts, -1);
23572       std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23573                 NumElts / 2);
23574
23575       auto ShufOp = Op1.getOperand(0);
23576       if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23577         return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23578     }
23579     return SDValue();
23580   }
23581   case X86ISD::BLENDI: {
23582     SDValue V0 = N->getOperand(0);
23583     SDValue V1 = N->getOperand(1);
23584     assert(VT == V0.getSimpleValueType() && VT == V1.getSimpleValueType() &&
23585            "Unexpected input vector types");
23586
23587     // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23588     // operands and changing the mask to 1. This saves us a bunch of
23589     // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23590     // x86InstrInfo knows how to commute this back after instruction selection
23591     // if it would help register allocation.
23592
23593     // TODO: If optimizing for size or a processor that doesn't suffer from
23594     // partial register update stalls, this should be transformed into a MOVSD
23595     // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23596
23597     if (VT == MVT::v2f64)
23598       if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23599         if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23600           SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23601           return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23602         }
23603
23604     return SDValue();
23605   }
23606   default:
23607     return SDValue();
23608   }
23609
23610   // Nuke no-op shuffles that show up after combining.
23611   if (isNoopShuffleMask(Mask))
23612     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23613
23614   // Look for simplifications involving one or two shuffle instructions.
23615   SDValue V = N.getOperand(0);
23616   switch (N.getOpcode()) {
23617   default:
23618     break;
23619   case X86ISD::PSHUFLW:
23620   case X86ISD::PSHUFHW:
23621     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23622
23623     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23624       return SDValue(); // We combined away this shuffle, so we're done.
23625
23626     // See if this reduces to a PSHUFD which is no more expensive and can
23627     // combine with more operations. Note that it has to at least flip the
23628     // dwords as otherwise it would have been removed as a no-op.
23629     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23630       int DMask[] = {0, 1, 2, 3};
23631       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23632       DMask[DOffset + 0] = DOffset + 1;
23633       DMask[DOffset + 1] = DOffset + 0;
23634       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23635       V = DAG.getBitcast(DVT, V);
23636       DCI.AddToWorklist(V.getNode());
23637       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23638                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23639       DCI.AddToWorklist(V.getNode());
23640       return DAG.getBitcast(VT, V);
23641     }
23642
23643     // Look for shuffle patterns which can be implemented as a single unpack.
23644     // FIXME: This doesn't handle the location of the PSHUFD generically, and
23645     // only works when we have a PSHUFD followed by two half-shuffles.
23646     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23647         (V.getOpcode() == X86ISD::PSHUFLW ||
23648          V.getOpcode() == X86ISD::PSHUFHW) &&
23649         V.getOpcode() != N.getOpcode() &&
23650         V.hasOneUse()) {
23651       SDValue D = V.getOperand(0);
23652       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23653         D = D.getOperand(0);
23654       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23655         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23656         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23657         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23658         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23659         int WordMask[8];
23660         for (int i = 0; i < 4; ++i) {
23661           WordMask[i + NOffset] = Mask[i] + NOffset;
23662           WordMask[i + VOffset] = VMask[i] + VOffset;
23663         }
23664         // Map the word mask through the DWord mask.
23665         int MappedMask[8];
23666         for (int i = 0; i < 8; ++i)
23667           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23668         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23669             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23670           // We can replace all three shuffles with an unpack.
23671           V = DAG.getBitcast(VT, D.getOperand(0));
23672           DCI.AddToWorklist(V.getNode());
23673           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23674                                                 : X86ISD::UNPCKH,
23675                              DL, VT, V, V);
23676         }
23677       }
23678     }
23679
23680     break;
23681
23682   case X86ISD::PSHUFD:
23683     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23684       return NewN;
23685
23686     break;
23687   }
23688
23689   return SDValue();
23690 }
23691
23692 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23693 ///
23694 /// We combine this directly on the abstract vector shuffle nodes so it is
23695 /// easier to generically match. We also insert dummy vector shuffle nodes for
23696 /// the operands which explicitly discard the lanes which are unused by this
23697 /// operation to try to flow through the rest of the combiner the fact that
23698 /// they're unused.
23699 static SDValue combineShuffleToAddSub(SDNode *N, const X86Subtarget *Subtarget,
23700                                       SelectionDAG &DAG) {
23701   SDLoc DL(N);
23702   EVT VT = N->getValueType(0);
23703   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
23704       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
23705     return SDValue();
23706
23707   // We only handle target-independent shuffles.
23708   // FIXME: It would be easy and harmless to use the target shuffle mask
23709   // extraction tool to support more.
23710   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23711     return SDValue();
23712
23713   auto *SVN = cast<ShuffleVectorSDNode>(N);
23714   SmallVector<int, 8> Mask;
23715   for (int M : SVN->getMask())
23716     Mask.push_back(M);
23717
23718   SDValue V1 = N->getOperand(0);
23719   SDValue V2 = N->getOperand(1);
23720
23721   // We require the first shuffle operand to be the FSUB node, and the second to
23722   // be the FADD node.
23723   if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23724     ShuffleVectorSDNode::commuteMask(Mask);
23725     std::swap(V1, V2);
23726   } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23727     return SDValue();
23728
23729   // If there are other uses of these operations we can't fold them.
23730   if (!V1->hasOneUse() || !V2->hasOneUse())
23731     return SDValue();
23732
23733   // Ensure that both operations have the same operands. Note that we can
23734   // commute the FADD operands.
23735   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23736   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23737       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23738     return SDValue();
23739
23740   // We're looking for blends between FADD and FSUB nodes. We insist on these
23741   // nodes being lined up in a specific expected pattern.
23742   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23743         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23744         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23745     return SDValue();
23746
23747   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23748 }
23749
23750 /// PerformShuffleCombine - Performs several different shuffle combines.
23751 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23752                                      TargetLowering::DAGCombinerInfo &DCI,
23753                                      const X86Subtarget *Subtarget) {
23754   SDLoc dl(N);
23755   SDValue N0 = N->getOperand(0);
23756   SDValue N1 = N->getOperand(1);
23757   EVT VT = N->getValueType(0);
23758
23759   // Don't create instructions with illegal types after legalize types has run.
23760   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23761   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23762     return SDValue();
23763
23764   // If we have legalized the vector types, look for blends of FADD and FSUB
23765   // nodes that we can fuse into an ADDSUB node.
23766   if (TLI.isTypeLegal(VT))
23767     if (SDValue AddSub = combineShuffleToAddSub(N, Subtarget, DAG))
23768       return AddSub;
23769
23770   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23771   if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23772       N->getOpcode() == ISD::VECTOR_SHUFFLE)
23773     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23774
23775   // During Type Legalization, when promoting illegal vector types,
23776   // the backend might introduce new shuffle dag nodes and bitcasts.
23777   //
23778   // This code performs the following transformation:
23779   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23780   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23781   //
23782   // We do this only if both the bitcast and the BINOP dag nodes have
23783   // one use. Also, perform this transformation only if the new binary
23784   // operation is legal. This is to avoid introducing dag nodes that
23785   // potentially need to be further expanded (or custom lowered) into a
23786   // less optimal sequence of dag nodes.
23787   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23788       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23789       N0.getOpcode() == ISD::BITCAST) {
23790     SDValue BC0 = N0.getOperand(0);
23791     EVT SVT = BC0.getValueType();
23792     unsigned Opcode = BC0.getOpcode();
23793     unsigned NumElts = VT.getVectorNumElements();
23794
23795     if (BC0.hasOneUse() && SVT.isVector() &&
23796         SVT.getVectorNumElements() * 2 == NumElts &&
23797         TLI.isOperationLegal(Opcode, VT)) {
23798       bool CanFold = false;
23799       switch (Opcode) {
23800       default : break;
23801       case ISD::ADD :
23802       case ISD::FADD :
23803       case ISD::SUB :
23804       case ISD::FSUB :
23805       case ISD::MUL :
23806       case ISD::FMUL :
23807         CanFold = true;
23808       }
23809
23810       unsigned SVTNumElts = SVT.getVectorNumElements();
23811       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23812       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23813         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23814       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23815         CanFold = SVOp->getMaskElt(i) < 0;
23816
23817       if (CanFold) {
23818         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23819         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23820         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23821         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23822       }
23823     }
23824   }
23825
23826   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23827   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23828   // consecutive, non-overlapping, and in the right order.
23829   SmallVector<SDValue, 16> Elts;
23830   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23831     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23832
23833   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23834     return LD;
23835
23836   if (isTargetShuffle(N->getOpcode())) {
23837     SDValue Shuffle =
23838         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23839     if (Shuffle.getNode())
23840       return Shuffle;
23841
23842     // Try recursively combining arbitrary sequences of x86 shuffle
23843     // instructions into higher-order shuffles. We do this after combining
23844     // specific PSHUF instruction sequences into their minimal form so that we
23845     // can evaluate how many specialized shuffle instructions are involved in
23846     // a particular chain.
23847     SmallVector<int, 1> NonceMask; // Just a placeholder.
23848     NonceMask.push_back(0);
23849     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23850                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23851                                       DCI, Subtarget))
23852       return SDValue(); // This routine will use CombineTo to replace N.
23853   }
23854
23855   return SDValue();
23856 }
23857
23858 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23859 /// specific shuffle of a load can be folded into a single element load.
23860 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23861 /// shuffles have been custom lowered so we need to handle those here.
23862 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23863                                          TargetLowering::DAGCombinerInfo &DCI) {
23864   if (DCI.isBeforeLegalizeOps())
23865     return SDValue();
23866
23867   SDValue InVec = N->getOperand(0);
23868   SDValue EltNo = N->getOperand(1);
23869   EVT EltVT = N->getValueType(0);
23870
23871   if (!isa<ConstantSDNode>(EltNo))
23872     return SDValue();
23873
23874   EVT OriginalVT = InVec.getValueType();
23875
23876   if (InVec.getOpcode() == ISD::BITCAST) {
23877     // Don't duplicate a load with other uses.
23878     if (!InVec.hasOneUse())
23879       return SDValue();
23880     EVT BCVT = InVec.getOperand(0).getValueType();
23881     if (!BCVT.isVector() ||
23882         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23883       return SDValue();
23884     InVec = InVec.getOperand(0);
23885   }
23886
23887   EVT CurrentVT = InVec.getValueType();
23888
23889   if (!isTargetShuffle(InVec.getOpcode()))
23890     return SDValue();
23891
23892   // Don't duplicate a load with other uses.
23893   if (!InVec.hasOneUse())
23894     return SDValue();
23895
23896   SmallVector<int, 16> ShuffleMask;
23897   bool UnaryShuffle;
23898   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(), true,
23899                             ShuffleMask, UnaryShuffle))
23900     return SDValue();
23901
23902   // Select the input vector, guarding against out of range extract vector.
23903   unsigned NumElems = CurrentVT.getVectorNumElements();
23904   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23905   int Idx = (Elt > (int)NumElems) ? SM_SentinelUndef : ShuffleMask[Elt];
23906
23907   if (Idx == SM_SentinelZero)
23908     return EltVT.isInteger() ? DAG.getConstant(0, SDLoc(N), EltVT)
23909                              : DAG.getConstantFP(+0.0, SDLoc(N), EltVT);
23910   if (Idx == SM_SentinelUndef)
23911     return DAG.getUNDEF(EltVT);
23912
23913   assert(0 <= Idx && Idx < (int)(2 * NumElems) && "Shuffle index out of range");
23914   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23915                                          : InVec.getOperand(1);
23916
23917   // If inputs to shuffle are the same for both ops, then allow 2 uses
23918   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23919                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23920
23921   if (LdNode.getOpcode() == ISD::BITCAST) {
23922     // Don't duplicate a load with other uses.
23923     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23924       return SDValue();
23925
23926     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23927     LdNode = LdNode.getOperand(0);
23928   }
23929
23930   if (!ISD::isNormalLoad(LdNode.getNode()))
23931     return SDValue();
23932
23933   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23934
23935   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23936     return SDValue();
23937
23938   // If there's a bitcast before the shuffle, check if the load type and
23939   // alignment is valid.
23940   unsigned Align = LN0->getAlignment();
23941   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23942   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23943       EltVT.getTypeForEVT(*DAG.getContext()));
23944
23945   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23946     return SDValue();
23947
23948   // All checks match so transform back to vector_shuffle so that DAG combiner
23949   // can finish the job
23950   SDLoc dl(N);
23951
23952   // Create shuffle node taking into account the case that its a unary shuffle
23953   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23954                                    : InVec.getOperand(1);
23955   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23956                                  InVec.getOperand(0), Shuffle,
23957                                  &ShuffleMask[0]);
23958   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23959   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23960                      EltNo);
23961 }
23962
23963 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
23964                                      const X86Subtarget *Subtarget) {
23965   SDValue N0 = N->getOperand(0);
23966   EVT VT = N->getValueType(0);
23967
23968   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23969   // special and don't usually play with other vector types, it's better to
23970   // handle them early to be sure we emit efficient code by avoiding
23971   // store-load conversions.
23972   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
23973       N0.getValueType() == MVT::v2i32 &&
23974       isNullConstant(N0.getOperand(1))) {
23975     SDValue N00 = N0->getOperand(0);
23976     if (N00.getValueType() == MVT::i32)
23977       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
23978   }
23979
23980   // Convert a bitcasted integer logic operation that has one bitcasted
23981   // floating-point operand and one constant operand into a floating-point
23982   // logic operation. This may create a load of the constant, but that is
23983   // cheaper than materializing the constant in an integer register and
23984   // transferring it to an SSE register or transferring the SSE operand to
23985   // integer register and back.
23986   unsigned FPOpcode;
23987   switch (N0.getOpcode()) {
23988     case ISD::AND: FPOpcode = X86ISD::FAND; break;
23989     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
23990     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
23991     default: return SDValue();
23992   }
23993   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
23994        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
23995       isa<ConstantSDNode>(N0.getOperand(1)) &&
23996       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
23997       N0.getOperand(0).getOperand(0).getValueType() == VT) {
23998     SDValue N000 = N0.getOperand(0).getOperand(0);
23999     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
24000     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
24001   }
24002
24003   return SDValue();
24004 }
24005
24006 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
24007 /// generation and convert it from being a bunch of shuffles and extracts
24008 /// into a somewhat faster sequence. For i686, the best sequence is apparently
24009 /// storing the value and loading scalars back, while for x64 we should
24010 /// use 64-bit extracts and shifts.
24011 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
24012                                          TargetLowering::DAGCombinerInfo &DCI) {
24013   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
24014     return NewOp;
24015
24016   SDValue InputVector = N->getOperand(0);
24017   SDLoc dl(InputVector);
24018   // Detect mmx to i32 conversion through a v2i32 elt extract.
24019   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
24020       N->getValueType(0) == MVT::i32 &&
24021       InputVector.getValueType() == MVT::v2i32) {
24022
24023     // The bitcast source is a direct mmx result.
24024     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
24025     if (MMXSrc.getValueType() == MVT::x86mmx)
24026       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24027                          N->getValueType(0),
24028                          InputVector.getNode()->getOperand(0));
24029
24030     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
24031     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
24032         MMXSrc.getValueType() == MVT::i64) {
24033       SDValue MMXSrcOp = MMXSrc.getOperand(0);
24034       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
24035           MMXSrcOp.getValueType() == MVT::v1i64 &&
24036           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
24037         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24038                            N->getValueType(0), MMXSrcOp.getOperand(0));
24039     }
24040   }
24041
24042   EVT VT = N->getValueType(0);
24043
24044   if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
24045       InputVector.getOpcode() == ISD::BITCAST &&
24046       isa<ConstantSDNode>(InputVector.getOperand(0))) {
24047     uint64_t ExtractedElt =
24048         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
24049     uint64_t InputValue =
24050         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
24051     uint64_t Res = (InputValue >> ExtractedElt) & 1;
24052     return DAG.getConstant(Res, dl, MVT::i1);
24053   }
24054   // Only operate on vectors of 4 elements, where the alternative shuffling
24055   // gets to be more expensive.
24056   if (InputVector.getValueType() != MVT::v4i32)
24057     return SDValue();
24058
24059   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
24060   // single use which is a sign-extend or zero-extend, and all elements are
24061   // used.
24062   SmallVector<SDNode *, 4> Uses;
24063   unsigned ExtractedElements = 0;
24064   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
24065        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
24066     if (UI.getUse().getResNo() != InputVector.getResNo())
24067       return SDValue();
24068
24069     SDNode *Extract = *UI;
24070     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
24071       return SDValue();
24072
24073     if (Extract->getValueType(0) != MVT::i32)
24074       return SDValue();
24075     if (!Extract->hasOneUse())
24076       return SDValue();
24077     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
24078         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
24079       return SDValue();
24080     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
24081       return SDValue();
24082
24083     // Record which element was extracted.
24084     ExtractedElements |=
24085       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
24086
24087     Uses.push_back(Extract);
24088   }
24089
24090   // If not all the elements were used, this may not be worthwhile.
24091   if (ExtractedElements != 15)
24092     return SDValue();
24093
24094   // Ok, we've now decided to do the transformation.
24095   // If 64-bit shifts are legal, use the extract-shift sequence,
24096   // otherwise bounce the vector off the cache.
24097   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24098   SDValue Vals[4];
24099
24100   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
24101     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
24102     auto &DL = DAG.getDataLayout();
24103     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
24104     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24105       DAG.getConstant(0, dl, VecIdxTy));
24106     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24107       DAG.getConstant(1, dl, VecIdxTy));
24108
24109     SDValue ShAmt = DAG.getConstant(
24110         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
24111     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
24112     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24113       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
24114     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
24115     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24116       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
24117   } else {
24118     // Store the value to a temporary stack slot.
24119     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
24120     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
24121       MachinePointerInfo(), false, false, 0);
24122
24123     EVT ElementType = InputVector.getValueType().getVectorElementType();
24124     unsigned EltSize = ElementType.getSizeInBits() / 8;
24125
24126     // Replace each use (extract) with a load of the appropriate element.
24127     for (unsigned i = 0; i < 4; ++i) {
24128       uint64_t Offset = EltSize * i;
24129       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24130       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
24131
24132       SDValue ScalarAddr =
24133           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
24134
24135       // Load the scalar.
24136       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
24137                             ScalarAddr, MachinePointerInfo(),
24138                             false, false, false, 0);
24139
24140     }
24141   }
24142
24143   // Replace the extracts
24144   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
24145     UE = Uses.end(); UI != UE; ++UI) {
24146     SDNode *Extract = *UI;
24147
24148     SDValue Idx = Extract->getOperand(1);
24149     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
24150     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
24151   }
24152
24153   // The replacement was made in place; don't return anything.
24154   return SDValue();
24155 }
24156
24157 static SDValue
24158 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
24159                                       const X86Subtarget *Subtarget) {
24160   SDLoc dl(N);
24161   SDValue Cond = N->getOperand(0);
24162   SDValue LHS = N->getOperand(1);
24163   SDValue RHS = N->getOperand(2);
24164
24165   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
24166     SDValue CondSrc = Cond->getOperand(0);
24167     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
24168       Cond = CondSrc->getOperand(0);
24169   }
24170
24171   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
24172     return SDValue();
24173
24174   // A vselect where all conditions and data are constants can be optimized into
24175   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
24176   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
24177       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
24178     return SDValue();
24179
24180   unsigned MaskValue = 0;
24181   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
24182     return SDValue();
24183
24184   MVT VT = N->getSimpleValueType(0);
24185   unsigned NumElems = VT.getVectorNumElements();
24186   SmallVector<int, 8> ShuffleMask(NumElems, -1);
24187   for (unsigned i = 0; i < NumElems; ++i) {
24188     // Be sure we emit undef where we can.
24189     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
24190       ShuffleMask[i] = -1;
24191     else
24192       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
24193   }
24194
24195   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24196   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
24197     return SDValue();
24198   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
24199 }
24200
24201 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
24202 /// nodes.
24203 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
24204                                     TargetLowering::DAGCombinerInfo &DCI,
24205                                     const X86Subtarget *Subtarget) {
24206   SDLoc DL(N);
24207   SDValue Cond = N->getOperand(0);
24208   // Get the LHS/RHS of the select.
24209   SDValue LHS = N->getOperand(1);
24210   SDValue RHS = N->getOperand(2);
24211   EVT VT = LHS.getValueType();
24212   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24213
24214   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
24215   // instructions match the semantics of the common C idiom x<y?x:y but not
24216   // x<=y?x:y, because of how they handle negative zero (which can be
24217   // ignored in unsafe-math mode).
24218   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
24219   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
24220       VT != MVT::f80 && VT != MVT::f128 &&
24221       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
24222       (Subtarget->hasSSE2() ||
24223        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
24224     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24225
24226     unsigned Opcode = 0;
24227     // Check for x CC y ? x : y.
24228     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24229         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24230       switch (CC) {
24231       default: break;
24232       case ISD::SETULT:
24233         // Converting this to a min would handle NaNs incorrectly, and swapping
24234         // the operands would cause it to handle comparisons between positive
24235         // and negative zero incorrectly.
24236         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24237           if (!DAG.getTarget().Options.UnsafeFPMath &&
24238               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24239             break;
24240           std::swap(LHS, RHS);
24241         }
24242         Opcode = X86ISD::FMIN;
24243         break;
24244       case ISD::SETOLE:
24245         // Converting this to a min would handle comparisons between positive
24246         // and negative zero incorrectly.
24247         if (!DAG.getTarget().Options.UnsafeFPMath &&
24248             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24249           break;
24250         Opcode = X86ISD::FMIN;
24251         break;
24252       case ISD::SETULE:
24253         // Converting this to a min would handle both negative zeros and NaNs
24254         // incorrectly, but we can swap the operands to fix both.
24255         std::swap(LHS, RHS);
24256       case ISD::SETOLT:
24257       case ISD::SETLT:
24258       case ISD::SETLE:
24259         Opcode = X86ISD::FMIN;
24260         break;
24261
24262       case ISD::SETOGE:
24263         // Converting this to a max would handle comparisons between positive
24264         // and negative zero incorrectly.
24265         if (!DAG.getTarget().Options.UnsafeFPMath &&
24266             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24267           break;
24268         Opcode = X86ISD::FMAX;
24269         break;
24270       case ISD::SETUGT:
24271         // Converting this to a max would handle NaNs incorrectly, and swapping
24272         // the operands would cause it to handle comparisons between positive
24273         // and negative zero incorrectly.
24274         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24275           if (!DAG.getTarget().Options.UnsafeFPMath &&
24276               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24277             break;
24278           std::swap(LHS, RHS);
24279         }
24280         Opcode = X86ISD::FMAX;
24281         break;
24282       case ISD::SETUGE:
24283         // Converting this to a max would handle both negative zeros and NaNs
24284         // incorrectly, but we can swap the operands to fix both.
24285         std::swap(LHS, RHS);
24286       case ISD::SETOGT:
24287       case ISD::SETGT:
24288       case ISD::SETGE:
24289         Opcode = X86ISD::FMAX;
24290         break;
24291       }
24292     // Check for x CC y ? y : x -- a min/max with reversed arms.
24293     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
24294                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
24295       switch (CC) {
24296       default: break;
24297       case ISD::SETOGE:
24298         // Converting this to a min would handle comparisons between positive
24299         // and negative zero incorrectly, and swapping the operands would
24300         // cause it to handle NaNs incorrectly.
24301         if (!DAG.getTarget().Options.UnsafeFPMath &&
24302             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
24303           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24304             break;
24305           std::swap(LHS, RHS);
24306         }
24307         Opcode = X86ISD::FMIN;
24308         break;
24309       case ISD::SETUGT:
24310         // Converting this to a min would handle NaNs incorrectly.
24311         if (!DAG.getTarget().Options.UnsafeFPMath &&
24312             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
24313           break;
24314         Opcode = X86ISD::FMIN;
24315         break;
24316       case ISD::SETUGE:
24317         // Converting this to a min would handle both negative zeros and NaNs
24318         // incorrectly, but we can swap the operands to fix both.
24319         std::swap(LHS, RHS);
24320       case ISD::SETOGT:
24321       case ISD::SETGT:
24322       case ISD::SETGE:
24323         Opcode = X86ISD::FMIN;
24324         break;
24325
24326       case ISD::SETULT:
24327         // Converting this to a max would handle NaNs incorrectly.
24328         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24329           break;
24330         Opcode = X86ISD::FMAX;
24331         break;
24332       case ISD::SETOLE:
24333         // Converting this to a max would handle comparisons between positive
24334         // and negative zero incorrectly, and swapping the operands would
24335         // cause it to handle NaNs incorrectly.
24336         if (!DAG.getTarget().Options.UnsafeFPMath &&
24337             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
24338           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24339             break;
24340           std::swap(LHS, RHS);
24341         }
24342         Opcode = X86ISD::FMAX;
24343         break;
24344       case ISD::SETULE:
24345         // Converting this to a max would handle both negative zeros and NaNs
24346         // incorrectly, but we can swap the operands to fix both.
24347         std::swap(LHS, RHS);
24348       case ISD::SETOLT:
24349       case ISD::SETLT:
24350       case ISD::SETLE:
24351         Opcode = X86ISD::FMAX;
24352         break;
24353       }
24354     }
24355
24356     if (Opcode)
24357       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
24358   }
24359
24360   EVT CondVT = Cond.getValueType();
24361   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
24362       CondVT.getVectorElementType() == MVT::i1) {
24363     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
24364     // lowering on KNL. In this case we convert it to
24365     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24366     // The same situation for all 128 and 256-bit vectors of i8 and i16.
24367     // Since SKX these selects have a proper lowering.
24368     EVT OpVT = LHS.getValueType();
24369     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24370         (OpVT.getVectorElementType() == MVT::i8 ||
24371          OpVT.getVectorElementType() == MVT::i16) &&
24372         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24373       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24374       DCI.AddToWorklist(Cond.getNode());
24375       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24376     }
24377   }
24378   // If this is a select between two integer constants, try to do some
24379   // optimizations.
24380   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24381     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24382       // Don't do this for crazy integer types.
24383       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24384         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24385         // so that TrueC (the true value) is larger than FalseC.
24386         bool NeedsCondInvert = false;
24387
24388         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24389             // Efficiently invertible.
24390             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
24391              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
24392               isa<ConstantSDNode>(Cond.getOperand(1))))) {
24393           NeedsCondInvert = true;
24394           std::swap(TrueC, FalseC);
24395         }
24396
24397         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
24398         if (FalseC->getAPIntValue() == 0 &&
24399             TrueC->getAPIntValue().isPowerOf2()) {
24400           if (NeedsCondInvert) // Invert the condition if needed.
24401             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24402                                DAG.getConstant(1, DL, Cond.getValueType()));
24403
24404           // Zero extend the condition if needed.
24405           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
24406
24407           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24408           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24409                              DAG.getConstant(ShAmt, DL, MVT::i8));
24410         }
24411
24412         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24413         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24414           if (NeedsCondInvert) // Invert the condition if needed.
24415             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24416                                DAG.getConstant(1, DL, Cond.getValueType()));
24417
24418           // Zero extend the condition if needed.
24419           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24420                              FalseC->getValueType(0), Cond);
24421           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24422                              SDValue(FalseC, 0));
24423         }
24424
24425         // Optimize cases that will turn into an LEA instruction.  This requires
24426         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24427         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24428           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24429           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24430
24431           bool isFastMultiplier = false;
24432           if (Diff < 10) {
24433             switch ((unsigned char)Diff) {
24434               default: break;
24435               case 1:  // result = add base, cond
24436               case 2:  // result = lea base(    , cond*2)
24437               case 3:  // result = lea base(cond, cond*2)
24438               case 4:  // result = lea base(    , cond*4)
24439               case 5:  // result = lea base(cond, cond*4)
24440               case 8:  // result = lea base(    , cond*8)
24441               case 9:  // result = lea base(cond, cond*8)
24442                 isFastMultiplier = true;
24443                 break;
24444             }
24445           }
24446
24447           if (isFastMultiplier) {
24448             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24449             if (NeedsCondInvert) // Invert the condition if needed.
24450               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24451                                  DAG.getConstant(1, DL, Cond.getValueType()));
24452
24453             // Zero extend the condition if needed.
24454             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24455                                Cond);
24456             // Scale the condition by the difference.
24457             if (Diff != 1)
24458               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24459                                  DAG.getConstant(Diff, DL,
24460                                                  Cond.getValueType()));
24461
24462             // Add the base if non-zero.
24463             if (FalseC->getAPIntValue() != 0)
24464               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24465                                  SDValue(FalseC, 0));
24466             return Cond;
24467           }
24468         }
24469       }
24470   }
24471
24472   // Canonicalize max and min:
24473   // (x > y) ? x : y -> (x >= y) ? x : y
24474   // (x < y) ? x : y -> (x <= y) ? x : y
24475   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24476   // the need for an extra compare
24477   // against zero. e.g.
24478   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24479   // subl   %esi, %edi
24480   // testl  %edi, %edi
24481   // movl   $0, %eax
24482   // cmovgl %edi, %eax
24483   // =>
24484   // xorl   %eax, %eax
24485   // subl   %esi, $edi
24486   // cmovsl %eax, %edi
24487   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24488       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24489       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24490     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24491     switch (CC) {
24492     default: break;
24493     case ISD::SETLT:
24494     case ISD::SETGT: {
24495       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24496       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24497                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
24498       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24499     }
24500     }
24501   }
24502
24503   // Early exit check
24504   if (!TLI.isTypeLegal(VT))
24505     return SDValue();
24506
24507   // Match VSELECTs into subs with unsigned saturation.
24508   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24509       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24510       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24511        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24512     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24513
24514     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24515     // left side invert the predicate to simplify logic below.
24516     SDValue Other;
24517     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24518       Other = RHS;
24519       CC = ISD::getSetCCInverse(CC, true);
24520     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24521       Other = LHS;
24522     }
24523
24524     if (Other.getNode() && Other->getNumOperands() == 2 &&
24525         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24526       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24527       SDValue CondRHS = Cond->getOperand(1);
24528
24529       // Look for a general sub with unsigned saturation first.
24530       // x >= y ? x-y : 0 --> subus x, y
24531       // x >  y ? x-y : 0 --> subus x, y
24532       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24533           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24534         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24535
24536       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24537         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24538           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24539             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24540               // If the RHS is a constant we have to reverse the const
24541               // canonicalization.
24542               // x > C-1 ? x+-C : 0 --> subus x, C
24543               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24544                   CondRHSConst->getAPIntValue() ==
24545                       (-OpRHSConst->getAPIntValue() - 1))
24546                 return DAG.getNode(
24547                     X86ISD::SUBUS, DL, VT, OpLHS,
24548                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24549
24550           // Another special case: If C was a sign bit, the sub has been
24551           // canonicalized into a xor.
24552           // FIXME: Would it be better to use computeKnownBits to determine
24553           //        whether it's safe to decanonicalize the xor?
24554           // x s< 0 ? x^C : 0 --> subus x, C
24555           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24556               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24557               OpRHSConst->getAPIntValue().isSignBit())
24558             // Note that we have to rebuild the RHS constant here to ensure we
24559             // don't rely on particular values of undef lanes.
24560             return DAG.getNode(
24561                 X86ISD::SUBUS, DL, VT, OpLHS,
24562                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24563         }
24564     }
24565   }
24566
24567   // Simplify vector selection if condition value type matches vselect
24568   // operand type
24569   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24570     assert(Cond.getValueType().isVector() &&
24571            "vector select expects a vector selector!");
24572
24573     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24574     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24575
24576     // Try invert the condition if true value is not all 1s and false value
24577     // is not all 0s.
24578     if (!TValIsAllOnes && !FValIsAllZeros &&
24579         // Check if the selector will be produced by CMPP*/PCMP*
24580         Cond.getOpcode() == ISD::SETCC &&
24581         // Check if SETCC has already been promoted
24582         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24583             CondVT) {
24584       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24585       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24586
24587       if (TValIsAllZeros || FValIsAllOnes) {
24588         SDValue CC = Cond.getOperand(2);
24589         ISD::CondCode NewCC =
24590           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24591                                Cond.getOperand(0).getValueType().isInteger());
24592         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24593         std::swap(LHS, RHS);
24594         TValIsAllOnes = FValIsAllOnes;
24595         FValIsAllZeros = TValIsAllZeros;
24596       }
24597     }
24598
24599     if (TValIsAllOnes || FValIsAllZeros) {
24600       SDValue Ret;
24601
24602       if (TValIsAllOnes && FValIsAllZeros)
24603         Ret = Cond;
24604       else if (TValIsAllOnes)
24605         Ret =
24606             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24607       else if (FValIsAllZeros)
24608         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24609                           DAG.getBitcast(CondVT, LHS));
24610
24611       return DAG.getBitcast(VT, Ret);
24612     }
24613   }
24614
24615   // We should generate an X86ISD::BLENDI from a vselect if its argument
24616   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24617   // constants. This specific pattern gets generated when we split a
24618   // selector for a 512 bit vector in a machine without AVX512 (but with
24619   // 256-bit vectors), during legalization:
24620   //
24621   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24622   //
24623   // Iff we find this pattern and the build_vectors are built from
24624   // constants, we translate the vselect into a shuffle_vector that we
24625   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24626   if ((N->getOpcode() == ISD::VSELECT ||
24627        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24628       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24629     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24630     if (Shuffle.getNode())
24631       return Shuffle;
24632   }
24633
24634   // If this is a *dynamic* select (non-constant condition) and we can match
24635   // this node with one of the variable blend instructions, restructure the
24636   // condition so that the blends can use the high bit of each element and use
24637   // SimplifyDemandedBits to simplify the condition operand.
24638   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24639       !DCI.isBeforeLegalize() &&
24640       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24641     unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24642
24643     // Don't optimize vector selects that map to mask-registers.
24644     if (BitWidth == 1)
24645       return SDValue();
24646
24647     // We can only handle the cases where VSELECT is directly legal on the
24648     // subtarget. We custom lower VSELECT nodes with constant conditions and
24649     // this makes it hard to see whether a dynamic VSELECT will correctly
24650     // lower, so we both check the operation's status and explicitly handle the
24651     // cases where a *dynamic* blend will fail even though a constant-condition
24652     // blend could be custom lowered.
24653     // FIXME: We should find a better way to handle this class of problems.
24654     // Potentially, we should combine constant-condition vselect nodes
24655     // pre-legalization into shuffles and not mark as many types as custom
24656     // lowered.
24657     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24658       return SDValue();
24659     // FIXME: We don't support i16-element blends currently. We could and
24660     // should support them by making *all* the bits in the condition be set
24661     // rather than just the high bit and using an i8-element blend.
24662     if (VT.getVectorElementType() == MVT::i16)
24663       return SDValue();
24664     // Dynamic blending was only available from SSE4.1 onward.
24665     if (VT.is128BitVector() && !Subtarget->hasSSE41())
24666       return SDValue();
24667     // Byte blends are only available in AVX2
24668     if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24669       return SDValue();
24670
24671     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24672     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24673
24674     APInt KnownZero, KnownOne;
24675     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24676                                           DCI.isBeforeLegalizeOps());
24677     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24678         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24679                                  TLO)) {
24680       // If we changed the computation somewhere in the DAG, this change
24681       // will affect all users of Cond.
24682       // Make sure it is fine and update all the nodes so that we do not
24683       // use the generic VSELECT anymore. Otherwise, we may perform
24684       // wrong optimizations as we messed up with the actual expectation
24685       // for the vector boolean values.
24686       if (Cond != TLO.Old) {
24687         // Check all uses of that condition operand to check whether it will be
24688         // consumed by non-BLEND instructions, which may depend on all bits are
24689         // set properly.
24690         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24691              I != E; ++I)
24692           if (I->getOpcode() != ISD::VSELECT)
24693             // TODO: Add other opcodes eventually lowered into BLEND.
24694             return SDValue();
24695
24696         // Update all the users of the condition, before committing the change,
24697         // so that the VSELECT optimizations that expect the correct vector
24698         // boolean value will not be triggered.
24699         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24700              I != E; ++I)
24701           DAG.ReplaceAllUsesOfValueWith(
24702               SDValue(*I, 0),
24703               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24704                           Cond, I->getOperand(1), I->getOperand(2)));
24705         DCI.CommitTargetLoweringOpt(TLO);
24706         return SDValue();
24707       }
24708       // At this point, only Cond is changed. Change the condition
24709       // just for N to keep the opportunity to optimize all other
24710       // users their own way.
24711       DAG.ReplaceAllUsesOfValueWith(
24712           SDValue(N, 0),
24713           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24714                       TLO.New, N->getOperand(1), N->getOperand(2)));
24715       return SDValue();
24716     }
24717   }
24718
24719   return SDValue();
24720 }
24721
24722 // Check whether a boolean test is testing a boolean value generated by
24723 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24724 // code.
24725 //
24726 // Simplify the following patterns:
24727 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24728 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24729 // to (Op EFLAGS Cond)
24730 //
24731 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24732 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24733 // to (Op EFLAGS !Cond)
24734 //
24735 // where Op could be BRCOND or CMOV.
24736 //
24737 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24738   // Quit if not CMP and SUB with its value result used.
24739   if (Cmp.getOpcode() != X86ISD::CMP &&
24740       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24741       return SDValue();
24742
24743   // Quit if not used as a boolean value.
24744   if (CC != X86::COND_E && CC != X86::COND_NE)
24745     return SDValue();
24746
24747   // Check CMP operands. One of them should be 0 or 1 and the other should be
24748   // an SetCC or extended from it.
24749   SDValue Op1 = Cmp.getOperand(0);
24750   SDValue Op2 = Cmp.getOperand(1);
24751
24752   SDValue SetCC;
24753   const ConstantSDNode* C = nullptr;
24754   bool needOppositeCond = (CC == X86::COND_E);
24755   bool checkAgainstTrue = false; // Is it a comparison against 1?
24756
24757   if ((C = dyn_cast<ConstantSDNode>(Op1)))
24758     SetCC = Op2;
24759   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24760     SetCC = Op1;
24761   else // Quit if all operands are not constants.
24762     return SDValue();
24763
24764   if (C->getZExtValue() == 1) {
24765     needOppositeCond = !needOppositeCond;
24766     checkAgainstTrue = true;
24767   } else if (C->getZExtValue() != 0)
24768     // Quit if the constant is neither 0 or 1.
24769     return SDValue();
24770
24771   bool truncatedToBoolWithAnd = false;
24772   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24773   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24774          SetCC.getOpcode() == ISD::TRUNCATE ||
24775          SetCC.getOpcode() == ISD::AND) {
24776     if (SetCC.getOpcode() == ISD::AND) {
24777       int OpIdx = -1;
24778       if (isOneConstant(SetCC.getOperand(0)))
24779         OpIdx = 1;
24780       if (isOneConstant(SetCC.getOperand(1)))
24781         OpIdx = 0;
24782       if (OpIdx == -1)
24783         break;
24784       SetCC = SetCC.getOperand(OpIdx);
24785       truncatedToBoolWithAnd = true;
24786     } else
24787       SetCC = SetCC.getOperand(0);
24788   }
24789
24790   switch (SetCC.getOpcode()) {
24791   case X86ISD::SETCC_CARRY:
24792     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24793     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24794     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24795     // truncated to i1 using 'and'.
24796     if (checkAgainstTrue && !truncatedToBoolWithAnd)
24797       break;
24798     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24799            "Invalid use of SETCC_CARRY!");
24800     // FALL THROUGH
24801   case X86ISD::SETCC:
24802     // Set the condition code or opposite one if necessary.
24803     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24804     if (needOppositeCond)
24805       CC = X86::GetOppositeBranchCondition(CC);
24806     return SetCC.getOperand(1);
24807   case X86ISD::CMOV: {
24808     // Check whether false/true value has canonical one, i.e. 0 or 1.
24809     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24810     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24811     // Quit if true value is not a constant.
24812     if (!TVal)
24813       return SDValue();
24814     // Quit if false value is not a constant.
24815     if (!FVal) {
24816       SDValue Op = SetCC.getOperand(0);
24817       // Skip 'zext' or 'trunc' node.
24818       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24819           Op.getOpcode() == ISD::TRUNCATE)
24820         Op = Op.getOperand(0);
24821       // A special case for rdrand/rdseed, where 0 is set if false cond is
24822       // found.
24823       if ((Op.getOpcode() != X86ISD::RDRAND &&
24824            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24825         return SDValue();
24826     }
24827     // Quit if false value is not the constant 0 or 1.
24828     bool FValIsFalse = true;
24829     if (FVal && FVal->getZExtValue() != 0) {
24830       if (FVal->getZExtValue() != 1)
24831         return SDValue();
24832       // If FVal is 1, opposite cond is needed.
24833       needOppositeCond = !needOppositeCond;
24834       FValIsFalse = false;
24835     }
24836     // Quit if TVal is not the constant opposite of FVal.
24837     if (FValIsFalse && TVal->getZExtValue() != 1)
24838       return SDValue();
24839     if (!FValIsFalse && TVal->getZExtValue() != 0)
24840       return SDValue();
24841     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24842     if (needOppositeCond)
24843       CC = X86::GetOppositeBranchCondition(CC);
24844     return SetCC.getOperand(3);
24845   }
24846   }
24847
24848   return SDValue();
24849 }
24850
24851 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24852 /// Match:
24853 ///   (X86or (X86setcc) (X86setcc))
24854 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24855 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24856                                            X86::CondCode &CC1, SDValue &Flags,
24857                                            bool &isAnd) {
24858   if (Cond->getOpcode() == X86ISD::CMP) {
24859     if (!isNullConstant(Cond->getOperand(1)))
24860       return false;
24861
24862     Cond = Cond->getOperand(0);
24863   }
24864
24865   isAnd = false;
24866
24867   SDValue SetCC0, SetCC1;
24868   switch (Cond->getOpcode()) {
24869   default: return false;
24870   case ISD::AND:
24871   case X86ISD::AND:
24872     isAnd = true;
24873     // fallthru
24874   case ISD::OR:
24875   case X86ISD::OR:
24876     SetCC0 = Cond->getOperand(0);
24877     SetCC1 = Cond->getOperand(1);
24878     break;
24879   };
24880
24881   // Make sure we have SETCC nodes, using the same flags value.
24882   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24883       SetCC1.getOpcode() != X86ISD::SETCC ||
24884       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24885     return false;
24886
24887   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24888   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24889   Flags = SetCC0->getOperand(1);
24890   return true;
24891 }
24892
24893 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24894 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24895                                   TargetLowering::DAGCombinerInfo &DCI,
24896                                   const X86Subtarget *Subtarget) {
24897   SDLoc DL(N);
24898
24899   // If the flag operand isn't dead, don't touch this CMOV.
24900   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24901     return SDValue();
24902
24903   SDValue FalseOp = N->getOperand(0);
24904   SDValue TrueOp = N->getOperand(1);
24905   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24906   SDValue Cond = N->getOperand(3);
24907
24908   if (CC == X86::COND_E || CC == X86::COND_NE) {
24909     switch (Cond.getOpcode()) {
24910     default: break;
24911     case X86ISD::BSR:
24912     case X86ISD::BSF:
24913       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24914       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24915         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24916     }
24917   }
24918
24919   SDValue Flags;
24920
24921   Flags = checkBoolTestSetCCCombine(Cond, CC);
24922   if (Flags.getNode() &&
24923       // Extra check as FCMOV only supports a subset of X86 cond.
24924       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24925     SDValue Ops[] = { FalseOp, TrueOp,
24926                       DAG.getConstant(CC, DL, MVT::i8), Flags };
24927     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24928   }
24929
24930   // If this is a select between two integer constants, try to do some
24931   // optimizations.  Note that the operands are ordered the opposite of SELECT
24932   // operands.
24933   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24934     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24935       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24936       // larger than FalseC (the false value).
24937       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24938         CC = X86::GetOppositeBranchCondition(CC);
24939         std::swap(TrueC, FalseC);
24940         std::swap(TrueOp, FalseOp);
24941       }
24942
24943       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24944       // This is efficient for any integer data type (including i8/i16) and
24945       // shift amount.
24946       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24947         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24948                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24949
24950         // Zero extend the condition if needed.
24951         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24952
24953         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24954         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24955                            DAG.getConstant(ShAmt, DL, MVT::i8));
24956         if (N->getNumValues() == 2)  // Dead flag value?
24957           return DCI.CombineTo(N, Cond, SDValue());
24958         return Cond;
24959       }
24960
24961       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
24962       // for any integer data type, including i8/i16.
24963       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24964         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24965                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24966
24967         // Zero extend the condition if needed.
24968         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24969                            FalseC->getValueType(0), Cond);
24970         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24971                            SDValue(FalseC, 0));
24972
24973         if (N->getNumValues() == 2)  // Dead flag value?
24974           return DCI.CombineTo(N, Cond, SDValue());
24975         return Cond;
24976       }
24977
24978       // Optimize cases that will turn into an LEA instruction.  This requires
24979       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24980       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24981         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24982         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24983
24984         bool isFastMultiplier = false;
24985         if (Diff < 10) {
24986           switch ((unsigned char)Diff) {
24987           default: break;
24988           case 1:  // result = add base, cond
24989           case 2:  // result = lea base(    , cond*2)
24990           case 3:  // result = lea base(cond, cond*2)
24991           case 4:  // result = lea base(    , cond*4)
24992           case 5:  // result = lea base(cond, cond*4)
24993           case 8:  // result = lea base(    , cond*8)
24994           case 9:  // result = lea base(cond, cond*8)
24995             isFastMultiplier = true;
24996             break;
24997           }
24998         }
24999
25000         if (isFastMultiplier) {
25001           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
25002           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25003                              DAG.getConstant(CC, DL, MVT::i8), Cond);
25004           // Zero extend the condition if needed.
25005           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
25006                              Cond);
25007           // Scale the condition by the difference.
25008           if (Diff != 1)
25009             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
25010                                DAG.getConstant(Diff, DL, Cond.getValueType()));
25011
25012           // Add the base if non-zero.
25013           if (FalseC->getAPIntValue() != 0)
25014             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25015                                SDValue(FalseC, 0));
25016           if (N->getNumValues() == 2)  // Dead flag value?
25017             return DCI.CombineTo(N, Cond, SDValue());
25018           return Cond;
25019         }
25020       }
25021     }
25022   }
25023
25024   // Handle these cases:
25025   //   (select (x != c), e, c) -> select (x != c), e, x),
25026   //   (select (x == c), c, e) -> select (x == c), x, e)
25027   // where the c is an integer constant, and the "select" is the combination
25028   // of CMOV and CMP.
25029   //
25030   // The rationale for this change is that the conditional-move from a constant
25031   // needs two instructions, however, conditional-move from a register needs
25032   // only one instruction.
25033   //
25034   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
25035   //  some instruction-combining opportunities. This opt needs to be
25036   //  postponed as late as possible.
25037   //
25038   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
25039     // the DCI.xxxx conditions are provided to postpone the optimization as
25040     // late as possible.
25041
25042     ConstantSDNode *CmpAgainst = nullptr;
25043     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
25044         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
25045         !isa<ConstantSDNode>(Cond.getOperand(0))) {
25046
25047       if (CC == X86::COND_NE &&
25048           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
25049         CC = X86::GetOppositeBranchCondition(CC);
25050         std::swap(TrueOp, FalseOp);
25051       }
25052
25053       if (CC == X86::COND_E &&
25054           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
25055         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
25056                           DAG.getConstant(CC, DL, MVT::i8), Cond };
25057         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
25058       }
25059     }
25060   }
25061
25062   // Fold and/or of setcc's to double CMOV:
25063   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
25064   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
25065   //
25066   // This combine lets us generate:
25067   //   cmovcc1 (jcc1 if we don't have CMOV)
25068   //   cmovcc2 (same)
25069   // instead of:
25070   //   setcc1
25071   //   setcc2
25072   //   and/or
25073   //   cmovne (jne if we don't have CMOV)
25074   // When we can't use the CMOV instruction, it might increase branch
25075   // mispredicts.
25076   // When we can use CMOV, or when there is no mispredict, this improves
25077   // throughput and reduces register pressure.
25078   //
25079   if (CC == X86::COND_NE) {
25080     SDValue Flags;
25081     X86::CondCode CC0, CC1;
25082     bool isAndSetCC;
25083     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
25084       if (isAndSetCC) {
25085         std::swap(FalseOp, TrueOp);
25086         CC0 = X86::GetOppositeBranchCondition(CC0);
25087         CC1 = X86::GetOppositeBranchCondition(CC1);
25088       }
25089
25090       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
25091         Flags};
25092       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
25093       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
25094       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25095       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
25096       return CMOV;
25097     }
25098   }
25099
25100   return SDValue();
25101 }
25102
25103 /// PerformMulCombine - Optimize a single multiply with constant into two
25104 /// in order to implement it with two cheaper instructions, e.g.
25105 /// LEA + SHL, LEA + LEA.
25106 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
25107                                  TargetLowering::DAGCombinerInfo &DCI) {
25108   // An imul is usually smaller than the alternative sequence.
25109   if (DAG.getMachineFunction().getFunction()->optForMinSize())
25110     return SDValue();
25111
25112   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
25113     return SDValue();
25114
25115   EVT VT = N->getValueType(0);
25116   if (VT != MVT::i64 && VT != MVT::i32)
25117     return SDValue();
25118
25119   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
25120   if (!C)
25121     return SDValue();
25122   uint64_t MulAmt = C->getZExtValue();
25123   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
25124     return SDValue();
25125
25126   uint64_t MulAmt1 = 0;
25127   uint64_t MulAmt2 = 0;
25128   if ((MulAmt % 9) == 0) {
25129     MulAmt1 = 9;
25130     MulAmt2 = MulAmt / 9;
25131   } else if ((MulAmt % 5) == 0) {
25132     MulAmt1 = 5;
25133     MulAmt2 = MulAmt / 5;
25134   } else if ((MulAmt % 3) == 0) {
25135     MulAmt1 = 3;
25136     MulAmt2 = MulAmt / 3;
25137   }
25138
25139   SDLoc DL(N);
25140   SDValue NewMul;
25141   if (MulAmt2 &&
25142       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
25143
25144     if (isPowerOf2_64(MulAmt2) &&
25145         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
25146       // If second multiplifer is pow2, issue it first. We want the multiply by
25147       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
25148       // is an add.
25149       std::swap(MulAmt1, MulAmt2);
25150
25151     if (isPowerOf2_64(MulAmt1))
25152       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25153                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
25154     else
25155       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
25156                            DAG.getConstant(MulAmt1, DL, VT));
25157
25158     if (isPowerOf2_64(MulAmt2))
25159       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
25160                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
25161     else
25162       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
25163                            DAG.getConstant(MulAmt2, DL, VT));
25164   }
25165
25166   if (!NewMul) {
25167     assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
25168            && "Both cases that could cause potential overflows should have "
25169               "already been handled.");
25170     if (isPowerOf2_64(MulAmt - 1))
25171       // (mul x, 2^N + 1) => (add (shl x, N), x)
25172       NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
25173                                 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25174                                 DAG.getConstant(Log2_64(MulAmt - 1), DL,
25175                                 MVT::i8)));
25176
25177     else if (isPowerOf2_64(MulAmt + 1))
25178       // (mul x, 2^N - 1) => (sub (shl x, N), x)
25179       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
25180                                 N->getOperand(0),
25181                                 DAG.getConstant(Log2_64(MulAmt + 1),
25182                                 DL, MVT::i8)), N->getOperand(0));
25183   }
25184
25185   if (NewMul)
25186     // Do not add new nodes to DAG combiner worklist.
25187     DCI.CombineTo(N, NewMul, false);
25188
25189   return SDValue();
25190 }
25191
25192 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
25193   SDValue N0 = N->getOperand(0);
25194   SDValue N1 = N->getOperand(1);
25195   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
25196   EVT VT = N0.getValueType();
25197
25198   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
25199   // since the result of setcc_c is all zero's or all ones.
25200   if (VT.isInteger() && !VT.isVector() &&
25201       N1C && N0.getOpcode() == ISD::AND &&
25202       N0.getOperand(1).getOpcode() == ISD::Constant) {
25203     SDValue N00 = N0.getOperand(0);
25204     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
25205     APInt ShAmt = N1C->getAPIntValue();
25206     Mask = Mask.shl(ShAmt);
25207     bool MaskOK = false;
25208     // We can handle cases concerning bit-widening nodes containing setcc_c if
25209     // we carefully interrogate the mask to make sure we are semantics
25210     // preserving.
25211     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
25212     // of the underlying setcc_c operation if the setcc_c was zero extended.
25213     // Consider the following example:
25214     //   zext(setcc_c)                 -> i32 0x0000FFFF
25215     //   c1                            -> i32 0x0000FFFF
25216     //   c2                            -> i32 0x00000001
25217     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
25218     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
25219     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25220       MaskOK = true;
25221     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
25222                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25223       MaskOK = true;
25224     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
25225                 N00.getOpcode() == ISD::ANY_EXTEND) &&
25226                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25227       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
25228     }
25229     if (MaskOK && Mask != 0) {
25230       SDLoc DL(N);
25231       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
25232     }
25233   }
25234
25235   // Hardware support for vector shifts is sparse which makes us scalarize the
25236   // vector operations in many cases. Also, on sandybridge ADD is faster than
25237   // shl.
25238   // (shl V, 1) -> add V,V
25239   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
25240     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
25241       assert(N0.getValueType().isVector() && "Invalid vector shift type");
25242       // We shift all of the values by one. In many cases we do not have
25243       // hardware support for this operation. This is better expressed as an ADD
25244       // of two values.
25245       if (N1SplatC->getAPIntValue() == 1)
25246         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
25247     }
25248
25249   return SDValue();
25250 }
25251
25252 static SDValue PerformSRACombine(SDNode *N, SelectionDAG &DAG) {
25253   SDValue N0 = N->getOperand(0);
25254   SDValue N1 = N->getOperand(1);
25255   EVT VT = N0.getValueType();
25256   unsigned Size = VT.getSizeInBits();
25257
25258   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
25259   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
25260   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
25261   // depending on sign of (SarConst - [56,48,32,24,16])
25262
25263   // sexts in X86 are MOVs. The MOVs have the same code size
25264   // as above SHIFTs (only SHIFT on 1 has lower code size).
25265   // However the MOVs have 2 advantages to a SHIFT:
25266   // 1. MOVs can write to a register that differs from source
25267   // 2. MOVs accept memory operands
25268
25269   if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
25270       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
25271       N0.getOperand(1).getOpcode() != ISD::Constant)
25272     return SDValue();
25273
25274   SDValue N00 = N0.getOperand(0);
25275   SDValue N01 = N0.getOperand(1);
25276   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
25277   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
25278   EVT CVT = N1.getValueType();
25279
25280   if (SarConst.isNegative())
25281     return SDValue();
25282
25283   for (MVT SVT : MVT::integer_valuetypes()) {
25284     unsigned ShiftSize = SVT.getSizeInBits();
25285     // skipping types without corresponding sext/zext and
25286     // ShlConst that is not one of [56,48,32,24,16]
25287     if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
25288       continue;
25289     SDLoc DL(N);
25290     SDValue NN =
25291         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
25292     SarConst = SarConst - (Size - ShiftSize);
25293     if (SarConst == 0)
25294       return NN;
25295     else if (SarConst.isNegative())
25296       return DAG.getNode(ISD::SHL, DL, VT, NN,
25297                          DAG.getConstant(-SarConst, DL, CVT));
25298     else
25299       return DAG.getNode(ISD::SRA, DL, VT, NN,
25300                          DAG.getConstant(SarConst, DL, CVT));
25301   }
25302   return SDValue();
25303 }
25304
25305 /// \brief Returns a vector of 0s if the node in input is a vector logical
25306 /// shift by a constant amount which is known to be bigger than or equal
25307 /// to the vector element size in bits.
25308 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
25309                                       const X86Subtarget *Subtarget) {
25310   EVT VT = N->getValueType(0);
25311
25312   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
25313       (!Subtarget->hasInt256() ||
25314        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
25315     return SDValue();
25316
25317   SDValue Amt = N->getOperand(1);
25318   SDLoc DL(N);
25319   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
25320     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
25321       APInt ShiftAmt = AmtSplat->getAPIntValue();
25322       unsigned MaxAmount =
25323         VT.getSimpleVT().getVectorElementType().getSizeInBits();
25324
25325       // SSE2/AVX2 logical shifts always return a vector of 0s
25326       // if the shift amount is bigger than or equal to
25327       // the element size. The constant shift amount will be
25328       // encoded as a 8-bit immediate.
25329       if (ShiftAmt.trunc(8).uge(MaxAmount))
25330         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
25331     }
25332
25333   return SDValue();
25334 }
25335
25336 /// PerformShiftCombine - Combine shifts.
25337 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
25338                                    TargetLowering::DAGCombinerInfo &DCI,
25339                                    const X86Subtarget *Subtarget) {
25340   if (N->getOpcode() == ISD::SHL)
25341     if (SDValue V = PerformSHLCombine(N, DAG))
25342       return V;
25343
25344   if (N->getOpcode() == ISD::SRA)
25345     if (SDValue V = PerformSRACombine(N, DAG))
25346       return V;
25347
25348   // Try to fold this logical shift into a zero vector.
25349   if (N->getOpcode() != ISD::SRA)
25350     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
25351       return V;
25352
25353   return SDValue();
25354 }
25355
25356 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
25357 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
25358 // and friends.  Likewise for OR -> CMPNEQSS.
25359 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
25360                             TargetLowering::DAGCombinerInfo &DCI,
25361                             const X86Subtarget *Subtarget) {
25362   unsigned opcode;
25363
25364   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
25365   // we're requiring SSE2 for both.
25366   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
25367     SDValue N0 = N->getOperand(0);
25368     SDValue N1 = N->getOperand(1);
25369     SDValue CMP0 = N0->getOperand(1);
25370     SDValue CMP1 = N1->getOperand(1);
25371     SDLoc DL(N);
25372
25373     // The SETCCs should both refer to the same CMP.
25374     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
25375       return SDValue();
25376
25377     SDValue CMP00 = CMP0->getOperand(0);
25378     SDValue CMP01 = CMP0->getOperand(1);
25379     EVT     VT    = CMP00.getValueType();
25380
25381     if (VT == MVT::f32 || VT == MVT::f64) {
25382       bool ExpectingFlags = false;
25383       // Check for any users that want flags:
25384       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
25385            !ExpectingFlags && UI != UE; ++UI)
25386         switch (UI->getOpcode()) {
25387         default:
25388         case ISD::BR_CC:
25389         case ISD::BRCOND:
25390         case ISD::SELECT:
25391           ExpectingFlags = true;
25392           break;
25393         case ISD::CopyToReg:
25394         case ISD::SIGN_EXTEND:
25395         case ISD::ZERO_EXTEND:
25396         case ISD::ANY_EXTEND:
25397           break;
25398         }
25399
25400       if (!ExpectingFlags) {
25401         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
25402         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
25403
25404         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
25405           X86::CondCode tmp = cc0;
25406           cc0 = cc1;
25407           cc1 = tmp;
25408         }
25409
25410         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
25411             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
25412           // FIXME: need symbolic constants for these magic numbers.
25413           // See X86ATTInstPrinter.cpp:printSSECC().
25414           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
25415           if (Subtarget->hasAVX512()) {
25416             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
25417                                          CMP01,
25418                                          DAG.getConstant(x86cc, DL, MVT::i8));
25419             if (N->getValueType(0) != MVT::i1)
25420               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25421                                  FSetCC);
25422             return FSetCC;
25423           }
25424           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25425                                               CMP00.getValueType(), CMP00, CMP01,
25426                                               DAG.getConstant(x86cc, DL,
25427                                                               MVT::i8));
25428
25429           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25430           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25431
25432           if (is64BitFP && !Subtarget->is64Bit()) {
25433             // On a 32-bit target, we cannot bitcast the 64-bit float to a
25434             // 64-bit integer, since that's not a legal type. Since
25435             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25436             // bits, but can do this little dance to extract the lowest 32 bits
25437             // and work with those going forward.
25438             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25439                                            OnesOrZeroesF);
25440             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25441             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25442                                         Vector32, DAG.getIntPtrConstant(0, DL));
25443             IntVT = MVT::i32;
25444           }
25445
25446           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25447           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25448                                       DAG.getConstant(1, DL, IntVT));
25449           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25450                                               ANDed);
25451           return OneBitOfTruth;
25452         }
25453       }
25454     }
25455   }
25456   return SDValue();
25457 }
25458
25459 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25460 /// so it can be folded inside ANDNP.
25461 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25462   EVT VT = N->getValueType(0);
25463
25464   // Match direct AllOnes for 128 and 256-bit vectors
25465   if (ISD::isBuildVectorAllOnes(N))
25466     return true;
25467
25468   // Look through a bit convert.
25469   if (N->getOpcode() == ISD::BITCAST)
25470     N = N->getOperand(0).getNode();
25471
25472   // Sometimes the operand may come from a insert_subvector building a 256-bit
25473   // allones vector
25474   if (VT.is256BitVector() &&
25475       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25476     SDValue V1 = N->getOperand(0);
25477     SDValue V2 = N->getOperand(1);
25478
25479     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25480         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25481         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25482         ISD::isBuildVectorAllOnes(V2.getNode()))
25483       return true;
25484   }
25485
25486   return false;
25487 }
25488
25489 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25490 // register. In most cases we actually compare or select YMM-sized registers
25491 // and mixing the two types creates horrible code. This method optimizes
25492 // some of the transition sequences.
25493 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25494                                  TargetLowering::DAGCombinerInfo &DCI,
25495                                  const X86Subtarget *Subtarget) {
25496   EVT VT = N->getValueType(0);
25497   if (!VT.is256BitVector())
25498     return SDValue();
25499
25500   assert((N->getOpcode() == ISD::ANY_EXTEND ||
25501           N->getOpcode() == ISD::ZERO_EXTEND ||
25502           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25503
25504   SDValue Narrow = N->getOperand(0);
25505   EVT NarrowVT = Narrow->getValueType(0);
25506   if (!NarrowVT.is128BitVector())
25507     return SDValue();
25508
25509   if (Narrow->getOpcode() != ISD::XOR &&
25510       Narrow->getOpcode() != ISD::AND &&
25511       Narrow->getOpcode() != ISD::OR)
25512     return SDValue();
25513
25514   SDValue N0  = Narrow->getOperand(0);
25515   SDValue N1  = Narrow->getOperand(1);
25516   SDLoc DL(Narrow);
25517
25518   // The Left side has to be a trunc.
25519   if (N0.getOpcode() != ISD::TRUNCATE)
25520     return SDValue();
25521
25522   // The type of the truncated inputs.
25523   EVT WideVT = N0->getOperand(0)->getValueType(0);
25524   if (WideVT != VT)
25525     return SDValue();
25526
25527   // The right side has to be a 'trunc' or a constant vector.
25528   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25529   ConstantSDNode *RHSConstSplat = nullptr;
25530   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25531     RHSConstSplat = RHSBV->getConstantSplatNode();
25532   if (!RHSTrunc && !RHSConstSplat)
25533     return SDValue();
25534
25535   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25536
25537   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25538     return SDValue();
25539
25540   // Set N0 and N1 to hold the inputs to the new wide operation.
25541   N0 = N0->getOperand(0);
25542   if (RHSConstSplat) {
25543     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25544                      SDValue(RHSConstSplat, 0));
25545     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25546     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25547   } else if (RHSTrunc) {
25548     N1 = N1->getOperand(0);
25549   }
25550
25551   // Generate the wide operation.
25552   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25553   unsigned Opcode = N->getOpcode();
25554   switch (Opcode) {
25555   case ISD::ANY_EXTEND:
25556     return Op;
25557   case ISD::ZERO_EXTEND: {
25558     unsigned InBits = NarrowVT.getScalarSizeInBits();
25559     APInt Mask = APInt::getAllOnesValue(InBits);
25560     Mask = Mask.zext(VT.getScalarSizeInBits());
25561     return DAG.getNode(ISD::AND, DL, VT,
25562                        Op, DAG.getConstant(Mask, DL, VT));
25563   }
25564   case ISD::SIGN_EXTEND:
25565     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25566                        Op, DAG.getValueType(NarrowVT));
25567   default:
25568     llvm_unreachable("Unexpected opcode");
25569   }
25570 }
25571
25572 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25573                                  TargetLowering::DAGCombinerInfo &DCI,
25574                                  const X86Subtarget *Subtarget) {
25575   SDValue N0 = N->getOperand(0);
25576   SDValue N1 = N->getOperand(1);
25577   SDLoc DL(N);
25578
25579   // A vector zext_in_reg may be represented as a shuffle,
25580   // feeding into a bitcast (this represents anyext) feeding into
25581   // an and with a mask.
25582   // We'd like to try to combine that into a shuffle with zero
25583   // plus a bitcast, removing the and.
25584   if (N0.getOpcode() != ISD::BITCAST ||
25585       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25586     return SDValue();
25587
25588   // The other side of the AND should be a splat of 2^C, where C
25589   // is the number of bits in the source type.
25590   if (N1.getOpcode() == ISD::BITCAST)
25591     N1 = N1.getOperand(0);
25592   if (N1.getOpcode() != ISD::BUILD_VECTOR)
25593     return SDValue();
25594   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25595
25596   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25597   EVT SrcType = Shuffle->getValueType(0);
25598
25599   // We expect a single-source shuffle
25600   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25601     return SDValue();
25602
25603   unsigned SrcSize = SrcType.getScalarSizeInBits();
25604
25605   APInt SplatValue, SplatUndef;
25606   unsigned SplatBitSize;
25607   bool HasAnyUndefs;
25608   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25609                                 SplatBitSize, HasAnyUndefs))
25610     return SDValue();
25611
25612   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25613   // Make sure the splat matches the mask we expect
25614   if (SplatBitSize > ResSize ||
25615       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25616     return SDValue();
25617
25618   // Make sure the input and output size make sense
25619   if (SrcSize >= ResSize || ResSize % SrcSize)
25620     return SDValue();
25621
25622   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25623   // The number of u's between each two values depends on the ratio between
25624   // the source and dest type.
25625   unsigned ZextRatio = ResSize / SrcSize;
25626   bool IsZext = true;
25627   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25628     if (i % ZextRatio) {
25629       if (Shuffle->getMaskElt(i) > 0) {
25630         // Expected undef
25631         IsZext = false;
25632         break;
25633       }
25634     } else {
25635       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25636         // Expected element number
25637         IsZext = false;
25638         break;
25639       }
25640     }
25641   }
25642
25643   if (!IsZext)
25644     return SDValue();
25645
25646   // Ok, perform the transformation - replace the shuffle with
25647   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25648   // (instead of undef) where the k elements come from the zero vector.
25649   SmallVector<int, 8> Mask;
25650   unsigned NumElems = SrcType.getVectorNumElements();
25651   for (unsigned i = 0; i < NumElems; ++i)
25652     if (i % ZextRatio)
25653       Mask.push_back(NumElems);
25654     else
25655       Mask.push_back(i / ZextRatio);
25656
25657   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25658     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25659   return DAG.getBitcast(N0.getValueType(), NewShuffle);
25660 }
25661
25662 /// If both input operands of a logic op are being cast from floating point
25663 /// types, try to convert this into a floating point logic node to avoid
25664 /// unnecessary moves from SSE to integer registers.
25665 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25666                                         const X86Subtarget *Subtarget) {
25667   unsigned FPOpcode = ISD::DELETED_NODE;
25668   if (N->getOpcode() == ISD::AND)
25669     FPOpcode = X86ISD::FAND;
25670   else if (N->getOpcode() == ISD::OR)
25671     FPOpcode = X86ISD::FOR;
25672   else if (N->getOpcode() == ISD::XOR)
25673     FPOpcode = X86ISD::FXOR;
25674
25675   assert(FPOpcode != ISD::DELETED_NODE &&
25676          "Unexpected input node for FP logic conversion");
25677
25678   EVT VT = N->getValueType(0);
25679   SDValue N0 = N->getOperand(0);
25680   SDValue N1 = N->getOperand(1);
25681   SDLoc DL(N);
25682   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25683       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25684        (Subtarget->hasSSE2() && VT == MVT::i64))) {
25685     SDValue N00 = N0.getOperand(0);
25686     SDValue N10 = N1.getOperand(0);
25687     EVT N00Type = N00.getValueType();
25688     EVT N10Type = N10.getValueType();
25689     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25690       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25691       return DAG.getBitcast(VT, FPLogic);
25692     }
25693   }
25694   return SDValue();
25695 }
25696
25697 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25698                                  TargetLowering::DAGCombinerInfo &DCI,
25699                                  const X86Subtarget *Subtarget) {
25700   if (DCI.isBeforeLegalizeOps())
25701     return SDValue();
25702
25703   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25704     return Zext;
25705
25706   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25707     return R;
25708
25709   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25710     return FPLogic;
25711
25712   EVT VT = N->getValueType(0);
25713   SDValue N0 = N->getOperand(0);
25714   SDValue N1 = N->getOperand(1);
25715   SDLoc DL(N);
25716
25717   // Create BEXTR instructions
25718   // BEXTR is ((X >> imm) & (2**size-1))
25719   if (VT == MVT::i32 || VT == MVT::i64) {
25720     // Check for BEXTR.
25721     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25722         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25723       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25724       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25725       if (MaskNode && ShiftNode) {
25726         uint64_t Mask = MaskNode->getZExtValue();
25727         uint64_t Shift = ShiftNode->getZExtValue();
25728         if (isMask_64(Mask)) {
25729           uint64_t MaskSize = countPopulation(Mask);
25730           if (Shift + MaskSize <= VT.getSizeInBits())
25731             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25732                                DAG.getConstant(Shift | (MaskSize << 8), DL,
25733                                                VT));
25734         }
25735       }
25736     } // BEXTR
25737
25738     return SDValue();
25739   }
25740
25741   // Want to form ANDNP nodes:
25742   // 1) In the hopes of then easily combining them with OR and AND nodes
25743   //    to form PBLEND/PSIGN.
25744   // 2) To match ANDN packed intrinsics
25745   if (VT != MVT::v2i64 && VT != MVT::v4i64)
25746     return SDValue();
25747
25748   // Check LHS for vnot
25749   if (N0.getOpcode() == ISD::XOR &&
25750       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25751       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25752     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25753
25754   // Check RHS for vnot
25755   if (N1.getOpcode() == ISD::XOR &&
25756       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25757       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25758     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25759
25760   return SDValue();
25761 }
25762
25763 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25764                                 TargetLowering::DAGCombinerInfo &DCI,
25765                                 const X86Subtarget *Subtarget) {
25766   if (DCI.isBeforeLegalizeOps())
25767     return SDValue();
25768
25769   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25770     return R;
25771
25772   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25773     return FPLogic;
25774
25775   SDValue N0 = N->getOperand(0);
25776   SDValue N1 = N->getOperand(1);
25777   EVT VT = N->getValueType(0);
25778
25779   // look for psign/blend
25780   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25781     if (!Subtarget->hasSSSE3() ||
25782         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25783       return SDValue();
25784
25785     // Canonicalize pandn to RHS
25786     if (N0.getOpcode() == X86ISD::ANDNP)
25787       std::swap(N0, N1);
25788     // or (and (m, y), (pandn m, x))
25789     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25790       SDValue Mask = N1.getOperand(0);
25791       SDValue X    = N1.getOperand(1);
25792       SDValue Y;
25793       if (N0.getOperand(0) == Mask)
25794         Y = N0.getOperand(1);
25795       if (N0.getOperand(1) == Mask)
25796         Y = N0.getOperand(0);
25797
25798       // Check to see if the mask appeared in both the AND and ANDNP and
25799       if (!Y.getNode())
25800         return SDValue();
25801
25802       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25803       // Look through mask bitcast.
25804       if (Mask.getOpcode() == ISD::BITCAST)
25805         Mask = Mask.getOperand(0);
25806       if (X.getOpcode() == ISD::BITCAST)
25807         X = X.getOperand(0);
25808       if (Y.getOpcode() == ISD::BITCAST)
25809         Y = Y.getOperand(0);
25810
25811       EVT MaskVT = Mask.getValueType();
25812
25813       // Validate that the Mask operand is a vector sra node.
25814       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25815       // there is no psrai.b
25816       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25817       unsigned SraAmt = ~0;
25818       if (Mask.getOpcode() == ISD::SRA) {
25819         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25820           if (auto *AmtConst = AmtBV->getConstantSplatNode())
25821             SraAmt = AmtConst->getZExtValue();
25822       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25823         SDValue SraC = Mask.getOperand(1);
25824         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
25825       }
25826       if ((SraAmt + 1) != EltBits)
25827         return SDValue();
25828
25829       SDLoc DL(N);
25830
25831       // Now we know we at least have a plendvb with the mask val.  See if
25832       // we can form a psignb/w/d.
25833       // psign = x.type == y.type == mask.type && y = sub(0, x);
25834       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25835           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25836           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25837         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25838                "Unsupported VT for PSIGN");
25839         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25840         return DAG.getBitcast(VT, Mask);
25841       }
25842       // PBLENDVB only available on SSE 4.1
25843       if (!Subtarget->hasSSE41())
25844         return SDValue();
25845
25846       MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25847
25848       X = DAG.getBitcast(BlendVT, X);
25849       Y = DAG.getBitcast(BlendVT, Y);
25850       Mask = DAG.getBitcast(BlendVT, Mask);
25851       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25852       return DAG.getBitcast(VT, Mask);
25853     }
25854   }
25855
25856   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25857     return SDValue();
25858
25859   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25860   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25861
25862   // SHLD/SHRD instructions have lower register pressure, but on some
25863   // platforms they have higher latency than the equivalent
25864   // series of shifts/or that would otherwise be generated.
25865   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25866   // have higher latencies and we are not optimizing for size.
25867   if (!OptForSize && Subtarget->isSHLDSlow())
25868     return SDValue();
25869
25870   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25871     std::swap(N0, N1);
25872   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25873     return SDValue();
25874   if (!N0.hasOneUse() || !N1.hasOneUse())
25875     return SDValue();
25876
25877   SDValue ShAmt0 = N0.getOperand(1);
25878   if (ShAmt0.getValueType() != MVT::i8)
25879     return SDValue();
25880   SDValue ShAmt1 = N1.getOperand(1);
25881   if (ShAmt1.getValueType() != MVT::i8)
25882     return SDValue();
25883   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25884     ShAmt0 = ShAmt0.getOperand(0);
25885   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25886     ShAmt1 = ShAmt1.getOperand(0);
25887
25888   SDLoc DL(N);
25889   unsigned Opc = X86ISD::SHLD;
25890   SDValue Op0 = N0.getOperand(0);
25891   SDValue Op1 = N1.getOperand(0);
25892   if (ShAmt0.getOpcode() == ISD::SUB) {
25893     Opc = X86ISD::SHRD;
25894     std::swap(Op0, Op1);
25895     std::swap(ShAmt0, ShAmt1);
25896   }
25897
25898   unsigned Bits = VT.getSizeInBits();
25899   if (ShAmt1.getOpcode() == ISD::SUB) {
25900     SDValue Sum = ShAmt1.getOperand(0);
25901     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25902       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25903       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25904         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25905       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25906         return DAG.getNode(Opc, DL, VT,
25907                            Op0, Op1,
25908                            DAG.getNode(ISD::TRUNCATE, DL,
25909                                        MVT::i8, ShAmt0));
25910     }
25911   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25912     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25913     if (ShAmt0C &&
25914         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25915       return DAG.getNode(Opc, DL, VT,
25916                          N0.getOperand(0), N1.getOperand(0),
25917                          DAG.getNode(ISD::TRUNCATE, DL,
25918                                        MVT::i8, ShAmt0));
25919   }
25920
25921   return SDValue();
25922 }
25923
25924 // Generate NEG and CMOV for integer abs.
25925 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25926   EVT VT = N->getValueType(0);
25927
25928   // Since X86 does not have CMOV for 8-bit integer, we don't convert
25929   // 8-bit integer abs to NEG and CMOV.
25930   if (VT.isInteger() && VT.getSizeInBits() == 8)
25931     return SDValue();
25932
25933   SDValue N0 = N->getOperand(0);
25934   SDValue N1 = N->getOperand(1);
25935   SDLoc DL(N);
25936
25937   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25938   // and change it to SUB and CMOV.
25939   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25940       N0.getOpcode() == ISD::ADD &&
25941       N0.getOperand(1) == N1 &&
25942       N1.getOpcode() == ISD::SRA &&
25943       N1.getOperand(0) == N0.getOperand(0))
25944     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25945       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25946         // Generate SUB & CMOV.
25947         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25948                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
25949
25950         SDValue Ops[] = { N0.getOperand(0), Neg,
25951                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25952                           SDValue(Neg.getNode(), 1) };
25953         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25954       }
25955   return SDValue();
25956 }
25957
25958 // Try to turn tests against the signbit in the form of:
25959 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25960 // into:
25961 //   SETGT(X, -1)
25962 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25963   // This is only worth doing if the output type is i8.
25964   if (N->getValueType(0) != MVT::i8)
25965     return SDValue();
25966
25967   SDValue N0 = N->getOperand(0);
25968   SDValue N1 = N->getOperand(1);
25969
25970   // We should be performing an xor against a truncated shift.
25971   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25972     return SDValue();
25973
25974   // Make sure we are performing an xor against one.
25975   if (!isOneConstant(N1))
25976     return SDValue();
25977
25978   // SetCC on x86 zero extends so only act on this if it's a logical shift.
25979   SDValue Shift = N0.getOperand(0);
25980   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25981     return SDValue();
25982
25983   // Make sure we are truncating from one of i16, i32 or i64.
25984   EVT ShiftTy = Shift.getValueType();
25985   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25986     return SDValue();
25987
25988   // Make sure the shift amount extracts the sign bit.
25989   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25990       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25991     return SDValue();
25992
25993   // Create a greater-than comparison against -1.
25994   // N.B. Using SETGE against 0 works but we want a canonical looking
25995   // comparison, using SETGT matches up with what TranslateX86CC.
25996   SDLoc DL(N);
25997   SDValue ShiftOp = Shift.getOperand(0);
25998   EVT ShiftOpTy = ShiftOp.getValueType();
25999   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
26000                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
26001   return Cond;
26002 }
26003
26004 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
26005                                  TargetLowering::DAGCombinerInfo &DCI,
26006                                  const X86Subtarget *Subtarget) {
26007   if (DCI.isBeforeLegalizeOps())
26008     return SDValue();
26009
26010   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
26011     return RV;
26012
26013   if (Subtarget->hasCMov())
26014     if (SDValue RV = performIntegerAbsCombine(N, DAG))
26015       return RV;
26016
26017   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
26018     return FPLogic;
26019
26020   return SDValue();
26021 }
26022
26023 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
26024 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
26025 /// X86ISD::AVG instruction.
26026 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
26027                                 const X86Subtarget *Subtarget, SDLoc DL) {
26028   if (!VT.isVector() || !VT.isSimple())
26029     return SDValue();
26030   EVT InVT = In.getValueType();
26031   unsigned NumElems = VT.getVectorNumElements();
26032
26033   EVT ScalarVT = VT.getVectorElementType();
26034   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
26035         isPowerOf2_32(NumElems)))
26036     return SDValue();
26037
26038   // InScalarVT is the intermediate type in AVG pattern and it should be greater
26039   // than the original input type (i8/i16).
26040   EVT InScalarVT = InVT.getVectorElementType();
26041   if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
26042     return SDValue();
26043
26044   if (Subtarget->hasAVX512()) {
26045     if (VT.getSizeInBits() > 512)
26046       return SDValue();
26047   } else if (Subtarget->hasAVX2()) {
26048     if (VT.getSizeInBits() > 256)
26049       return SDValue();
26050   } else {
26051     if (VT.getSizeInBits() > 128)
26052       return SDValue();
26053   }
26054
26055   // Detect the following pattern:
26056   //
26057   //   %1 = zext <N x i8> %a to <N x i32>
26058   //   %2 = zext <N x i8> %b to <N x i32>
26059   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
26060   //   %4 = add nuw nsw <N x i32> %3, %2
26061   //   %5 = lshr <N x i32> %N, <i32 1 x N>
26062   //   %6 = trunc <N x i32> %5 to <N x i8>
26063   //
26064   // In AVX512, the last instruction can also be a trunc store.
26065
26066   if (In.getOpcode() != ISD::SRL)
26067     return SDValue();
26068
26069   // A lambda checking the given SDValue is a constant vector and each element
26070   // is in the range [Min, Max].
26071   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
26072     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
26073     if (!BV || !BV->isConstant())
26074       return false;
26075     for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
26076       ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
26077       if (!C)
26078         return false;
26079       uint64_t Val = C->getZExtValue();
26080       if (Val < Min || Val > Max)
26081         return false;
26082     }
26083     return true;
26084   };
26085
26086   // Check if each element of the vector is left-shifted by one.
26087   auto LHS = In.getOperand(0);
26088   auto RHS = In.getOperand(1);
26089   if (!IsConstVectorInRange(RHS, 1, 1))
26090     return SDValue();
26091   if (LHS.getOpcode() != ISD::ADD)
26092     return SDValue();
26093
26094   // Detect a pattern of a + b + 1 where the order doesn't matter.
26095   SDValue Operands[3];
26096   Operands[0] = LHS.getOperand(0);
26097   Operands[1] = LHS.getOperand(1);
26098
26099   // Take care of the case when one of the operands is a constant vector whose
26100   // element is in the range [1, 256].
26101   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
26102       Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
26103       Operands[0].getOperand(0).getValueType() == VT) {
26104     // The pattern is detected. Subtract one from the constant vector, then
26105     // demote it and emit X86ISD::AVG instruction.
26106     SDValue One = DAG.getConstant(1, DL, InScalarVT);
26107     SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
26108                                SmallVector<SDValue, 8>(NumElems, One));
26109     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
26110     Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
26111     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26112                        Operands[1]);
26113   }
26114
26115   if (Operands[0].getOpcode() == ISD::ADD)
26116     std::swap(Operands[0], Operands[1]);
26117   else if (Operands[1].getOpcode() != ISD::ADD)
26118     return SDValue();
26119   Operands[2] = Operands[1].getOperand(0);
26120   Operands[1] = Operands[1].getOperand(1);
26121
26122   // Now we have three operands of two additions. Check that one of them is a
26123   // constant vector with ones, and the other two are promoted from i8/i16.
26124   for (int i = 0; i < 3; ++i) {
26125     if (!IsConstVectorInRange(Operands[i], 1, 1))
26126       continue;
26127     std::swap(Operands[i], Operands[2]);
26128
26129     // Check if Operands[0] and Operands[1] are results of type promotion.
26130     for (int j = 0; j < 2; ++j)
26131       if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
26132           Operands[j].getOperand(0).getValueType() != VT)
26133         return SDValue();
26134
26135     // The pattern is detected, emit X86ISD::AVG instruction.
26136     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26137                        Operands[1].getOperand(0));
26138   }
26139
26140   return SDValue();
26141 }
26142
26143 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
26144 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
26145                                   TargetLowering::DAGCombinerInfo &DCI,
26146                                   const X86Subtarget *Subtarget) {
26147   LoadSDNode *Ld = cast<LoadSDNode>(N);
26148   EVT RegVT = Ld->getValueType(0);
26149   EVT MemVT = Ld->getMemoryVT();
26150   SDLoc dl(Ld);
26151   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26152
26153   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
26154   // into two 16-byte operations.
26155   ISD::LoadExtType Ext = Ld->getExtensionType();
26156   bool Fast;
26157   unsigned AddressSpace = Ld->getAddressSpace();
26158   unsigned Alignment = Ld->getAlignment();
26159   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
26160       Ext == ISD::NON_EXTLOAD &&
26161       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
26162                              AddressSpace, Alignment, &Fast) && !Fast) {
26163     unsigned NumElems = RegVT.getVectorNumElements();
26164     if (NumElems < 2)
26165       return SDValue();
26166
26167     SDValue Ptr = Ld->getBasePtr();
26168     SDValue Increment =
26169         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26170
26171     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
26172                                   NumElems/2);
26173     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26174                                 Ld->getPointerInfo(), Ld->isVolatile(),
26175                                 Ld->isNonTemporal(), Ld->isInvariant(),
26176                                 Alignment);
26177     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26178     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26179                                 Ld->getPointerInfo(), Ld->isVolatile(),
26180                                 Ld->isNonTemporal(), Ld->isInvariant(),
26181                                 std::min(16U, Alignment));
26182     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
26183                              Load1.getValue(1),
26184                              Load2.getValue(1));
26185
26186     SDValue NewVec = DAG.getUNDEF(RegVT);
26187     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
26188     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
26189     return DCI.CombineTo(N, NewVec, TF, true);
26190   }
26191
26192   return SDValue();
26193 }
26194
26195 /// PerformMLOADCombine - Resolve extending loads
26196 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
26197                                    TargetLowering::DAGCombinerInfo &DCI,
26198                                    const X86Subtarget *Subtarget) {
26199   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
26200   if (Mld->getExtensionType() != ISD::SEXTLOAD)
26201     return SDValue();
26202
26203   EVT VT = Mld->getValueType(0);
26204   unsigned NumElems = VT.getVectorNumElements();
26205   EVT LdVT = Mld->getMemoryVT();
26206   SDLoc dl(Mld);
26207
26208   assert(LdVT != VT && "Cannot extend to the same type");
26209   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
26210   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
26211   // From, To sizes and ElemCount must be pow of two
26212   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26213     "Unexpected size for extending masked load");
26214
26215   unsigned SizeRatio  = ToSz / FromSz;
26216   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
26217
26218   // Create a type on which we perform the shuffle
26219   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26220           LdVT.getScalarType(), NumElems*SizeRatio);
26221   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26222
26223   // Convert Src0 value
26224   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
26225   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
26226     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26227     for (unsigned i = 0; i != NumElems; ++i)
26228       ShuffleVec[i] = i * SizeRatio;
26229
26230     // Can't shuffle using an illegal type.
26231     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26232            "WideVecVT should be legal");
26233     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
26234                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
26235   }
26236   // Prepare the new mask
26237   SDValue NewMask;
26238   SDValue Mask = Mld->getMask();
26239   if (Mask.getValueType() == VT) {
26240     // Mask and original value have the same type
26241     NewMask = DAG.getBitcast(WideVecVT, Mask);
26242     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26243     for (unsigned i = 0; i != NumElems; ++i)
26244       ShuffleVec[i] = i * SizeRatio;
26245     for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
26246       ShuffleVec[i] = NumElems * SizeRatio;
26247     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26248                                    DAG.getConstant(0, dl, WideVecVT),
26249                                    &ShuffleVec[0]);
26250   }
26251   else {
26252     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26253     unsigned WidenNumElts = NumElems*SizeRatio;
26254     unsigned MaskNumElts = VT.getVectorNumElements();
26255     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26256                                      WidenNumElts);
26257
26258     unsigned NumConcat = WidenNumElts / MaskNumElts;
26259     SmallVector<SDValue, 16> Ops(NumConcat);
26260     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26261     Ops[0] = Mask;
26262     for (unsigned i = 1; i != NumConcat; ++i)
26263       Ops[i] = ZeroVal;
26264
26265     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26266   }
26267
26268   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
26269                                      Mld->getBasePtr(), NewMask, WideSrc0,
26270                                      Mld->getMemoryVT(), Mld->getMemOperand(),
26271                                      ISD::NON_EXTLOAD);
26272   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
26273   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
26274 }
26275 /// PerformMSTORECombine - Resolve truncating stores
26276 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
26277                                     const X86Subtarget *Subtarget) {
26278   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
26279   if (!Mst->isTruncatingStore())
26280     return SDValue();
26281
26282   EVT VT = Mst->getValue().getValueType();
26283   unsigned NumElems = VT.getVectorNumElements();
26284   EVT StVT = Mst->getMemoryVT();
26285   SDLoc dl(Mst);
26286
26287   assert(StVT != VT && "Cannot truncate to the same type");
26288   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26289   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26290
26291   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26292
26293   // The truncating store is legal in some cases. For example
26294   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26295   // are designated for truncate store.
26296   // In this case we don't need any further transformations.
26297   if (TLI.isTruncStoreLegal(VT, StVT))
26298     return SDValue();
26299
26300   // From, To sizes and ElemCount must be pow of two
26301   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26302     "Unexpected size for truncating masked store");
26303   // We are going to use the original vector elt for storing.
26304   // Accumulated smaller vector elements must be a multiple of the store size.
26305   assert (((NumElems * FromSz) % ToSz) == 0 &&
26306           "Unexpected ratio for truncating masked store");
26307
26308   unsigned SizeRatio  = FromSz / ToSz;
26309   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26310
26311   // Create a type on which we perform the shuffle
26312   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26313           StVT.getScalarType(), NumElems*SizeRatio);
26314
26315   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26316
26317   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
26318   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26319   for (unsigned i = 0; i != NumElems; ++i)
26320     ShuffleVec[i] = i * SizeRatio;
26321
26322   // Can't shuffle using an illegal type.
26323   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26324          "WideVecVT should be legal");
26325
26326   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26327                                               DAG.getUNDEF(WideVecVT),
26328                                               &ShuffleVec[0]);
26329
26330   SDValue NewMask;
26331   SDValue Mask = Mst->getMask();
26332   if (Mask.getValueType() == VT) {
26333     // Mask and original value have the same type
26334     NewMask = DAG.getBitcast(WideVecVT, Mask);
26335     for (unsigned i = 0; i != NumElems; ++i)
26336       ShuffleVec[i] = i * SizeRatio;
26337     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
26338       ShuffleVec[i] = NumElems*SizeRatio;
26339     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26340                                    DAG.getConstant(0, dl, WideVecVT),
26341                                    &ShuffleVec[0]);
26342   }
26343   else {
26344     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26345     unsigned WidenNumElts = NumElems*SizeRatio;
26346     unsigned MaskNumElts = VT.getVectorNumElements();
26347     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26348                                      WidenNumElts);
26349
26350     unsigned NumConcat = WidenNumElts / MaskNumElts;
26351     SmallVector<SDValue, 16> Ops(NumConcat);
26352     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26353     Ops[0] = Mask;
26354     for (unsigned i = 1; i != NumConcat; ++i)
26355       Ops[i] = ZeroVal;
26356
26357     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26358   }
26359
26360   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
26361                             Mst->getBasePtr(), NewMask, StVT,
26362                             Mst->getMemOperand(), false);
26363 }
26364 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
26365 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
26366                                    const X86Subtarget *Subtarget) {
26367   StoreSDNode *St = cast<StoreSDNode>(N);
26368   EVT VT = St->getValue().getValueType();
26369   EVT StVT = St->getMemoryVT();
26370   SDLoc dl(St);
26371   SDValue StoredVal = St->getOperand(1);
26372   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26373
26374   // If we are saving a concatenation of two XMM registers and 32-byte stores
26375   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
26376   bool Fast;
26377   unsigned AddressSpace = St->getAddressSpace();
26378   unsigned Alignment = St->getAlignment();
26379   if (VT.is256BitVector() && StVT == VT &&
26380       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
26381                              AddressSpace, Alignment, &Fast) && !Fast) {
26382     unsigned NumElems = VT.getVectorNumElements();
26383     if (NumElems < 2)
26384       return SDValue();
26385
26386     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
26387     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
26388
26389     SDValue Stride =
26390         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26391     SDValue Ptr0 = St->getBasePtr();
26392     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
26393
26394     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
26395                                 St->getPointerInfo(), St->isVolatile(),
26396                                 St->isNonTemporal(), Alignment);
26397     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
26398                                 St->getPointerInfo(), St->isVolatile(),
26399                                 St->isNonTemporal(),
26400                                 std::min(16U, Alignment));
26401     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
26402   }
26403
26404   // Optimize trunc store (of multiple scalars) to shuffle and store.
26405   // First, pack all of the elements in one place. Next, store to memory
26406   // in fewer chunks.
26407   if (St->isTruncatingStore() && VT.isVector()) {
26408     // Check if we can detect an AVG pattern from the truncation. If yes,
26409     // replace the trunc store by a normal store with the result of X86ISD::AVG
26410     // instruction.
26411     SDValue Avg =
26412         detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
26413     if (Avg.getNode())
26414       return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
26415                           St->getPointerInfo(), St->isVolatile(),
26416                           St->isNonTemporal(), St->getAlignment());
26417
26418     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26419     unsigned NumElems = VT.getVectorNumElements();
26420     assert(StVT != VT && "Cannot truncate to the same type");
26421     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26422     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26423
26424     // The truncating store is legal in some cases. For example
26425     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26426     // are designated for truncate store.
26427     // In this case we don't need any further transformations.
26428     if (TLI.isTruncStoreLegal(VT, StVT))
26429       return SDValue();
26430
26431     // From, To sizes and ElemCount must be pow of two
26432     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26433     // We are going to use the original vector elt for storing.
26434     // Accumulated smaller vector elements must be a multiple of the store size.
26435     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26436
26437     unsigned SizeRatio  = FromSz / ToSz;
26438
26439     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26440
26441     // Create a type on which we perform the shuffle
26442     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26443             StVT.getScalarType(), NumElems*SizeRatio);
26444
26445     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26446
26447     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26448     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26449     for (unsigned i = 0; i != NumElems; ++i)
26450       ShuffleVec[i] = i * SizeRatio;
26451
26452     // Can't shuffle using an illegal type.
26453     if (!TLI.isTypeLegal(WideVecVT))
26454       return SDValue();
26455
26456     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26457                                          DAG.getUNDEF(WideVecVT),
26458                                          &ShuffleVec[0]);
26459     // At this point all of the data is stored at the bottom of the
26460     // register. We now need to save it to mem.
26461
26462     // Find the largest store unit
26463     MVT StoreType = MVT::i8;
26464     for (MVT Tp : MVT::integer_valuetypes()) {
26465       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26466         StoreType = Tp;
26467     }
26468
26469     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26470     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26471         (64 <= NumElems * ToSz))
26472       StoreType = MVT::f64;
26473
26474     // Bitcast the original vector into a vector of store-size units
26475     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26476             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26477     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26478     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26479     SmallVector<SDValue, 8> Chains;
26480     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26481                                         TLI.getPointerTy(DAG.getDataLayout()));
26482     SDValue Ptr = St->getBasePtr();
26483
26484     // Perform one or more big stores into memory.
26485     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26486       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26487                                    StoreType, ShuffWide,
26488                                    DAG.getIntPtrConstant(i, dl));
26489       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26490                                 St->getPointerInfo(), St->isVolatile(),
26491                                 St->isNonTemporal(), St->getAlignment());
26492       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26493       Chains.push_back(Ch);
26494     }
26495
26496     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26497   }
26498
26499   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
26500   // the FP state in cases where an emms may be missing.
26501   // A preferable solution to the general problem is to figure out the right
26502   // places to insert EMMS.  This qualifies as a quick hack.
26503
26504   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26505   if (VT.getSizeInBits() != 64)
26506     return SDValue();
26507
26508   const Function *F = DAG.getMachineFunction().getFunction();
26509   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26510   bool F64IsLegal =
26511       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26512   if ((VT.isVector() ||
26513        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26514       isa<LoadSDNode>(St->getValue()) &&
26515       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26516       St->getChain().hasOneUse() && !St->isVolatile()) {
26517     SDNode* LdVal = St->getValue().getNode();
26518     LoadSDNode *Ld = nullptr;
26519     int TokenFactorIndex = -1;
26520     SmallVector<SDValue, 8> Ops;
26521     SDNode* ChainVal = St->getChain().getNode();
26522     // Must be a store of a load.  We currently handle two cases:  the load
26523     // is a direct child, and it's under an intervening TokenFactor.  It is
26524     // possible to dig deeper under nested TokenFactors.
26525     if (ChainVal == LdVal)
26526       Ld = cast<LoadSDNode>(St->getChain());
26527     else if (St->getValue().hasOneUse() &&
26528              ChainVal->getOpcode() == ISD::TokenFactor) {
26529       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26530         if (ChainVal->getOperand(i).getNode() == LdVal) {
26531           TokenFactorIndex = i;
26532           Ld = cast<LoadSDNode>(St->getValue());
26533         } else
26534           Ops.push_back(ChainVal->getOperand(i));
26535       }
26536     }
26537
26538     if (!Ld || !ISD::isNormalLoad(Ld))
26539       return SDValue();
26540
26541     // If this is not the MMX case, i.e. we are just turning i64 load/store
26542     // into f64 load/store, avoid the transformation if there are multiple
26543     // uses of the loaded value.
26544     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26545       return SDValue();
26546
26547     SDLoc LdDL(Ld);
26548     SDLoc StDL(N);
26549     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26550     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26551     // pair instead.
26552     if (Subtarget->is64Bit() || F64IsLegal) {
26553       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26554       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26555                                   Ld->getPointerInfo(), Ld->isVolatile(),
26556                                   Ld->isNonTemporal(), Ld->isInvariant(),
26557                                   Ld->getAlignment());
26558       SDValue NewChain = NewLd.getValue(1);
26559       if (TokenFactorIndex != -1) {
26560         Ops.push_back(NewChain);
26561         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26562       }
26563       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26564                           St->getPointerInfo(),
26565                           St->isVolatile(), St->isNonTemporal(),
26566                           St->getAlignment());
26567     }
26568
26569     // Otherwise, lower to two pairs of 32-bit loads / stores.
26570     SDValue LoAddr = Ld->getBasePtr();
26571     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26572                                  DAG.getConstant(4, LdDL, MVT::i32));
26573
26574     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26575                                Ld->getPointerInfo(),
26576                                Ld->isVolatile(), Ld->isNonTemporal(),
26577                                Ld->isInvariant(), Ld->getAlignment());
26578     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26579                                Ld->getPointerInfo().getWithOffset(4),
26580                                Ld->isVolatile(), Ld->isNonTemporal(),
26581                                Ld->isInvariant(),
26582                                MinAlign(Ld->getAlignment(), 4));
26583
26584     SDValue NewChain = LoLd.getValue(1);
26585     if (TokenFactorIndex != -1) {
26586       Ops.push_back(LoLd);
26587       Ops.push_back(HiLd);
26588       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26589     }
26590
26591     LoAddr = St->getBasePtr();
26592     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26593                          DAG.getConstant(4, StDL, MVT::i32));
26594
26595     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26596                                 St->getPointerInfo(),
26597                                 St->isVolatile(), St->isNonTemporal(),
26598                                 St->getAlignment());
26599     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26600                                 St->getPointerInfo().getWithOffset(4),
26601                                 St->isVolatile(),
26602                                 St->isNonTemporal(),
26603                                 MinAlign(St->getAlignment(), 4));
26604     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26605   }
26606
26607   // This is similar to the above case, but here we handle a scalar 64-bit
26608   // integer store that is extracted from a vector on a 32-bit target.
26609   // If we have SSE2, then we can treat it like a floating-point double
26610   // to get past legalization. The execution dependencies fixup pass will
26611   // choose the optimal machine instruction for the store if this really is
26612   // an integer or v2f32 rather than an f64.
26613   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26614       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26615     SDValue OldExtract = St->getOperand(1);
26616     SDValue ExtOp0 = OldExtract.getOperand(0);
26617     unsigned VecSize = ExtOp0.getValueSizeInBits();
26618     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26619     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26620     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26621                                      BitCast, OldExtract.getOperand(1));
26622     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26623                         St->getPointerInfo(), St->isVolatile(),
26624                         St->isNonTemporal(), St->getAlignment());
26625   }
26626
26627   return SDValue();
26628 }
26629
26630 /// Return 'true' if this vector operation is "horizontal"
26631 /// and return the operands for the horizontal operation in LHS and RHS.  A
26632 /// horizontal operation performs the binary operation on successive elements
26633 /// of its first operand, then on successive elements of its second operand,
26634 /// returning the resulting values in a vector.  For example, if
26635 ///   A = < float a0, float a1, float a2, float a3 >
26636 /// and
26637 ///   B = < float b0, float b1, float b2, float b3 >
26638 /// then the result of doing a horizontal operation on A and B is
26639 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26640 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26641 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26642 /// set to A, RHS to B, and the routine returns 'true'.
26643 /// Note that the binary operation should have the property that if one of the
26644 /// operands is UNDEF then the result is UNDEF.
26645 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26646   // Look for the following pattern: if
26647   //   A = < float a0, float a1, float a2, float a3 >
26648   //   B = < float b0, float b1, float b2, float b3 >
26649   // and
26650   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26651   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26652   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26653   // which is A horizontal-op B.
26654
26655   // At least one of the operands should be a vector shuffle.
26656   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26657       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26658     return false;
26659
26660   MVT VT = LHS.getSimpleValueType();
26661
26662   assert((VT.is128BitVector() || VT.is256BitVector()) &&
26663          "Unsupported vector type for horizontal add/sub");
26664
26665   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26666   // operate independently on 128-bit lanes.
26667   unsigned NumElts = VT.getVectorNumElements();
26668   unsigned NumLanes = VT.getSizeInBits()/128;
26669   unsigned NumLaneElts = NumElts / NumLanes;
26670   assert((NumLaneElts % 2 == 0) &&
26671          "Vector type should have an even number of elements in each lane");
26672   unsigned HalfLaneElts = NumLaneElts/2;
26673
26674   // View LHS in the form
26675   //   LHS = VECTOR_SHUFFLE A, B, LMask
26676   // If LHS is not a shuffle then pretend it is the shuffle
26677   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26678   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26679   // type VT.
26680   SDValue A, B;
26681   SmallVector<int, 16> LMask(NumElts);
26682   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26683     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26684       A = LHS.getOperand(0);
26685     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26686       B = LHS.getOperand(1);
26687     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26688     std::copy(Mask.begin(), Mask.end(), LMask.begin());
26689   } else {
26690     if (LHS.getOpcode() != ISD::UNDEF)
26691       A = LHS;
26692     for (unsigned i = 0; i != NumElts; ++i)
26693       LMask[i] = i;
26694   }
26695
26696   // Likewise, view RHS in the form
26697   //   RHS = VECTOR_SHUFFLE C, D, RMask
26698   SDValue C, D;
26699   SmallVector<int, 16> RMask(NumElts);
26700   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26701     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26702       C = RHS.getOperand(0);
26703     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26704       D = RHS.getOperand(1);
26705     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26706     std::copy(Mask.begin(), Mask.end(), RMask.begin());
26707   } else {
26708     if (RHS.getOpcode() != ISD::UNDEF)
26709       C = RHS;
26710     for (unsigned i = 0; i != NumElts; ++i)
26711       RMask[i] = i;
26712   }
26713
26714   // Check that the shuffles are both shuffling the same vectors.
26715   if (!(A == C && B == D) && !(A == D && B == C))
26716     return false;
26717
26718   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26719   if (!A.getNode() && !B.getNode())
26720     return false;
26721
26722   // If A and B occur in reverse order in RHS, then "swap" them (which means
26723   // rewriting the mask).
26724   if (A != C)
26725     ShuffleVectorSDNode::commuteMask(RMask);
26726
26727   // At this point LHS and RHS are equivalent to
26728   //   LHS = VECTOR_SHUFFLE A, B, LMask
26729   //   RHS = VECTOR_SHUFFLE A, B, RMask
26730   // Check that the masks correspond to performing a horizontal operation.
26731   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26732     for (unsigned i = 0; i != NumLaneElts; ++i) {
26733       int LIdx = LMask[i+l], RIdx = RMask[i+l];
26734
26735       // Ignore any UNDEF components.
26736       if (LIdx < 0 || RIdx < 0 ||
26737           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26738           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26739         continue;
26740
26741       // Check that successive elements are being operated on.  If not, this is
26742       // not a horizontal operation.
26743       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26744       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26745       if (!(LIdx == Index && RIdx == Index + 1) &&
26746           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26747         return false;
26748     }
26749   }
26750
26751   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26752   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26753   return true;
26754 }
26755
26756 /// Do target-specific dag combines on floating point adds.
26757 static SDValue PerformFADDCombine(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 adds from adds 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, true))
26767     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26768   return SDValue();
26769 }
26770
26771 /// Do target-specific dag combines on floating point subs.
26772 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26773                                   const X86Subtarget *Subtarget) {
26774   EVT VT = N->getValueType(0);
26775   SDValue LHS = N->getOperand(0);
26776   SDValue RHS = N->getOperand(1);
26777
26778   // Try to synthesize horizontal subs from subs of shuffles.
26779   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26780        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26781       isHorizontalBinOp(LHS, RHS, false))
26782     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26783   return SDValue();
26784 }
26785
26786 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
26787 static SDValue
26788 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
26789                                   SmallVector<SDValue, 8> &Regs) {
26790   assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
26791                              Regs[0].getValueType() == MVT::v2i64));
26792   EVT OutVT = N->getValueType(0);
26793   EVT OutSVT = OutVT.getVectorElementType();
26794   EVT InVT = Regs[0].getValueType();
26795   EVT InSVT = InVT.getVectorElementType();
26796   SDLoc DL(N);
26797
26798   // First, use mask to unset all bits that won't appear in the result.
26799   assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
26800          "OutSVT can only be either i8 or i16.");
26801   SDValue MaskVal =
26802       DAG.getConstant(OutSVT == MVT::i8 ? 0xFF : 0xFFFF, DL, InSVT);
26803   SDValue MaskVec = DAG.getNode(
26804       ISD::BUILD_VECTOR, DL, InVT,
26805       SmallVector<SDValue, 8>(InVT.getVectorNumElements(), MaskVal));
26806   for (auto &Reg : Regs)
26807     Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVec, Reg);
26808
26809   MVT UnpackedVT, PackedVT;
26810   if (OutSVT == MVT::i8) {
26811     UnpackedVT = MVT::v8i16;
26812     PackedVT = MVT::v16i8;
26813   } else {
26814     UnpackedVT = MVT::v4i32;
26815     PackedVT = MVT::v8i16;
26816   }
26817
26818   // In each iteration, truncate the type by a half size.
26819   auto RegNum = Regs.size();
26820   for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
26821        j < e; j *= 2, RegNum /= 2) {
26822     for (unsigned i = 0; i < RegNum; i++)
26823       Regs[i] = DAG.getNode(ISD::BITCAST, DL, UnpackedVT, Regs[i]);
26824     for (unsigned i = 0; i < RegNum / 2; i++)
26825       Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
26826                             Regs[i * 2 + 1]);
26827   }
26828
26829   // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
26830   // then extract a subvector as the result since v8i8 is not a legal type.
26831   if (OutVT == MVT::v8i8) {
26832     Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
26833     Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
26834                           DAG.getIntPtrConstant(0, DL));
26835     return Regs[0];
26836   } else if (RegNum > 1) {
26837     Regs.resize(RegNum);
26838     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26839   } else
26840     return Regs[0];
26841 }
26842
26843 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
26844 static SDValue
26845 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
26846                                   SmallVector<SDValue, 8> &Regs) {
26847   assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
26848   EVT OutVT = N->getValueType(0);
26849   SDLoc DL(N);
26850
26851   // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
26852   SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
26853   for (auto &Reg : Regs) {
26854     Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26855     Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26856   }
26857
26858   for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
26859     Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
26860                           Regs[i * 2 + 1]);
26861
26862   if (Regs.size() > 2) {
26863     Regs.resize(Regs.size() / 2);
26864     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26865   } else
26866     return Regs[0];
26867 }
26868
26869 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
26870 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
26871 /// legalization the truncation will be translated into a BUILD_VECTOR with each
26872 /// element that is extracted from a vector and then truncated, and it is
26873 /// diffcult to do this optimization based on them.
26874 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
26875                                        const X86Subtarget *Subtarget) {
26876   EVT OutVT = N->getValueType(0);
26877   if (!OutVT.isVector())
26878     return SDValue();
26879
26880   SDValue In = N->getOperand(0);
26881   if (!In.getValueType().isSimple())
26882     return SDValue();
26883
26884   EVT InVT = In.getValueType();
26885   unsigned NumElems = OutVT.getVectorNumElements();
26886
26887   // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
26888   // SSE2, and we need to take care of it specially.
26889   // AVX512 provides vpmovdb.
26890   if (!Subtarget->hasSSE2() || Subtarget->hasAVX2())
26891     return SDValue();
26892
26893   EVT OutSVT = OutVT.getVectorElementType();
26894   EVT InSVT = InVT.getVectorElementType();
26895   if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
26896         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
26897         NumElems >= 8))
26898     return SDValue();
26899
26900   // SSSE3's pshufb results in less instructions in the cases below.
26901   if (Subtarget->hasSSSE3() && NumElems == 8 &&
26902       ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
26903        (InSVT == MVT::i32 && OutSVT == MVT::i16)))
26904     return SDValue();
26905
26906   SDLoc DL(N);
26907
26908   // Split a long vector into vectors of legal type.
26909   unsigned RegNum = InVT.getSizeInBits() / 128;
26910   SmallVector<SDValue, 8> SubVec(RegNum);
26911   if (InSVT == MVT::i32) {
26912     for (unsigned i = 0; i < RegNum; i++)
26913       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
26914                               DAG.getIntPtrConstant(i * 4, DL));
26915   } else {
26916     for (unsigned i = 0; i < RegNum; i++)
26917       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
26918                               DAG.getIntPtrConstant(i * 2, DL));
26919   }
26920
26921   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PAKCUS
26922   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
26923   // truncate 2 x v4i32 to v8i16.
26924   if (Subtarget->hasSSE41() || OutSVT == MVT::i8)
26925     return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
26926   else if (InSVT == MVT::i32)
26927     return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
26928   else
26929     return SDValue();
26930 }
26931
26932 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
26933                                       const X86Subtarget *Subtarget) {
26934   // Try to detect AVG pattern first.
26935   SDValue Avg = detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG,
26936                                  Subtarget, SDLoc(N));
26937   if (Avg.getNode())
26938     return Avg;
26939
26940   return combineVectorTruncation(N, DAG, Subtarget);
26941 }
26942
26943 /// Do target-specific dag combines on floating point negations.
26944 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
26945                                   const X86Subtarget *Subtarget) {
26946   EVT VT = N->getValueType(0);
26947   EVT SVT = VT.getScalarType();
26948   SDValue Arg = N->getOperand(0);
26949   SDLoc DL(N);
26950
26951   // Let legalize expand this if it isn't a legal type yet.
26952   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26953     return SDValue();
26954
26955   // If we're negating a FMUL node on a target with FMA, then we can avoid the
26956   // use of a constant by performing (-0 - A*B) instead.
26957   // FIXME: Check rounding control flags as well once it becomes available.
26958   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
26959       Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
26960     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
26961     return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26962                        Arg.getOperand(1), Zero);
26963   }
26964
26965   // If we're negating a FMA node, then we can adjust the
26966   // instruction to include the extra negation.
26967   if (Arg.hasOneUse()) {
26968     switch (Arg.getOpcode()) {
26969     case X86ISD::FMADD:
26970       return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26971                          Arg.getOperand(1), Arg.getOperand(2));
26972     case X86ISD::FMSUB:
26973       return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
26974                          Arg.getOperand(1), Arg.getOperand(2));
26975     case X86ISD::FNMADD:
26976       return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
26977                          Arg.getOperand(1), Arg.getOperand(2));
26978     case X86ISD::FNMSUB:
26979       return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
26980                          Arg.getOperand(1), Arg.getOperand(2));
26981     }
26982   }
26983   return SDValue();
26984 }
26985
26986 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
26987                               const X86Subtarget *Subtarget) {
26988   EVT VT = N->getValueType(0);
26989   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
26990     // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
26991     // These logic operations may be executed in the integer domain.
26992     SDLoc dl(N);
26993     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
26994     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
26995
26996     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
26997     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
26998     unsigned IntOpcode = 0;
26999     switch (N->getOpcode()) {
27000       default: llvm_unreachable("Unexpected FP logic op");
27001       case X86ISD::FOR: IntOpcode = ISD::OR; break;
27002       case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
27003       case X86ISD::FAND: IntOpcode = ISD::AND; break;
27004       case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
27005     }
27006     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
27007     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
27008   }
27009   return SDValue();
27010 }
27011 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
27012 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
27013                                  const X86Subtarget *Subtarget) {
27014   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
27015
27016   // F[X]OR(0.0, x) -> x
27017   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27018     if (C->getValueAPF().isPosZero())
27019       return N->getOperand(1);
27020
27021   // F[X]OR(x, 0.0) -> x
27022   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27023     if (C->getValueAPF().isPosZero())
27024       return N->getOperand(0);
27025
27026   return lowerX86FPLogicOp(N, DAG, Subtarget);
27027 }
27028
27029 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
27030 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
27031   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
27032
27033   // Only perform optimizations if UnsafeMath is used.
27034   if (!DAG.getTarget().Options.UnsafeFPMath)
27035     return SDValue();
27036
27037   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
27038   // into FMINC and FMAXC, which are Commutative operations.
27039   unsigned NewOp = 0;
27040   switch (N->getOpcode()) {
27041     default: llvm_unreachable("unknown opcode");
27042     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
27043     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
27044   }
27045
27046   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
27047                      N->getOperand(0), N->getOperand(1));
27048 }
27049
27050 static SDValue performFMinNumFMaxNumCombine(SDNode *N, SelectionDAG &DAG,
27051                                             const X86Subtarget *Subtarget) {
27052   if (Subtarget->useSoftFloat())
27053     return SDValue();
27054
27055   // TODO: Check for global or instruction-level "nnan". In that case, we
27056   //       should be able to lower to FMAX/FMIN alone.
27057   // TODO: If an operand is already known to be a NaN or not a NaN, this
27058   //       should be an optional swap and FMAX/FMIN.
27059
27060   EVT VT = N->getValueType(0);
27061   if (!((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
27062         (Subtarget->hasSSE2() && (VT == MVT::f64 || VT == MVT::v2f64)) ||
27063         (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))))
27064     return SDValue();
27065
27066   // This takes at least 3 instructions, so favor a library call when operating
27067   // on a scalar and minimizing code size.
27068   if (!VT.isVector() && DAG.getMachineFunction().getFunction()->optForMinSize())
27069     return SDValue();
27070
27071   SDValue Op0 = N->getOperand(0);
27072   SDValue Op1 = N->getOperand(1);
27073   SDLoc DL(N);
27074   EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
27075       DAG.getDataLayout(), *DAG.getContext(), VT);
27076
27077   // There are 4 possibilities involving NaN inputs, and these are the required
27078   // outputs:
27079   //                   Op1
27080   //               Num     NaN
27081   //            ----------------
27082   //       Num  |  Max  |  Op0 |
27083   // Op0        ----------------
27084   //       NaN  |  Op1  |  NaN |
27085   //            ----------------
27086   //
27087   // The SSE FP max/min instructions were not designed for this case, but rather
27088   // to implement:
27089   //   Min = Op1 < Op0 ? Op1 : Op0
27090   //   Max = Op1 > Op0 ? Op1 : Op0
27091   //
27092   // So they always return Op0 if either input is a NaN. However, we can still
27093   // use those instructions for fmaxnum by selecting away a NaN input.
27094
27095   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
27096   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
27097   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
27098   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
27099
27100   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
27101   // are NaN, the NaN value of Op1 is the result.
27102   auto SelectOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
27103   return DAG.getNode(SelectOpcode, DL, VT, IsOp0Nan, Op1, MinOrMax);
27104 }
27105
27106 /// Do target-specific dag combines on X86ISD::FAND nodes.
27107 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
27108                                   const X86Subtarget *Subtarget) {
27109   // FAND(0.0, x) -> 0.0
27110   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27111     if (C->getValueAPF().isPosZero())
27112       return N->getOperand(0);
27113
27114   // FAND(x, 0.0) -> 0.0
27115   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27116     if (C->getValueAPF().isPosZero())
27117       return N->getOperand(1);
27118
27119   return lowerX86FPLogicOp(N, DAG, Subtarget);
27120 }
27121
27122 /// Do target-specific dag combines on X86ISD::FANDN nodes
27123 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
27124                                    const X86Subtarget *Subtarget) {
27125   // FANDN(0.0, x) -> x
27126   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27127     if (C->getValueAPF().isPosZero())
27128       return N->getOperand(1);
27129
27130   // FANDN(x, 0.0) -> 0.0
27131   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27132     if (C->getValueAPF().isPosZero())
27133       return N->getOperand(1);
27134
27135   return lowerX86FPLogicOp(N, DAG, Subtarget);
27136 }
27137
27138 static SDValue PerformBTCombine(SDNode *N,
27139                                 SelectionDAG &DAG,
27140                                 TargetLowering::DAGCombinerInfo &DCI) {
27141   // BT ignores high bits in the bit index operand.
27142   SDValue Op1 = N->getOperand(1);
27143   if (Op1.hasOneUse()) {
27144     unsigned BitWidth = Op1.getValueSizeInBits();
27145     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
27146     APInt KnownZero, KnownOne;
27147     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
27148                                           !DCI.isBeforeLegalizeOps());
27149     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27150     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
27151         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
27152       DCI.CommitTargetLoweringOpt(TLO);
27153   }
27154   return SDValue();
27155 }
27156
27157 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
27158   SDValue Op = N->getOperand(0);
27159   if (Op.getOpcode() == ISD::BITCAST)
27160     Op = Op.getOperand(0);
27161   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
27162   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
27163       VT.getVectorElementType().getSizeInBits() ==
27164       OpVT.getVectorElementType().getSizeInBits()) {
27165     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
27166   }
27167   return SDValue();
27168 }
27169
27170 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
27171                                                const X86Subtarget *Subtarget) {
27172   EVT VT = N->getValueType(0);
27173   if (!VT.isVector())
27174     return SDValue();
27175
27176   SDValue N0 = N->getOperand(0);
27177   SDValue N1 = N->getOperand(1);
27178   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
27179   SDLoc dl(N);
27180
27181   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
27182   // both SSE and AVX2 since there is no sign-extended shift right
27183   // operation on a vector with 64-bit elements.
27184   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
27185   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
27186   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
27187       N0.getOpcode() == ISD::SIGN_EXTEND)) {
27188     SDValue N00 = N0.getOperand(0);
27189
27190     // EXTLOAD has a better solution on AVX2,
27191     // it may be replaced with X86ISD::VSEXT node.
27192     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
27193       if (!ISD::isNormalLoad(N00.getNode()))
27194         return SDValue();
27195
27196     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
27197         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
27198                                   N00, N1);
27199       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
27200     }
27201   }
27202   return SDValue();
27203 }
27204
27205 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
27206 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
27207 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
27208 /// eliminate extend, add, and shift instructions.
27209 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
27210                                        const X86Subtarget *Subtarget) {
27211   // TODO: This should be valid for other integer types.
27212   EVT VT = Sext->getValueType(0);
27213   if (VT != MVT::i64)
27214     return SDValue();
27215
27216   // We need an 'add nsw' feeding into the 'sext'.
27217   SDValue Add = Sext->getOperand(0);
27218   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
27219     return SDValue();
27220
27221   // Having a constant operand to the 'add' ensures that we are not increasing
27222   // the instruction count because the constant is extended for free below.
27223   // A constant operand can also become the displacement field of an LEA.
27224   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
27225   if (!AddOp1)
27226     return SDValue();
27227
27228   // Don't make the 'add' bigger if there's no hope of combining it with some
27229   // other 'add' or 'shl' instruction.
27230   // TODO: It may be profitable to generate simpler LEA instructions in place
27231   // of single 'add' instructions, but the cost model for selecting an LEA
27232   // currently has a high threshold.
27233   bool HasLEAPotential = false;
27234   for (auto *User : Sext->uses()) {
27235     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
27236       HasLEAPotential = true;
27237       break;
27238     }
27239   }
27240   if (!HasLEAPotential)
27241     return SDValue();
27242
27243   // Everything looks good, so pull the 'sext' ahead of the 'add'.
27244   int64_t AddConstant = AddOp1->getSExtValue();
27245   SDValue AddOp0 = Add.getOperand(0);
27246   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
27247   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
27248
27249   // The wider add is guaranteed to not wrap because both operands are
27250   // sign-extended.
27251   SDNodeFlags Flags;
27252   Flags.setNoSignedWrap(true);
27253   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
27254 }
27255
27256 /// (i8,i32 {s/z}ext ({s/u}divrem (i8 x, i8 y)) ->
27257 /// (i8,i32 ({s/u}divrem_sext_hreg (i8 x, i8 y)
27258 /// This exposes the {s/z}ext to the sdivrem lowering, so that it directly
27259 /// extends from AH (which we otherwise need to do contortions to access).
27260 static SDValue getDivRem8(SDNode *N, SelectionDAG &DAG) {
27261   SDValue N0 = N->getOperand(0);
27262   auto OpcodeN = N->getOpcode();
27263   auto OpcodeN0 = N0.getOpcode();
27264   if (!((OpcodeN == ISD::SIGN_EXTEND && OpcodeN0 == ISD::SDIVREM) ||
27265         (OpcodeN == ISD::ZERO_EXTEND && OpcodeN0 == ISD::UDIVREM)))
27266     return SDValue();
27267
27268   EVT VT = N->getValueType(0);
27269   EVT InVT = N0.getValueType();
27270   if (N0.getResNo() != 1 || InVT != MVT::i8 || VT != MVT::i32)
27271     return SDValue();
27272
27273   SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27274   auto DivRemOpcode = OpcodeN0 == ISD::SDIVREM ? X86ISD::SDIVREM8_SEXT_HREG
27275                                                : X86ISD::UDIVREM8_ZEXT_HREG;
27276   SDValue R = DAG.getNode(DivRemOpcode, SDLoc(N), NodeTys, N0.getOperand(0),
27277                           N0.getOperand(1));
27278   DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27279   return R.getValue(1);
27280 }
27281
27282 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
27283                                   TargetLowering::DAGCombinerInfo &DCI,
27284                                   const X86Subtarget *Subtarget) {
27285   SDValue N0 = N->getOperand(0);
27286   EVT VT = N->getValueType(0);
27287   EVT SVT = VT.getScalarType();
27288   EVT InVT = N0.getValueType();
27289   EVT InSVT = InVT.getScalarType();
27290   SDLoc DL(N);
27291
27292   if (SDValue DivRem8 = getDivRem8(N, DAG))
27293     return DivRem8;
27294
27295   if (!DCI.isBeforeLegalizeOps()) {
27296     if (InVT == MVT::i1) {
27297       SDValue Zero = DAG.getConstant(0, DL, VT);
27298       SDValue AllOnes =
27299         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
27300       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
27301     }
27302     return SDValue();
27303   }
27304
27305   if (VT.isVector() && Subtarget->hasSSE2()) {
27306     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
27307       EVT InVT = N.getValueType();
27308       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
27309                                    Size / InVT.getScalarSizeInBits());
27310       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
27311                                     DAG.getUNDEF(InVT));
27312       Opnds[0] = N;
27313       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
27314     };
27315
27316     // If target-size is less than 128-bits, extend to a type that would extend
27317     // to 128 bits, extend that and extract the original target vector.
27318     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
27319         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27320         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27321       unsigned Scale = 128 / VT.getSizeInBits();
27322       EVT ExVT =
27323           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
27324       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
27325       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
27326       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
27327                          DAG.getIntPtrConstant(0, DL));
27328     }
27329
27330     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
27331     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
27332     if (VT.getSizeInBits() == 128 &&
27333         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27334         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27335       SDValue ExOp = ExtendVecSize(DL, N0, 128);
27336       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
27337     }
27338
27339     // On pre-AVX2 targets, split into 128-bit nodes of
27340     // ISD::SIGN_EXTEND_VECTOR_INREG.
27341     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
27342         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27343         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27344       unsigned NumVecs = VT.getSizeInBits() / 128;
27345       unsigned NumSubElts = 128 / SVT.getSizeInBits();
27346       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
27347       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
27348
27349       SmallVector<SDValue, 8> Opnds;
27350       for (unsigned i = 0, Offset = 0; i != NumVecs;
27351            ++i, Offset += NumSubElts) {
27352         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
27353                                      DAG.getIntPtrConstant(Offset, DL));
27354         SrcVec = ExtendVecSize(DL, SrcVec, 128);
27355         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
27356         Opnds.push_back(SrcVec);
27357       }
27358       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
27359     }
27360   }
27361
27362   if (Subtarget->hasAVX() && VT.is256BitVector())
27363     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27364       return R;
27365
27366   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
27367     return NewAdd;
27368
27369   return SDValue();
27370 }
27371
27372 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
27373                                  const X86Subtarget* Subtarget) {
27374   SDLoc dl(N);
27375   EVT VT = N->getValueType(0);
27376
27377   // Let legalize expand this if it isn't a legal type yet.
27378   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27379     return SDValue();
27380
27381   EVT ScalarVT = VT.getScalarType();
27382   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
27383     return SDValue();
27384
27385   SDValue A = N->getOperand(0);
27386   SDValue B = N->getOperand(1);
27387   SDValue C = N->getOperand(2);
27388
27389   bool NegA = (A.getOpcode() == ISD::FNEG);
27390   bool NegB = (B.getOpcode() == ISD::FNEG);
27391   bool NegC = (C.getOpcode() == ISD::FNEG);
27392
27393   // Negative multiplication when NegA xor NegB
27394   bool NegMul = (NegA != NegB);
27395   if (NegA)
27396     A = A.getOperand(0);
27397   if (NegB)
27398     B = B.getOperand(0);
27399   if (NegC)
27400     C = C.getOperand(0);
27401
27402   unsigned Opcode;
27403   if (!NegMul)
27404     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
27405   else
27406     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
27407
27408   return DAG.getNode(Opcode, dl, VT, A, B, C);
27409 }
27410
27411 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
27412                                   TargetLowering::DAGCombinerInfo &DCI,
27413                                   const X86Subtarget *Subtarget) {
27414   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
27415   //           (and (i32 x86isd::setcc_carry), 1)
27416   // This eliminates the zext. This transformation is necessary because
27417   // ISD::SETCC is always legalized to i8.
27418   SDLoc dl(N);
27419   SDValue N0 = N->getOperand(0);
27420   EVT VT = N->getValueType(0);
27421
27422   if (N0.getOpcode() == ISD::AND &&
27423       N0.hasOneUse() &&
27424       N0.getOperand(0).hasOneUse()) {
27425     SDValue N00 = N0.getOperand(0);
27426     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27427       if (!isOneConstant(N0.getOperand(1)))
27428         return SDValue();
27429       return DAG.getNode(ISD::AND, dl, VT,
27430                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27431                                      N00.getOperand(0), N00.getOperand(1)),
27432                          DAG.getConstant(1, dl, VT));
27433     }
27434   }
27435
27436   if (N0.getOpcode() == ISD::TRUNCATE &&
27437       N0.hasOneUse() &&
27438       N0.getOperand(0).hasOneUse()) {
27439     SDValue N00 = N0.getOperand(0);
27440     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27441       return DAG.getNode(ISD::AND, dl, VT,
27442                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27443                                      N00.getOperand(0), N00.getOperand(1)),
27444                          DAG.getConstant(1, dl, VT));
27445     }
27446   }
27447
27448   if (VT.is256BitVector())
27449     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27450       return R;
27451
27452   if (SDValue DivRem8 = getDivRem8(N, DAG))
27453     return DivRem8;
27454
27455   return SDValue();
27456 }
27457
27458 // Optimize x == -y --> x+y == 0
27459 //          x != -y --> x+y != 0
27460 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
27461                                       const X86Subtarget* Subtarget) {
27462   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
27463   SDValue LHS = N->getOperand(0);
27464   SDValue RHS = N->getOperand(1);
27465   EVT VT = N->getValueType(0);
27466   SDLoc DL(N);
27467
27468   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
27469     if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
27470       SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
27471                                  LHS.getOperand(1));
27472       return DAG.getSetCC(DL, N->getValueType(0), addV,
27473                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27474     }
27475   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
27476     if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
27477       SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
27478                                  RHS.getOperand(1));
27479       return DAG.getSetCC(DL, N->getValueType(0), addV,
27480                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27481     }
27482
27483   if (VT.getScalarType() == MVT::i1 &&
27484       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
27485     bool IsSEXT0 =
27486         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27487         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27488     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27489
27490     if (!IsSEXT0 || !IsVZero1) {
27491       // Swap the operands and update the condition code.
27492       std::swap(LHS, RHS);
27493       CC = ISD::getSetCCSwappedOperands(CC);
27494
27495       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27496                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27497       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27498     }
27499
27500     if (IsSEXT0 && IsVZero1) {
27501       assert(VT == LHS.getOperand(0).getValueType() &&
27502              "Uexpected operand type");
27503       if (CC == ISD::SETGT)
27504         return DAG.getConstant(0, DL, VT);
27505       if (CC == ISD::SETLE)
27506         return DAG.getConstant(1, DL, VT);
27507       if (CC == ISD::SETEQ || CC == ISD::SETGE)
27508         return DAG.getNOT(DL, LHS.getOperand(0), VT);
27509
27510       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
27511              "Unexpected condition code!");
27512       return LHS.getOperand(0);
27513     }
27514   }
27515
27516   return SDValue();
27517 }
27518
27519 static SDValue PerformGatherScatterCombine(SDNode *N, SelectionDAG &DAG) {
27520   SDLoc DL(N);
27521   // Gather and Scatter instructions use k-registers for masks. The type of
27522   // the masks is v*i1. So the mask will be truncated anyway.
27523   // The SIGN_EXTEND_INREG my be dropped.
27524   SDValue Mask = N->getOperand(2);
27525   if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
27526     SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
27527     NewOps[2] = Mask.getOperand(0);
27528     DAG.UpdateNodeOperands(N, NewOps);
27529   }
27530   return SDValue();
27531 }
27532
27533 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
27534 // as "sbb reg,reg", since it can be extended without zext and produces
27535 // an all-ones bit which is more useful than 0/1 in some cases.
27536 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
27537                                MVT VT) {
27538   if (VT == MVT::i8)
27539     return DAG.getNode(ISD::AND, DL, VT,
27540                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27541                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
27542                                    EFLAGS),
27543                        DAG.getConstant(1, DL, VT));
27544   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
27545   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
27546                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27547                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
27548                                  EFLAGS));
27549 }
27550
27551 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
27552 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
27553                                    TargetLowering::DAGCombinerInfo &DCI,
27554                                    const X86Subtarget *Subtarget) {
27555   SDLoc DL(N);
27556   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
27557   SDValue EFLAGS = N->getOperand(1);
27558
27559   if (CC == X86::COND_A) {
27560     // Try to convert COND_A into COND_B in an attempt to facilitate
27561     // materializing "setb reg".
27562     //
27563     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
27564     // cannot take an immediate as its first operand.
27565     //
27566     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
27567         EFLAGS.getValueType().isInteger() &&
27568         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
27569       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
27570                                    EFLAGS.getNode()->getVTList(),
27571                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
27572       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
27573       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
27574     }
27575   }
27576
27577   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
27578   // a zext and produces an all-ones bit which is more useful than 0/1 in some
27579   // cases.
27580   if (CC == X86::COND_B)
27581     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
27582
27583   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27584     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27585     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
27586   }
27587
27588   return SDValue();
27589 }
27590
27591 // Optimize branch condition evaluation.
27592 //
27593 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
27594                                     TargetLowering::DAGCombinerInfo &DCI,
27595                                     const X86Subtarget *Subtarget) {
27596   SDLoc DL(N);
27597   SDValue Chain = N->getOperand(0);
27598   SDValue Dest = N->getOperand(1);
27599   SDValue EFLAGS = N->getOperand(3);
27600   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
27601
27602   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27603     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27604     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
27605                        Flags);
27606   }
27607
27608   return SDValue();
27609 }
27610
27611 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
27612                                                          SelectionDAG &DAG) {
27613   // Take advantage of vector comparisons producing 0 or -1 in each lane to
27614   // optimize away operation when it's from a constant.
27615   //
27616   // The general transformation is:
27617   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
27618   //       AND(VECTOR_CMP(x,y), constant2)
27619   //    constant2 = UNARYOP(constant)
27620
27621   // Early exit if this isn't a vector operation, the operand of the
27622   // unary operation isn't a bitwise AND, or if the sizes of the operations
27623   // aren't the same.
27624   EVT VT = N->getValueType(0);
27625   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27626       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27627       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27628     return SDValue();
27629
27630   // Now check that the other operand of the AND is a constant. We could
27631   // make the transformation for non-constant splats as well, but it's unclear
27632   // that would be a benefit as it would not eliminate any operations, just
27633   // perform one more step in scalar code before moving to the vector unit.
27634   if (BuildVectorSDNode *BV =
27635           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27636     // Bail out if the vector isn't a constant.
27637     if (!BV->isConstant())
27638       return SDValue();
27639
27640     // Everything checks out. Build up the new and improved node.
27641     SDLoc DL(N);
27642     EVT IntVT = BV->getValueType(0);
27643     // Create a new constant of the appropriate type for the transformed
27644     // DAG.
27645     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27646     // The AND node needs bitcasts to/from an integer vector type around it.
27647     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27648     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27649                                  N->getOperand(0)->getOperand(0), MaskConst);
27650     SDValue Res = DAG.getBitcast(VT, NewAnd);
27651     return Res;
27652   }
27653
27654   return SDValue();
27655 }
27656
27657 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27658                                         const X86Subtarget *Subtarget) {
27659   SDValue Op0 = N->getOperand(0);
27660   EVT VT = N->getValueType(0);
27661   EVT InVT = Op0.getValueType();
27662   EVT InSVT = InVT.getScalarType();
27663   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27664
27665   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27666   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27667   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27668     SDLoc dl(N);
27669     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27670                                  InVT.getVectorNumElements());
27671     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27672
27673     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27674       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27675
27676     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27677   }
27678
27679   return SDValue();
27680 }
27681
27682 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27683                                         const X86Subtarget *Subtarget) {
27684   // First try to optimize away the conversion entirely when it's
27685   // conditionally from a constant. Vectors only.
27686   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27687     return Res;
27688
27689   // Now move on to more general possibilities.
27690   SDValue Op0 = N->getOperand(0);
27691   EVT VT = N->getValueType(0);
27692   EVT InVT = Op0.getValueType();
27693   EVT InSVT = InVT.getScalarType();
27694
27695   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27696   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27697   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27698     SDLoc dl(N);
27699     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27700                                  InVT.getVectorNumElements());
27701     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27702     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27703   }
27704
27705   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27706   // a 32-bit target where SSE doesn't support i64->FP operations.
27707   if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27708     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27709     EVT LdVT = Ld->getValueType(0);
27710
27711     // This transformation is not supported if the result type is f16
27712     if (VT == MVT::f16)
27713       return SDValue();
27714
27715     if (!Ld->isVolatile() && !VT.isVector() &&
27716         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27717         !Subtarget->is64Bit() && LdVT == MVT::i64) {
27718       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27719           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27720       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27721       return FILDChain;
27722     }
27723   }
27724   return SDValue();
27725 }
27726
27727 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27728 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27729                                  X86TargetLowering::DAGCombinerInfo &DCI) {
27730   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27731   // the result is either zero or one (depending on the input carry bit).
27732   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27733   if (X86::isZeroNode(N->getOperand(0)) &&
27734       X86::isZeroNode(N->getOperand(1)) &&
27735       // We don't have a good way to replace an EFLAGS use, so only do this when
27736       // dead right now.
27737       SDValue(N, 1).use_empty()) {
27738     SDLoc DL(N);
27739     EVT VT = N->getValueType(0);
27740     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27741     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27742                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27743                                            DAG.getConstant(X86::COND_B, DL,
27744                                                            MVT::i8),
27745                                            N->getOperand(2)),
27746                                DAG.getConstant(1, DL, VT));
27747     return DCI.CombineTo(N, Res1, CarryOut);
27748   }
27749
27750   return SDValue();
27751 }
27752
27753 // fold (add Y, (sete  X, 0)) -> adc  0, Y
27754 //      (add Y, (setne X, 0)) -> sbb -1, Y
27755 //      (sub (sete  X, 0), Y) -> sbb  0, Y
27756 //      (sub (setne X, 0), Y) -> adc -1, Y
27757 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27758   SDLoc DL(N);
27759
27760   // Look through ZExts.
27761   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27762   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27763     return SDValue();
27764
27765   SDValue SetCC = Ext.getOperand(0);
27766   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27767     return SDValue();
27768
27769   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27770   if (CC != X86::COND_E && CC != X86::COND_NE)
27771     return SDValue();
27772
27773   SDValue Cmp = SetCC.getOperand(1);
27774   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27775       !X86::isZeroNode(Cmp.getOperand(1)) ||
27776       !Cmp.getOperand(0).getValueType().isInteger())
27777     return SDValue();
27778
27779   SDValue CmpOp0 = Cmp.getOperand(0);
27780   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27781                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
27782
27783   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27784   if (CC == X86::COND_NE)
27785     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27786                        DL, OtherVal.getValueType(), OtherVal,
27787                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27788                        NewCmp);
27789   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27790                      DL, OtherVal.getValueType(), OtherVal,
27791                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27792 }
27793
27794 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27795 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27796                                  const X86Subtarget *Subtarget) {
27797   EVT VT = N->getValueType(0);
27798   SDValue Op0 = N->getOperand(0);
27799   SDValue Op1 = N->getOperand(1);
27800
27801   // Try to synthesize horizontal adds from adds of shuffles.
27802   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27803        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27804       isHorizontalBinOp(Op0, Op1, true))
27805     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27806
27807   return OptimizeConditionalInDecrement(N, DAG);
27808 }
27809
27810 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27811                                  const X86Subtarget *Subtarget) {
27812   SDValue Op0 = N->getOperand(0);
27813   SDValue Op1 = N->getOperand(1);
27814
27815   // X86 can't encode an immediate LHS of a sub. See if we can push the
27816   // negation into a preceding instruction.
27817   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27818     // If the RHS of the sub is a XOR with one use and a constant, invert the
27819     // immediate. Then add one to the LHS of the sub so we can turn
27820     // X-Y -> X+~Y+1, saving one register.
27821     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27822         isa<ConstantSDNode>(Op1.getOperand(1))) {
27823       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27824       EVT VT = Op0.getValueType();
27825       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27826                                    Op1.getOperand(0),
27827                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
27828       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27829                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27830     }
27831   }
27832
27833   // Try to synthesize horizontal adds from adds of shuffles.
27834   EVT VT = N->getValueType(0);
27835   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27836        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27837       isHorizontalBinOp(Op0, Op1, true))
27838     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27839
27840   return OptimizeConditionalInDecrement(N, DAG);
27841 }
27842
27843 /// performVZEXTCombine - Performs build vector combines
27844 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27845                                    TargetLowering::DAGCombinerInfo &DCI,
27846                                    const X86Subtarget *Subtarget) {
27847   SDLoc DL(N);
27848   MVT VT = N->getSimpleValueType(0);
27849   SDValue Op = N->getOperand(0);
27850   MVT OpVT = Op.getSimpleValueType();
27851   MVT OpEltVT = OpVT.getVectorElementType();
27852   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27853
27854   // (vzext (bitcast (vzext (x)) -> (vzext x)
27855   SDValue V = Op;
27856   while (V.getOpcode() == ISD::BITCAST)
27857     V = V.getOperand(0);
27858
27859   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27860     MVT InnerVT = V.getSimpleValueType();
27861     MVT InnerEltVT = InnerVT.getVectorElementType();
27862
27863     // If the element sizes match exactly, we can just do one larger vzext. This
27864     // is always an exact type match as vzext operates on integer types.
27865     if (OpEltVT == InnerEltVT) {
27866       assert(OpVT == InnerVT && "Types must match for vzext!");
27867       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27868     }
27869
27870     // The only other way we can combine them is if only a single element of the
27871     // inner vzext is used in the input to the outer vzext.
27872     if (InnerEltVT.getSizeInBits() < InputBits)
27873       return SDValue();
27874
27875     // In this case, the inner vzext is completely dead because we're going to
27876     // only look at bits inside of the low element. Just do the outer vzext on
27877     // a bitcast of the input to the inner.
27878     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27879   }
27880
27881   // Check if we can bypass extracting and re-inserting an element of an input
27882   // vector. Essentially:
27883   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27884   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27885       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27886       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27887     SDValue ExtractedV = V.getOperand(0);
27888     SDValue OrigV = ExtractedV.getOperand(0);
27889     if (isNullConstant(ExtractedV.getOperand(1))) {
27890         MVT OrigVT = OrigV.getSimpleValueType();
27891         // Extract a subvector if necessary...
27892         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27893           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27894           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
27895                                     OrigVT.getVectorNumElements() / Ratio);
27896           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
27897                               DAG.getIntPtrConstant(0, DL));
27898         }
27899         Op = DAG.getBitcast(OpVT, OrigV);
27900         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
27901       }
27902   }
27903
27904   return SDValue();
27905 }
27906
27907 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
27908                                              DAGCombinerInfo &DCI) const {
27909   SelectionDAG &DAG = DCI.DAG;
27910   switch (N->getOpcode()) {
27911   default: break;
27912   case ISD::EXTRACT_VECTOR_ELT:
27913     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
27914   case ISD::VSELECT:
27915   case ISD::SELECT:
27916   case X86ISD::SHRUNKBLEND:
27917     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
27918   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
27919   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
27920   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
27921   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
27922   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
27923   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
27924   case ISD::SHL:
27925   case ISD::SRA:
27926   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
27927   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
27928   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
27929   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
27930   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
27931   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
27932   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
27933   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
27934   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
27935   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
27936   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
27937   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
27938   case ISD::FNEG:           return PerformFNEGCombine(N, DAG, Subtarget);
27939   case ISD::TRUNCATE:       return PerformTRUNCATECombine(N, DAG, Subtarget);
27940   case X86ISD::FXOR:
27941   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
27942   case X86ISD::FMIN:
27943   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
27944   case ISD::FMINNUM:
27945   case ISD::FMAXNUM:        return performFMinNumFMaxNumCombine(N, DAG,
27946                                                                 Subtarget);
27947   case X86ISD::FAND:        return PerformFANDCombine(N, DAG, Subtarget);
27948   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG, Subtarget);
27949   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
27950   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
27951   case ISD::ANY_EXTEND:
27952   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
27953   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
27954   case ISD::SIGN_EXTEND_INREG:
27955     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
27956   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
27957   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
27958   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
27959   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
27960   case X86ISD::SHUFP:       // Handle all target specific shuffles
27961   case X86ISD::PALIGNR:
27962   case X86ISD::BLENDI:
27963   case X86ISD::UNPCKH:
27964   case X86ISD::UNPCKL:
27965   case X86ISD::MOVHLPS:
27966   case X86ISD::MOVLHPS:
27967   case X86ISD::PSHUFB:
27968   case X86ISD::PSHUFD:
27969   case X86ISD::PSHUFHW:
27970   case X86ISD::PSHUFLW:
27971   case X86ISD::MOVSS:
27972   case X86ISD::MOVSD:
27973   case X86ISD::VPERMILPI:
27974   case X86ISD::VPERM2X128:
27975   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
27976   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
27977   case ISD::MGATHER:
27978   case ISD::MSCATTER:       return PerformGatherScatterCombine(N, DAG);
27979   }
27980
27981   return SDValue();
27982 }
27983
27984 /// isTypeDesirableForOp - Return true if the target has native support for
27985 /// the specified value type and it is 'desirable' to use the type for the
27986 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
27987 /// instruction encodings are longer and some i16 instructions are slow.
27988 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
27989   if (!isTypeLegal(VT))
27990     return false;
27991   if (VT != MVT::i16)
27992     return true;
27993
27994   switch (Opc) {
27995   default:
27996     return true;
27997   case ISD::LOAD:
27998   case ISD::SIGN_EXTEND:
27999   case ISD::ZERO_EXTEND:
28000   case ISD::ANY_EXTEND:
28001   case ISD::SHL:
28002   case ISD::SRL:
28003   case ISD::SUB:
28004   case ISD::ADD:
28005   case ISD::MUL:
28006   case ISD::AND:
28007   case ISD::OR:
28008   case ISD::XOR:
28009     return false;
28010   }
28011 }
28012
28013 /// This function checks if any of the users of EFLAGS copies the EFLAGS. We
28014 /// know that the code that lowers COPY of EFLAGS has to use the stack, and if
28015 /// we don't adjust the stack we clobber the first frame index.
28016 /// See X86InstrInfo::copyPhysReg.
28017 bool X86TargetLowering::hasCopyImplyingStackAdjustment(
28018     MachineFunction *MF) const {
28019   const MachineRegisterInfo &MRI = MF->getRegInfo();
28020
28021   return any_of(MRI.reg_instructions(X86::EFLAGS),
28022                 [](const MachineInstr &RI) { return RI.isCopy(); });
28023 }
28024
28025 /// IsDesirableToPromoteOp - This method query the target whether it is
28026 /// beneficial for dag combiner to promote the specified node. If true, it
28027 /// should return the desired promotion type by reference.
28028 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
28029   EVT VT = Op.getValueType();
28030   if (VT != MVT::i16)
28031     return false;
28032
28033   bool Promote = false;
28034   bool Commute = false;
28035   switch (Op.getOpcode()) {
28036   default: break;
28037   case ISD::LOAD: {
28038     LoadSDNode *LD = cast<LoadSDNode>(Op);
28039     // If the non-extending load has a single use and it's not live out, then it
28040     // might be folded.
28041     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
28042                                                      Op.hasOneUse()*/) {
28043       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
28044              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
28045         // The only case where we'd want to promote LOAD (rather then it being
28046         // promoted as an operand is when it's only use is liveout.
28047         if (UI->getOpcode() != ISD::CopyToReg)
28048           return false;
28049       }
28050     }
28051     Promote = true;
28052     break;
28053   }
28054   case ISD::SIGN_EXTEND:
28055   case ISD::ZERO_EXTEND:
28056   case ISD::ANY_EXTEND:
28057     Promote = true;
28058     break;
28059   case ISD::SHL:
28060   case ISD::SRL: {
28061     SDValue N0 = Op.getOperand(0);
28062     // Look out for (store (shl (load), x)).
28063     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
28064       return false;
28065     Promote = true;
28066     break;
28067   }
28068   case ISD::ADD:
28069   case ISD::MUL:
28070   case ISD::AND:
28071   case ISD::OR:
28072   case ISD::XOR:
28073     Commute = true;
28074     // fallthrough
28075   case ISD::SUB: {
28076     SDValue N0 = Op.getOperand(0);
28077     SDValue N1 = Op.getOperand(1);
28078     if (!Commute && MayFoldLoad(N1))
28079       return false;
28080     // Avoid disabling potential load folding opportunities.
28081     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
28082       return false;
28083     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
28084       return false;
28085     Promote = true;
28086   }
28087   }
28088
28089   PVT = MVT::i32;
28090   return Promote;
28091 }
28092
28093 //===----------------------------------------------------------------------===//
28094 //                           X86 Inline Assembly Support
28095 //===----------------------------------------------------------------------===//
28096
28097 // Helper to match a string separated by whitespace.
28098 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
28099   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
28100
28101   for (StringRef Piece : Pieces) {
28102     if (!S.startswith(Piece)) // Check if the piece matches.
28103       return false;
28104
28105     S = S.substr(Piece.size());
28106     StringRef::size_type Pos = S.find_first_not_of(" \t");
28107     if (Pos == 0) // We matched a prefix.
28108       return false;
28109
28110     S = S.substr(Pos);
28111   }
28112
28113   return S.empty();
28114 }
28115
28116 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
28117
28118   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
28119     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
28120         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
28121         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
28122
28123       if (AsmPieces.size() == 3)
28124         return true;
28125       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
28126         return true;
28127     }
28128   }
28129   return false;
28130 }
28131
28132 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
28133   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
28134
28135   std::string AsmStr = IA->getAsmString();
28136
28137   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
28138   if (!Ty || Ty->getBitWidth() % 16 != 0)
28139     return false;
28140
28141   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
28142   SmallVector<StringRef, 4> AsmPieces;
28143   SplitString(AsmStr, AsmPieces, ";\n");
28144
28145   switch (AsmPieces.size()) {
28146   default: return false;
28147   case 1:
28148     // FIXME: this should verify that we are targeting a 486 or better.  If not,
28149     // we will turn this bswap into something that will be lowered to logical
28150     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
28151     // lower so don't worry about this.
28152     // bswap $0
28153     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
28154         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
28155         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
28156         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
28157         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
28158         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
28159       // No need to check constraints, nothing other than the equivalent of
28160       // "=r,0" would be valid here.
28161       return IntrinsicLowering::LowerToByteSwap(CI);
28162     }
28163
28164     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
28165     if (CI->getType()->isIntegerTy(16) &&
28166         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28167         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
28168          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
28169       AsmPieces.clear();
28170       StringRef ConstraintsStr = IA->getConstraintString();
28171       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28172       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28173       if (clobbersFlagRegisters(AsmPieces))
28174         return IntrinsicLowering::LowerToByteSwap(CI);
28175     }
28176     break;
28177   case 3:
28178     if (CI->getType()->isIntegerTy(32) &&
28179         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28180         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
28181         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
28182         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
28183       AsmPieces.clear();
28184       StringRef ConstraintsStr = IA->getConstraintString();
28185       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28186       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28187       if (clobbersFlagRegisters(AsmPieces))
28188         return IntrinsicLowering::LowerToByteSwap(CI);
28189     }
28190
28191     if (CI->getType()->isIntegerTy(64)) {
28192       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
28193       if (Constraints.size() >= 2 &&
28194           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
28195           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
28196         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
28197         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
28198             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
28199             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
28200           return IntrinsicLowering::LowerToByteSwap(CI);
28201       }
28202     }
28203     break;
28204   }
28205   return false;
28206 }
28207
28208 /// getConstraintType - Given a constraint letter, return the type of
28209 /// constraint it is for this target.
28210 X86TargetLowering::ConstraintType
28211 X86TargetLowering::getConstraintType(StringRef Constraint) const {
28212   if (Constraint.size() == 1) {
28213     switch (Constraint[0]) {
28214     case 'R':
28215     case 'q':
28216     case 'Q':
28217     case 'f':
28218     case 't':
28219     case 'u':
28220     case 'y':
28221     case 'x':
28222     case 'Y':
28223     case 'l':
28224       return C_RegisterClass;
28225     case 'a':
28226     case 'b':
28227     case 'c':
28228     case 'd':
28229     case 'S':
28230     case 'D':
28231     case 'A':
28232       return C_Register;
28233     case 'I':
28234     case 'J':
28235     case 'K':
28236     case 'L':
28237     case 'M':
28238     case 'N':
28239     case 'G':
28240     case 'C':
28241     case 'e':
28242     case 'Z':
28243       return C_Other;
28244     default:
28245       break;
28246     }
28247   }
28248   return TargetLowering::getConstraintType(Constraint);
28249 }
28250
28251 /// Examine constraint type and operand type and determine a weight value.
28252 /// This object must already have been set up with the operand type
28253 /// and the current alternative constraint selected.
28254 TargetLowering::ConstraintWeight
28255   X86TargetLowering::getSingleConstraintMatchWeight(
28256     AsmOperandInfo &info, const char *constraint) const {
28257   ConstraintWeight weight = CW_Invalid;
28258   Value *CallOperandVal = info.CallOperandVal;
28259     // If we don't have a value, we can't do a match,
28260     // but allow it at the lowest weight.
28261   if (!CallOperandVal)
28262     return CW_Default;
28263   Type *type = CallOperandVal->getType();
28264   // Look at the constraint type.
28265   switch (*constraint) {
28266   default:
28267     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
28268   case 'R':
28269   case 'q':
28270   case 'Q':
28271   case 'a':
28272   case 'b':
28273   case 'c':
28274   case 'd':
28275   case 'S':
28276   case 'D':
28277   case 'A':
28278     if (CallOperandVal->getType()->isIntegerTy())
28279       weight = CW_SpecificReg;
28280     break;
28281   case 'f':
28282   case 't':
28283   case 'u':
28284     if (type->isFloatingPointTy())
28285       weight = CW_SpecificReg;
28286     break;
28287   case 'y':
28288     if (type->isX86_MMXTy() && Subtarget->hasMMX())
28289       weight = CW_SpecificReg;
28290     break;
28291   case 'x':
28292   case 'Y':
28293     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
28294         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
28295       weight = CW_Register;
28296     break;
28297   case 'I':
28298     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
28299       if (C->getZExtValue() <= 31)
28300         weight = CW_Constant;
28301     }
28302     break;
28303   case 'J':
28304     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28305       if (C->getZExtValue() <= 63)
28306         weight = CW_Constant;
28307     }
28308     break;
28309   case 'K':
28310     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28311       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
28312         weight = CW_Constant;
28313     }
28314     break;
28315   case 'L':
28316     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28317       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
28318         weight = CW_Constant;
28319     }
28320     break;
28321   case 'M':
28322     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28323       if (C->getZExtValue() <= 3)
28324         weight = CW_Constant;
28325     }
28326     break;
28327   case 'N':
28328     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28329       if (C->getZExtValue() <= 0xff)
28330         weight = CW_Constant;
28331     }
28332     break;
28333   case 'G':
28334   case 'C':
28335     if (isa<ConstantFP>(CallOperandVal)) {
28336       weight = CW_Constant;
28337     }
28338     break;
28339   case 'e':
28340     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28341       if ((C->getSExtValue() >= -0x80000000LL) &&
28342           (C->getSExtValue() <= 0x7fffffffLL))
28343         weight = CW_Constant;
28344     }
28345     break;
28346   case 'Z':
28347     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28348       if (C->getZExtValue() <= 0xffffffff)
28349         weight = CW_Constant;
28350     }
28351     break;
28352   }
28353   return weight;
28354 }
28355
28356 /// LowerXConstraint - try to replace an X constraint, which matches anything,
28357 /// with another that has more specific requirements based on the type of the
28358 /// corresponding operand.
28359 const char *X86TargetLowering::
28360 LowerXConstraint(EVT ConstraintVT) const {
28361   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
28362   // 'f' like normal targets.
28363   if (ConstraintVT.isFloatingPoint()) {
28364     if (Subtarget->hasSSE2())
28365       return "Y";
28366     if (Subtarget->hasSSE1())
28367       return "x";
28368   }
28369
28370   return TargetLowering::LowerXConstraint(ConstraintVT);
28371 }
28372
28373 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
28374 /// vector.  If it is invalid, don't add anything to Ops.
28375 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
28376                                                      std::string &Constraint,
28377                                                      std::vector<SDValue>&Ops,
28378                                                      SelectionDAG &DAG) const {
28379   SDValue Result;
28380
28381   // Only support length 1 constraints for now.
28382   if (Constraint.length() > 1) return;
28383
28384   char ConstraintLetter = Constraint[0];
28385   switch (ConstraintLetter) {
28386   default: break;
28387   case 'I':
28388     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28389       if (C->getZExtValue() <= 31) {
28390         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28391                                        Op.getValueType());
28392         break;
28393       }
28394     }
28395     return;
28396   case 'J':
28397     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28398       if (C->getZExtValue() <= 63) {
28399         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28400                                        Op.getValueType());
28401         break;
28402       }
28403     }
28404     return;
28405   case 'K':
28406     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28407       if (isInt<8>(C->getSExtValue())) {
28408         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28409                                        Op.getValueType());
28410         break;
28411       }
28412     }
28413     return;
28414   case 'L':
28415     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28416       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
28417           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
28418         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
28419                                        Op.getValueType());
28420         break;
28421       }
28422     }
28423     return;
28424   case 'M':
28425     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28426       if (C->getZExtValue() <= 3) {
28427         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28428                                        Op.getValueType());
28429         break;
28430       }
28431     }
28432     return;
28433   case 'N':
28434     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28435       if (C->getZExtValue() <= 255) {
28436         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28437                                        Op.getValueType());
28438         break;
28439       }
28440     }
28441     return;
28442   case 'O':
28443     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28444       if (C->getZExtValue() <= 127) {
28445         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28446                                        Op.getValueType());
28447         break;
28448       }
28449     }
28450     return;
28451   case 'e': {
28452     // 32-bit signed value
28453     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28454       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28455                                            C->getSExtValue())) {
28456         // Widen to 64 bits here to get it sign extended.
28457         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
28458         break;
28459       }
28460     // FIXME gcc accepts some relocatable values here too, but only in certain
28461     // memory models; it's complicated.
28462     }
28463     return;
28464   }
28465   case 'Z': {
28466     // 32-bit unsigned value
28467     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28468       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28469                                            C->getZExtValue())) {
28470         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28471                                        Op.getValueType());
28472         break;
28473       }
28474     }
28475     // FIXME gcc accepts some relocatable values here too, but only in certain
28476     // memory models; it's complicated.
28477     return;
28478   }
28479   case 'i': {
28480     // Literal immediates are always ok.
28481     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
28482       // Widen to 64 bits here to get it sign extended.
28483       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
28484       break;
28485     }
28486
28487     // In any sort of PIC mode addresses need to be computed at runtime by
28488     // adding in a register or some sort of table lookup.  These can't
28489     // be used as immediates.
28490     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
28491       return;
28492
28493     // If we are in non-pic codegen mode, we allow the address of a global (with
28494     // an optional displacement) to be used with 'i'.
28495     GlobalAddressSDNode *GA = nullptr;
28496     int64_t Offset = 0;
28497
28498     // Match either (GA), (GA+C), (GA+C1+C2), etc.
28499     while (1) {
28500       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
28501         Offset += GA->getOffset();
28502         break;
28503       } else if (Op.getOpcode() == ISD::ADD) {
28504         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28505           Offset += C->getZExtValue();
28506           Op = Op.getOperand(0);
28507           continue;
28508         }
28509       } else if (Op.getOpcode() == ISD::SUB) {
28510         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28511           Offset += -C->getZExtValue();
28512           Op = Op.getOperand(0);
28513           continue;
28514         }
28515       }
28516
28517       // Otherwise, this isn't something we can handle, reject it.
28518       return;
28519     }
28520
28521     const GlobalValue *GV = GA->getGlobal();
28522     // If we require an extra load to get this address, as in PIC mode, we
28523     // can't accept it.
28524     if (isGlobalStubReference(
28525             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
28526       return;
28527
28528     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
28529                                         GA->getValueType(0), Offset);
28530     break;
28531   }
28532   }
28533
28534   if (Result.getNode()) {
28535     Ops.push_back(Result);
28536     return;
28537   }
28538   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
28539 }
28540
28541 std::pair<unsigned, const TargetRegisterClass *>
28542 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
28543                                                 StringRef Constraint,
28544                                                 MVT VT) const {
28545   // First, see if this is a constraint that directly corresponds to an LLVM
28546   // register class.
28547   if (Constraint.size() == 1) {
28548     // GCC Constraint Letters
28549     switch (Constraint[0]) {
28550     default: break;
28551       // TODO: Slight differences here in allocation order and leaving
28552       // RIP in the class. Do they matter any more here than they do
28553       // in the normal allocation?
28554     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
28555       if (Subtarget->is64Bit()) {
28556         if (VT == MVT::i32 || VT == MVT::f32)
28557           return std::make_pair(0U, &X86::GR32RegClass);
28558         if (VT == MVT::i16)
28559           return std::make_pair(0U, &X86::GR16RegClass);
28560         if (VT == MVT::i8 || VT == MVT::i1)
28561           return std::make_pair(0U, &X86::GR8RegClass);
28562         if (VT == MVT::i64 || VT == MVT::f64)
28563           return std::make_pair(0U, &X86::GR64RegClass);
28564         break;
28565       }
28566       // 32-bit fallthrough
28567     case 'Q':   // Q_REGS
28568       if (VT == MVT::i32 || VT == MVT::f32)
28569         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
28570       if (VT == MVT::i16)
28571         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
28572       if (VT == MVT::i8 || VT == MVT::i1)
28573         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
28574       if (VT == MVT::i64)
28575         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
28576       break;
28577     case 'r':   // GENERAL_REGS
28578     case 'l':   // INDEX_REGS
28579       if (VT == MVT::i8 || VT == MVT::i1)
28580         return std::make_pair(0U, &X86::GR8RegClass);
28581       if (VT == MVT::i16)
28582         return std::make_pair(0U, &X86::GR16RegClass);
28583       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
28584         return std::make_pair(0U, &X86::GR32RegClass);
28585       return std::make_pair(0U, &X86::GR64RegClass);
28586     case 'R':   // LEGACY_REGS
28587       if (VT == MVT::i8 || VT == MVT::i1)
28588         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
28589       if (VT == MVT::i16)
28590         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
28591       if (VT == MVT::i32 || !Subtarget->is64Bit())
28592         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
28593       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
28594     case 'f':  // FP Stack registers.
28595       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
28596       // value to the correct fpstack register class.
28597       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
28598         return std::make_pair(0U, &X86::RFP32RegClass);
28599       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
28600         return std::make_pair(0U, &X86::RFP64RegClass);
28601       return std::make_pair(0U, &X86::RFP80RegClass);
28602     case 'y':   // MMX_REGS if MMX allowed.
28603       if (!Subtarget->hasMMX()) break;
28604       return std::make_pair(0U, &X86::VR64RegClass);
28605     case 'Y':   // SSE_REGS if SSE2 allowed
28606       if (!Subtarget->hasSSE2()) break;
28607       // FALL THROUGH.
28608     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
28609       if (!Subtarget->hasSSE1()) break;
28610
28611       switch (VT.SimpleTy) {
28612       default: break;
28613       // Scalar SSE types.
28614       case MVT::f32:
28615       case MVT::i32:
28616         return std::make_pair(0U, &X86::FR32RegClass);
28617       case MVT::f64:
28618       case MVT::i64:
28619         return std::make_pair(0U, &X86::FR64RegClass);
28620       // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28621       // Vector types.
28622       case MVT::v16i8:
28623       case MVT::v8i16:
28624       case MVT::v4i32:
28625       case MVT::v2i64:
28626       case MVT::v4f32:
28627       case MVT::v2f64:
28628         return std::make_pair(0U, &X86::VR128RegClass);
28629       // AVX types.
28630       case MVT::v32i8:
28631       case MVT::v16i16:
28632       case MVT::v8i32:
28633       case MVT::v4i64:
28634       case MVT::v8f32:
28635       case MVT::v4f64:
28636         return std::make_pair(0U, &X86::VR256RegClass);
28637       case MVT::v8f64:
28638       case MVT::v16f32:
28639       case MVT::v16i32:
28640       case MVT::v8i64:
28641         return std::make_pair(0U, &X86::VR512RegClass);
28642       }
28643       break;
28644     }
28645   }
28646
28647   // Use the default implementation in TargetLowering to convert the register
28648   // constraint into a member of a register class.
28649   std::pair<unsigned, const TargetRegisterClass*> Res;
28650   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28651
28652   // Not found as a standard register?
28653   if (!Res.second) {
28654     // Map st(0) -> st(7) -> ST0
28655     if (Constraint.size() == 7 && Constraint[0] == '{' &&
28656         tolower(Constraint[1]) == 's' &&
28657         tolower(Constraint[2]) == 't' &&
28658         Constraint[3] == '(' &&
28659         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28660         Constraint[5] == ')' &&
28661         Constraint[6] == '}') {
28662
28663       Res.first = X86::FP0+Constraint[4]-'0';
28664       Res.second = &X86::RFP80RegClass;
28665       return Res;
28666     }
28667
28668     // GCC allows "st(0)" to be called just plain "st".
28669     if (StringRef("{st}").equals_lower(Constraint)) {
28670       Res.first = X86::FP0;
28671       Res.second = &X86::RFP80RegClass;
28672       return Res;
28673     }
28674
28675     // flags -> EFLAGS
28676     if (StringRef("{flags}").equals_lower(Constraint)) {
28677       Res.first = X86::EFLAGS;
28678       Res.second = &X86::CCRRegClass;
28679       return Res;
28680     }
28681
28682     // 'A' means EAX + EDX.
28683     if (Constraint == "A") {
28684       Res.first = X86::EAX;
28685       Res.second = &X86::GR32_ADRegClass;
28686       return Res;
28687     }
28688     return Res;
28689   }
28690
28691   // Otherwise, check to see if this is a register class of the wrong value
28692   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28693   // turn into {ax},{dx}.
28694   // MVT::Other is used to specify clobber names.
28695   if (Res.second->hasType(VT) || VT == MVT::Other)
28696     return Res;   // Correct type already, nothing to do.
28697
28698   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28699   // return "eax". This should even work for things like getting 64bit integer
28700   // registers when given an f64 type.
28701   const TargetRegisterClass *Class = Res.second;
28702   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28703       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28704     unsigned Size = VT.getSizeInBits();
28705     if (Size == 1) Size = 8;
28706     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
28707     if (DestReg > 0) {
28708       Res.first = DestReg;
28709       Res.second = Size == 8 ? &X86::GR8RegClass
28710                  : Size == 16 ? &X86::GR16RegClass
28711                  : Size == 32 ? &X86::GR32RegClass
28712                  : &X86::GR64RegClass;
28713       assert(Res.second->contains(Res.first) && "Register in register class");
28714     } else {
28715       // No register found/type mismatch.
28716       Res.first = 0;
28717       Res.second = nullptr;
28718     }
28719   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28720              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28721              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28722              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28723              Class == &X86::VR512RegClass) {
28724     // Handle references to XMM physical registers that got mapped into the
28725     // wrong class.  This can happen with constraints like {xmm0} where the
28726     // target independent register mapper will just pick the first match it can
28727     // find, ignoring the required type.
28728
28729     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28730     if (VT == MVT::f32 || VT == MVT::i32)
28731       Res.second = &X86::FR32RegClass;
28732     else if (VT == MVT::f64 || VT == MVT::i64)
28733       Res.second = &X86::FR64RegClass;
28734     else if (X86::VR128RegClass.hasType(VT))
28735       Res.second = &X86::VR128RegClass;
28736     else if (X86::VR256RegClass.hasType(VT))
28737       Res.second = &X86::VR256RegClass;
28738     else if (X86::VR512RegClass.hasType(VT))
28739       Res.second = &X86::VR512RegClass;
28740     else {
28741       // Type mismatch and not a clobber: Return an error;
28742       Res.first = 0;
28743       Res.second = nullptr;
28744     }
28745   }
28746
28747   return Res;
28748 }
28749
28750 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28751                                             const AddrMode &AM, Type *Ty,
28752                                             unsigned AS) const {
28753   // Scaling factors are not free at all.
28754   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28755   // will take 2 allocations in the out of order engine instead of 1
28756   // for plain addressing mode, i.e. inst (reg1).
28757   // E.g.,
28758   // vaddps (%rsi,%drx), %ymm0, %ymm1
28759   // Requires two allocations (one for the load, one for the computation)
28760   // whereas:
28761   // vaddps (%rsi), %ymm0, %ymm1
28762   // Requires just 1 allocation, i.e., freeing allocations for other operations
28763   // and having less micro operations to execute.
28764   //
28765   // For some X86 architectures, this is even worse because for instance for
28766   // stores, the complex addressing mode forces the instruction to use the
28767   // "load" ports instead of the dedicated "store" port.
28768   // E.g., on Haswell:
28769   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28770   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28771   if (isLegalAddressingMode(DL, AM, Ty, AS))
28772     // Scale represents reg2 * scale, thus account for 1
28773     // as soon as we use a second register.
28774     return AM.Scale != 0;
28775   return -1;
28776 }
28777
28778 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28779   // Integer division on x86 is expensive. However, when aggressively optimizing
28780   // for code size, we prefer to use a div instruction, as it is usually smaller
28781   // than the alternative sequence.
28782   // The exception to this is vector division. Since x86 doesn't have vector
28783   // integer division, leaving the division as-is is a loss even in terms of
28784   // size, because it will have to be scalarized, while the alternative code
28785   // sequence can be performed in vector form.
28786   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28787                                    Attribute::MinSize);
28788   return OptSize && !VT.isVector();
28789 }