Merging r257925, r257929, r257930, and r257997:
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86ShuffleDecodeConstantPool.h"
22 #include "X86TargetMachine.h"
23 #include "X86TargetObjectFile.h"
24 #include "llvm/ADT/SmallBitVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/WinEHFuncInfo.h"
38 #include "llvm/IR/CallSite.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalAlias.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/MC/MCAsmInfo.h"
48 #include "llvm/MC/MCContext.h"
49 #include "llvm/MC/MCExpr.h"
50 #include "llvm/MC/MCSymbol.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Target/TargetOptions.h"
56 #include "X86IntrinsicsInfo.h"
57 #include <bitset>
58 #include <numeric>
59 #include <cctype>
60 using namespace llvm;
61
62 #define DEBUG_TYPE "x86-isel"
63
64 STATISTIC(NumTailCalls, "Number of tail calls");
65
66 static cl::opt<bool> ExperimentalVectorWideningLegalization(
67     "x86-experimental-vector-widening-legalization", cl::init(false),
68     cl::desc("Enable an experimental vector type legalization through widening "
69              "rather than promotion."),
70     cl::Hidden);
71
72 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
73                                      const X86Subtarget &STI)
74     : TargetLowering(TM), Subtarget(&STI) {
75   X86ScalarSSEf64 = Subtarget->hasSSE2();
76   X86ScalarSSEf32 = Subtarget->hasSSE1();
77   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
78
79   // Set up the TargetLowering object.
80
81   // X86 is weird. It always uses i8 for shift amounts and setcc results.
82   setBooleanContents(ZeroOrOneBooleanContent);
83   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
84   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
85
86   // For 64-bit, since we have so many registers, use the ILP scheduler.
87   // For 32-bit, use the register pressure specific scheduling.
88   // For Atom, always use ILP scheduling.
89   if (Subtarget->isAtom())
90     setSchedulingPreference(Sched::ILP);
91   else if (Subtarget->is64Bit())
92     setSchedulingPreference(Sched::ILP);
93   else
94     setSchedulingPreference(Sched::RegPressure);
95   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
96   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
97
98   // Bypass expensive divides on Atom when compiling with O2.
99   if (TM.getOptLevel() >= CodeGenOpt::Default) {
100     if (Subtarget->hasSlowDivide32())
101       addBypassSlowDiv(32, 8);
102     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
103       addBypassSlowDiv(64, 16);
104   }
105
106   if (Subtarget->isTargetKnownWindowsMSVC()) {
107     // Setup Windows compiler runtime calls.
108     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
109     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
110     setLibcallName(RTLIB::SREM_I64, "_allrem");
111     setLibcallName(RTLIB::UREM_I64, "_aullrem");
112     setLibcallName(RTLIB::MUL_I64, "_allmul");
113     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
117     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
118   }
119
120   if (Subtarget->isTargetDarwin()) {
121     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
122     setUseUnderscoreSetJmp(false);
123     setUseUnderscoreLongJmp(false);
124   } else if (Subtarget->isTargetWindowsGNU()) {
125     // MS runtime is weird: it exports _setjmp, but longjmp!
126     setUseUnderscoreSetJmp(true);
127     setUseUnderscoreLongJmp(false);
128   } else {
129     setUseUnderscoreSetJmp(true);
130     setUseUnderscoreLongJmp(true);
131   }
132
133   // Set up the register classes.
134   addRegisterClass(MVT::i8, &X86::GR8RegClass);
135   addRegisterClass(MVT::i16, &X86::GR16RegClass);
136   addRegisterClass(MVT::i32, &X86::GR32RegClass);
137   if (Subtarget->is64Bit())
138     addRegisterClass(MVT::i64, &X86::GR64RegClass);
139
140   for (MVT VT : MVT::integer_valuetypes())
141     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142
143   // We don't accept any truncstore of integer registers.
144   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
146   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
147   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
148   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
149   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
150
151   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
152
153   // SETOEQ and SETUNE require checking two conditions.
154   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
155   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
156   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
158   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
159   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
160
161   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
162   // operation.
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
164   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
165   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
166
167   if (Subtarget->is64Bit()) {
168     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
169       // f32/f64 are legal, f80 is custom.
170       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
171     else
172       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
173     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
174   } else if (!Subtarget->useSoftFloat()) {
175     // We have an algorithm for SSE2->double, and we turn this into a
176     // 64-bit FILD followed by conditional FADD for other targets.
177     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
178     // We have an algorithm for SSE2, and we turn this into a 64-bit
179     // FILD or VCVTUSI2SS/SD for other targets.
180     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
181   }
182
183   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
184   // this operation.
185   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
186   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
187
188   if (!Subtarget->useSoftFloat()) {
189     // SSE has no i16 to fp conversion, only i32
190     if (X86ScalarSSEf32) {
191       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
192       // f32 and f64 cases are Legal, f80 case is not
193       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
194     } else {
195       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
196       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
197     }
198   } else {
199     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
200     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
201   }
202
203   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
204   // this operation.
205   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
206   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
207
208   if (!Subtarget->useSoftFloat()) {
209     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
210     // are Legal, f80 is custom lowered.
211     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
212     setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
213
214     if (X86ScalarSSEf32) {
215       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
216       // f32 and f64 cases are Legal, f80 case is not
217       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
218     } else {
219       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
220       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
221     }
222   } else {
223     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Expand);
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Expand);
226   }
227
228   // Handle FP_TO_UINT by promoting the destination to a larger signed
229   // conversion.
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
232   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
233
234   if (Subtarget->is64Bit()) {
235     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
236       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
237       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
238       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
239     } else {
240       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
241       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
242     }
243   } else if (!Subtarget->useSoftFloat()) {
244     // Since AVX is a superset of SSE3, only check for SSE here.
245     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246       // Expand FP_TO_UINT into a select.
247       // FIXME: We would like to use a Custom expander here eventually to do
248       // the optimal thing for SSE vs. the default expansion in the legalizer.
249       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
250     else
251       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
252       // With SSE3 we can use fisttpll to convert to a signed i64; without
253       // SSE, we're stuck with a fistpll.
254       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
255
256     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
257   }
258
259   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
260   if (!X86ScalarSSEf64) {
261     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
262     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
263     if (Subtarget->is64Bit()) {
264       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
265       // Without SSE, i64->f64 goes through memory.
266       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
267     }
268   } else if (!Subtarget->is64Bit())
269     setOperationAction(ISD::BITCAST      , MVT::i64  , Custom);
270
271   // Scalar integer divide and remainder are lowered to use operations that
272   // produce two results, to match the available instructions. This exposes
273   // the two-result form to trivial CSE, which is able to combine x/y and x%y
274   // into a single instruction.
275   //
276   // Scalar integer multiply-high is also lowered to use two-result
277   // operations, to match the available instructions. However, plain multiply
278   // (low) operations are left as Legal, as there are single-result
279   // instructions for this in x86. Using the two-result multiply instructions
280   // when both high and low results are needed must be arranged by dagcombine.
281   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
282     setOperationAction(ISD::MULHS, VT, Expand);
283     setOperationAction(ISD::MULHU, VT, Expand);
284     setOperationAction(ISD::SDIV, VT, Expand);
285     setOperationAction(ISD::UDIV, VT, Expand);
286     setOperationAction(ISD::SREM, VT, Expand);
287     setOperationAction(ISD::UREM, VT, Expand);
288
289     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
290     setOperationAction(ISD::ADDC, VT, Custom);
291     setOperationAction(ISD::ADDE, VT, Custom);
292     setOperationAction(ISD::SUBC, VT, Custom);
293     setOperationAction(ISD::SUBE, VT, Custom);
294   }
295
296   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
297   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
298   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
299   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::f128,  Expand);
302   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
303   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
305   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::f128,  Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
313   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
314   if (Subtarget->is64Bit())
315     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
316   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
318   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
319   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
320
321   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
322     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
323     // is. We should promote the value to 64-bits to solve this.
324     // This is what the CRT headers do - `fmodf` is an inline header
325     // function casting to f64 and calling `fmod`.
326     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
327   } else {
328     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
329   }
330
331   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
332   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
333   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
334
335   // Promote the i8 variants and force them on up to i32 which has a shorter
336   // encoding.
337   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
338   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
339   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
340   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
341   if (Subtarget->hasBMI()) {
342     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
343     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
344     if (Subtarget->is64Bit())
345       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
346   } else {
347     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
348     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
349     if (Subtarget->is64Bit())
350       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
351   }
352
353   if (Subtarget->hasLZCNT()) {
354     // When promoting the i8 variants, force them to i32 for a shorter
355     // encoding.
356     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
357     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
358     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
359     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
361     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
362     if (Subtarget->is64Bit())
363       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
364   } else {
365     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
366     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
367     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
368     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
369     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
370     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
371     if (Subtarget->is64Bit()) {
372       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
373       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
374     }
375   }
376
377   // Special handling for half-precision floating point conversions.
378   // If we don't have F16C support, then lower half float conversions
379   // into library calls.
380   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
381     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
382     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
383   }
384
385   // There's never any support for operations beyond MVT::f32.
386   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
387   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
388   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
389   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
390
391   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
392   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
393   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
394   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
395   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
396   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
397
398   if (Subtarget->hasPOPCNT()) {
399     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
400   } else {
401     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
402     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
403     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
404     if (Subtarget->is64Bit())
405       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
406   }
407
408   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
409
410   if (!Subtarget->hasMOVBE())
411     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
412
413   // These should be promoted to a larger select which is supported.
414   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
415   // X86 wants to expand cmov itself.
416   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
417   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
418   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
419   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
420   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
421   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
422   setOperationAction(ISD::SELECT          , MVT::f128 , Custom);
423   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
424   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
425   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
427   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
428   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
429   setOperationAction(ISD::SETCC           , MVT::f128 , Custom);
430   setOperationAction(ISD::SETCCE          , MVT::i8   , Custom);
431   setOperationAction(ISD::SETCCE          , MVT::i16  , Custom);
432   setOperationAction(ISD::SETCCE          , MVT::i32  , Custom);
433   if (Subtarget->is64Bit()) {
434     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
435     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
436     setOperationAction(ISD::SETCCE        , MVT::i64  , Custom);
437   }
438   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
439   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
440   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
441   // support continuation, user-level threading, and etc.. As a result, no
442   // other SjLj exception interfaces are implemented and please don't build
443   // your own exception handling based on them.
444   // LLVM/Clang supports zero-cost DWARF exception handling.
445   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
446   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
447
448   // Darwin ABI issue.
449   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
450   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
451   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
452   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
453   if (Subtarget->is64Bit())
454     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
455   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
456   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
457   if (Subtarget->is64Bit()) {
458     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
459     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
460     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
461     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
462     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
463   }
464   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
465   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
466   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
467   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
468   if (Subtarget->is64Bit()) {
469     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
470     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
471     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
472   }
473
474   if (Subtarget->hasSSE1())
475     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
476
477   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
478
479   // Expand certain atomics
480   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
481     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
482     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
483     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
484   }
485
486   if (Subtarget->hasCmpxchg16b()) {
487     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
488   }
489
490   // FIXME - use subtarget debug flags
491   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
492       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
493     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
494   }
495
496   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
497   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
498
499   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
500   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
501
502   setOperationAction(ISD::TRAP, MVT::Other, Legal);
503   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
504
505   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
506   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
507   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
508   if (Subtarget->is64Bit()) {
509     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
510     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
511   } else {
512     // TargetInfo::CharPtrBuiltinVaList
513     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
514     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
515   }
516
517   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
518   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
519
520   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
521
522   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
523   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
524   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
525
526   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
527     // f32 and f64 use SSE.
528     // Set up the FP register classes.
529     addRegisterClass(MVT::f32, &X86::FR32RegClass);
530     addRegisterClass(MVT::f64, &X86::FR64RegClass);
531
532     // Use ANDPD to simulate FABS.
533     setOperationAction(ISD::FABS , MVT::f64, Custom);
534     setOperationAction(ISD::FABS , MVT::f32, Custom);
535
536     // Use XORP to simulate FNEG.
537     setOperationAction(ISD::FNEG , MVT::f64, Custom);
538     setOperationAction(ISD::FNEG , MVT::f32, Custom);
539
540     // Use ANDPD and ORPD to simulate FCOPYSIGN.
541     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
542     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
543
544     // Lower this to FGETSIGNx86 plus an AND.
545     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
546     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
547
548     // We don't support sin/cos/fmod
549     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
550     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
551     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
552     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
553     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
554     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
555
556     // Expand FP immediates into loads from the stack, except for the special
557     // cases we handle.
558     addLegalFPImmediate(APFloat(+0.0)); // xorpd
559     addLegalFPImmediate(APFloat(+0.0f)); // xorps
560   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
561     // Use SSE for f32, x87 for f64.
562     // Set up the FP register classes.
563     addRegisterClass(MVT::f32, &X86::FR32RegClass);
564     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
565
566     // Use ANDPS to simulate FABS.
567     setOperationAction(ISD::FABS , MVT::f32, Custom);
568
569     // Use XORP to simulate FNEG.
570     setOperationAction(ISD::FNEG , MVT::f32, Custom);
571
572     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
573
574     // Use ANDPS and ORPS to simulate FCOPYSIGN.
575     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
576     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
577
578     // We don't support sin/cos/fmod
579     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
580     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
581     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
582
583     // Special cases we handle for FP constants.
584     addLegalFPImmediate(APFloat(+0.0f)); // xorps
585     addLegalFPImmediate(APFloat(+0.0)); // FLD0
586     addLegalFPImmediate(APFloat(+1.0)); // FLD1
587     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
588     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
589
590     if (!TM.Options.UnsafeFPMath) {
591       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
592       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
593       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
594     }
595   } else if (!Subtarget->useSoftFloat()) {
596     // f32 and f64 in x87.
597     // Set up the FP register classes.
598     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
599     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
600
601     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
602     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
603     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
604     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
605
606     if (!TM.Options.UnsafeFPMath) {
607       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
608       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
609       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
610       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
611       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
612       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
613     }
614     addLegalFPImmediate(APFloat(+0.0)); // FLD0
615     addLegalFPImmediate(APFloat(+1.0)); // FLD1
616     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
617     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
618     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
619     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
620     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
621     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
622   }
623
624   // We don't support FMA.
625   setOperationAction(ISD::FMA, MVT::f64, Expand);
626   setOperationAction(ISD::FMA, MVT::f32, Expand);
627
628   // Long double always uses X87, except f128 in MMX.
629   if (!Subtarget->useSoftFloat()) {
630     if (Subtarget->is64Bit() && Subtarget->hasMMX()) {
631       addRegisterClass(MVT::f128, &X86::FR128RegClass);
632       ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
633       setOperationAction(ISD::FABS , MVT::f128, Custom);
634       setOperationAction(ISD::FNEG , MVT::f128, Custom);
635       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
636     }
637
638     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
639     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
640     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
641     {
642       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
643       addLegalFPImmediate(TmpFlt);  // FLD0
644       TmpFlt.changeSign();
645       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
646
647       bool ignored;
648       APFloat TmpFlt2(+1.0);
649       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
650                       &ignored);
651       addLegalFPImmediate(TmpFlt2);  // FLD1
652       TmpFlt2.changeSign();
653       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
654     }
655
656     if (!TM.Options.UnsafeFPMath) {
657       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
658       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
659       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
660     }
661
662     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
663     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
664     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
665     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
666     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
667     setOperationAction(ISD::FMA, MVT::f80, Expand);
668   }
669
670   // Always use a library call for pow.
671   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
672   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
673   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
674
675   setOperationAction(ISD::FLOG, MVT::f80, Expand);
676   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
677   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
678   setOperationAction(ISD::FEXP, MVT::f80, Expand);
679   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
680   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
681   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
682
683   // First set operation action for all vector types to either promote
684   // (for widening) or expand (for scalarization). Then we will selectively
685   // turn on ones that can be effectively codegen'd.
686   for (MVT VT : MVT::vector_valuetypes()) {
687     setOperationAction(ISD::ADD , VT, Expand);
688     setOperationAction(ISD::SUB , VT, Expand);
689     setOperationAction(ISD::FADD, VT, Expand);
690     setOperationAction(ISD::FNEG, VT, Expand);
691     setOperationAction(ISD::FSUB, VT, Expand);
692     setOperationAction(ISD::MUL , VT, Expand);
693     setOperationAction(ISD::FMUL, VT, Expand);
694     setOperationAction(ISD::SDIV, VT, Expand);
695     setOperationAction(ISD::UDIV, VT, Expand);
696     setOperationAction(ISD::FDIV, VT, Expand);
697     setOperationAction(ISD::SREM, VT, Expand);
698     setOperationAction(ISD::UREM, VT, Expand);
699     setOperationAction(ISD::LOAD, VT, Expand);
700     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
701     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
702     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
703     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
704     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
705     setOperationAction(ISD::FABS, VT, Expand);
706     setOperationAction(ISD::FSIN, VT, Expand);
707     setOperationAction(ISD::FSINCOS, VT, Expand);
708     setOperationAction(ISD::FCOS, VT, Expand);
709     setOperationAction(ISD::FSINCOS, VT, Expand);
710     setOperationAction(ISD::FREM, VT, Expand);
711     setOperationAction(ISD::FMA,  VT, Expand);
712     setOperationAction(ISD::FPOWI, VT, Expand);
713     setOperationAction(ISD::FSQRT, VT, Expand);
714     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
715     setOperationAction(ISD::FFLOOR, VT, Expand);
716     setOperationAction(ISD::FCEIL, VT, Expand);
717     setOperationAction(ISD::FTRUNC, VT, Expand);
718     setOperationAction(ISD::FRINT, VT, Expand);
719     setOperationAction(ISD::FNEARBYINT, VT, Expand);
720     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
721     setOperationAction(ISD::MULHS, VT, Expand);
722     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
723     setOperationAction(ISD::MULHU, VT, Expand);
724     setOperationAction(ISD::SDIVREM, VT, Expand);
725     setOperationAction(ISD::UDIVREM, VT, Expand);
726     setOperationAction(ISD::FPOW, VT, Expand);
727     setOperationAction(ISD::CTPOP, VT, Expand);
728     setOperationAction(ISD::CTTZ, VT, Expand);
729     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
730     setOperationAction(ISD::CTLZ, VT, Expand);
731     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
732     setOperationAction(ISD::SHL, VT, Expand);
733     setOperationAction(ISD::SRA, VT, Expand);
734     setOperationAction(ISD::SRL, VT, Expand);
735     setOperationAction(ISD::ROTL, VT, Expand);
736     setOperationAction(ISD::ROTR, VT, Expand);
737     setOperationAction(ISD::BSWAP, VT, Expand);
738     setOperationAction(ISD::SETCC, VT, Expand);
739     setOperationAction(ISD::FLOG, VT, Expand);
740     setOperationAction(ISD::FLOG2, VT, Expand);
741     setOperationAction(ISD::FLOG10, VT, Expand);
742     setOperationAction(ISD::FEXP, VT, Expand);
743     setOperationAction(ISD::FEXP2, VT, Expand);
744     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
745     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
746     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
747     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
748     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
749     setOperationAction(ISD::TRUNCATE, VT, Expand);
750     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
751     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
752     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
753     setOperationAction(ISD::VSELECT, VT, Expand);
754     setOperationAction(ISD::SELECT_CC, VT, Expand);
755     for (MVT InnerVT : MVT::vector_valuetypes()) {
756       setTruncStoreAction(InnerVT, VT, Expand);
757
758       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
759       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
760
761       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
762       // types, we have to deal with them whether we ask for Expansion or not.
763       // Setting Expand causes its own optimisation problems though, so leave
764       // them legal.
765       if (VT.getVectorElementType() == MVT::i1)
766         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
767
768       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
769       // split/scalarized right now.
770       if (VT.getVectorElementType() == MVT::f16)
771         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
772     }
773   }
774
775   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
776   // with -msoft-float, disable use of MMX as well.
777   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
778     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
779     // No operations on x86mmx supported, everything uses intrinsics.
780   }
781
782   // MMX-sized vectors (other than x86mmx) are expected to be expanded
783   // into smaller operations.
784   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
785     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
786     setOperationAction(ISD::AND,                MMXTy,      Expand);
787     setOperationAction(ISD::OR,                 MMXTy,      Expand);
788     setOperationAction(ISD::XOR,                MMXTy,      Expand);
789     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
790     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
791     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
792   }
793   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
794
795   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
796     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
797
798     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
801     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
802     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
803     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
804     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
805     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
806     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
807     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
808     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
809     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
810     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
811     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
812   }
813
814   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
815     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
816
817     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
818     // registers cannot be used even for integer operations.
819     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
820     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
821     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
822     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
823
824     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
825     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
826     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
827     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
828     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
829     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
830     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
831     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
832     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
833     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
834     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
835     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
836     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
837     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
838     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
839     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
840     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
841     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
842     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
843     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
844     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
845     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
846     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
847
848     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
849     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
850     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
851     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
852
853     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
854     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
855     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
856     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
857
858     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
859     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
860     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
861     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
862     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
863
864     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
865     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
866     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
867     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
868
869     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
870     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
871     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
872     // ISD::CTTZ v2i64 - scalarization is faster.
873     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
874     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
875     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
876     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
877
878     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
879     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
880       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
881       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
882       setOperationAction(ISD::VSELECT,            VT, Custom);
883       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
884     }
885
886     // We support custom legalizing of sext and anyext loads for specific
887     // memory vector types which we can load as a scalar (or sequence of
888     // scalars) and extend in-register to a legal 128-bit vector type. For sext
889     // loads these must work with a single scalar load.
890     for (MVT VT : MVT::integer_vector_valuetypes()) {
891       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
892       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
893       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
894       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
895       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
896       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
897       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
898       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
899       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
900     }
901
902     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
903     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
904     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
905     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
906     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
907     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
908     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
909     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
910
911     if (Subtarget->is64Bit()) {
912       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
913       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
914     }
915
916     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
917     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
918       setOperationAction(ISD::AND,    VT, Promote);
919       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
920       setOperationAction(ISD::OR,     VT, Promote);
921       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
922       setOperationAction(ISD::XOR,    VT, Promote);
923       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
924       setOperationAction(ISD::LOAD,   VT, Promote);
925       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
926       setOperationAction(ISD::SELECT, VT, Promote);
927       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
928     }
929
930     // Custom lower v2i64 and v2f64 selects.
931     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
932     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
933     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
934     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
935
936     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
937     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
938
939     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
940
941     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
942     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
943     // As there is no 64-bit GPR available, we need build a special custom
944     // sequence to convert from v2i32 to v2f32.
945     if (!Subtarget->is64Bit())
946       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
947
948     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
949     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
950
951     for (MVT VT : MVT::fp_vector_valuetypes())
952       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
953
954     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
955     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
956     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
957   }
958
959   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
960     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
961       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
962       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
963       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
964       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
965       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
966     }
967
968     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
969     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
970     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
971     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
972     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
973     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
974     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
975     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
976
977     // FIXME: Do we need to handle scalar-to-vector here?
978     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
979
980     // We directly match byte blends in the backend as they match the VSELECT
981     // condition form.
982     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
983
984     // SSE41 brings specific instructions for doing vector sign extend even in
985     // cases where we don't have SRA.
986     for (MVT VT : MVT::integer_vector_valuetypes()) {
987       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
988       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
989       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
990     }
991
992     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
993     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
994     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
995     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
996     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
997     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
998     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
999
1000     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1001     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1002     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1003     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1004     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1005     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1006
1007     // i8 and i16 vectors are custom because the source register and source
1008     // source memory operand types are not the same width.  f32 vectors are
1009     // custom since the immediate controlling the insert encodes additional
1010     // information.
1011     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1012     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1013     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1014     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1015
1016     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1017     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1018     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1019     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1020
1021     // FIXME: these should be Legal, but that's only for the case where
1022     // the index is constant.  For now custom expand to deal with that.
1023     if (Subtarget->is64Bit()) {
1024       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1025       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1026     }
1027   }
1028
1029   if (Subtarget->hasSSE2()) {
1030     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1031     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1032     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1033
1034     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1035     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1036
1037     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1038     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1039
1040     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1041     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1042
1043     // In the customized shift lowering, the legal cases in AVX2 will be
1044     // recognized.
1045     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1046     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1047
1048     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1049     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1050
1051     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1052     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1053   }
1054
1055   if (Subtarget->hasXOP()) {
1056     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1057     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1058     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1059     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1060     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1061     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1062     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1063     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1064   }
1065
1066   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1067     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1068     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1069     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1070     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1071     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1072     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1073
1074     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1075     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1076     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1077
1078     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1079     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1080     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1081     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1082     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1083     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1084     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1085     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1086     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1087     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1088     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1089     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1090
1091     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1092     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1093     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1094     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1095     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1096     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1097     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1098     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1099     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1100     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1101     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1102     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1103
1104     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1105     // even though v8i16 is a legal type.
1106     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1107     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1108     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1109
1110     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1111     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1112     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1113
1114     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1115     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1116
1117     for (MVT VT : MVT::fp_vector_valuetypes())
1118       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1119
1120     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1121     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1122
1123     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1124     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1125
1126     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1127     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1128
1129     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1130     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1131     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1132     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1133
1134     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1135     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1136     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1137
1138     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1139     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1140     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1141     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1142     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1143     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1144     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1145     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1146     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1147     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1148     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1149     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1150
1151     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1152     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1153     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1154     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1155
1156     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1157     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1158     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1159     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1160     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1161     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1162     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1163     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1164
1165     if (Subtarget->hasAnyFMA()) {
1166       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1167       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1168       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1169       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1170       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1171       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1172     }
1173
1174     if (Subtarget->hasInt256()) {
1175       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1176       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1177       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1178       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1179
1180       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1181       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1182       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1183       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1184
1185       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1186       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1187       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1188       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1189
1190       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1191       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1192       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1193       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1194
1195       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1196       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1197       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1198       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1199       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1200       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1201       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1202       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1203       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1204       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1205       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1206       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1207
1208       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1209       // when we have a 256bit-wide blend with immediate.
1210       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1211
1212       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1213       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1214       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1215       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1216       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1217       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1218       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1219
1220       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1221       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1222       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1223       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1224       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1225       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1226     } else {
1227       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1228       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1229       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1230       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1231
1232       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1233       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1234       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1235       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1236
1237       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1238       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1239       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1240       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1241
1242       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1243       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1244       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1245       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1246       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1247       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1248       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1249       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1250       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1251       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1252       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1253       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1254     }
1255
1256     // In the customized shift lowering, the legal cases in AVX2 will be
1257     // recognized.
1258     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1259     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1260
1261     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1262     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1263
1264     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1265     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1266
1267     // Custom lower several nodes for 256-bit types.
1268     for (MVT VT : MVT::vector_valuetypes()) {
1269       if (VT.getScalarSizeInBits() >= 32) {
1270         setOperationAction(ISD::MLOAD,  VT, Legal);
1271         setOperationAction(ISD::MSTORE, VT, Legal);
1272       }
1273       // Extract subvector is special because the value type
1274       // (result) is 128-bit but the source is 256-bit wide.
1275       if (VT.is128BitVector()) {
1276         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1277       }
1278       // Do not attempt to custom lower other non-256-bit vectors
1279       if (!VT.is256BitVector())
1280         continue;
1281
1282       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1283       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1284       setOperationAction(ISD::VSELECT,            VT, Custom);
1285       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1286       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1287       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1288       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1289       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1290     }
1291
1292     if (Subtarget->hasInt256())
1293       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1294
1295     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1296     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1297       setOperationAction(ISD::AND,    VT, Promote);
1298       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1299       setOperationAction(ISD::OR,     VT, Promote);
1300       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1301       setOperationAction(ISD::XOR,    VT, Promote);
1302       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1303       setOperationAction(ISD::LOAD,   VT, Promote);
1304       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1305       setOperationAction(ISD::SELECT, VT, Promote);
1306       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1307     }
1308   }
1309
1310   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1311     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1312     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1313     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1314     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1315
1316     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1317     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1318     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1319
1320     for (MVT VT : MVT::fp_vector_valuetypes())
1321       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1322
1323     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1324     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1325     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1326     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1327     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1328     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1329     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1330     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1331     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1332     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1333     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1334     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1335
1336     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1337     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1338     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1339     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1340     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1341     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1342     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1343     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1344     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1345     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1346     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1347     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1348     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1349     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1350
1351     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1352     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1353     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1354     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1355     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1356     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1357     setOperationAction(ISD::FABS,               MVT::v16f32, Custom);
1358
1359     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1360     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1361     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1362     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1363     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1364     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1365     setOperationAction(ISD::FABS,               MVT::v8f64, Custom);
1366     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1367     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1368
1369     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1370     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1371     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1372     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1373     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1374     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1375     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1376     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1377     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1378     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1379     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1380     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1381     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1382     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1383     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1384     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1385
1386     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1387     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1388     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1389     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1390     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1391     if (Subtarget->hasVLX()){
1392       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1393       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1394       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1395       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1396       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1397
1398       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1399       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1400       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1401       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1402       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1403     } else {
1404       setOperationAction(ISD::MLOAD,    MVT::v8i32, Custom);
1405       setOperationAction(ISD::MLOAD,    MVT::v8f32, Custom);
1406       setOperationAction(ISD::MSTORE,   MVT::v8i32, Custom);
1407       setOperationAction(ISD::MSTORE,   MVT::v8f32, Custom);
1408     }
1409     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1410     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1411     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1412     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1413     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1414     if (Subtarget->hasDQI()) {
1415       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1416       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1417
1418       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1419       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1420       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1421       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1422       if (Subtarget->hasVLX()) {
1423         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1424         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1425         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1426         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1427         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1428         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1429         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1430         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1431       }
1432     }
1433     if (Subtarget->hasVLX()) {
1434       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1435       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1436       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1437       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1438       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1439       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1440       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1441       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1442     }
1443     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1444     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1445     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1446     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1447     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1448     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1449     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1450     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1451     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1452     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1453     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1454     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1455     if (Subtarget->hasDQI()) {
1456       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1457       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1458     }
1459     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1460     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1461     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1462     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1463     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1464     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1465     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1466     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1467     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1468     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1469
1470     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1471     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1472     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1473     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1474     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1,   Custom);
1475
1476     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1477     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1478
1479     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1480
1481     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1482     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1483     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v16i1, Custom);
1484     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1485     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1486     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1487     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1488     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1489     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1490     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1491     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1492     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1493
1494     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1495     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1496     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1497     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1498     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1499     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1500     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1501     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1502
1503     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1504     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1505
1506     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1507     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1508
1509     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1510
1511     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1512     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1513
1514     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1515     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1516
1517     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1518     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1519
1520     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1521     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1522     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1523     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1524     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1525     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1526
1527     if (Subtarget->hasCDI()) {
1528       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1529       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1530       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Expand);
1531       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Expand);
1532
1533       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1534       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1535       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1536       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1537       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Expand);
1538       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Expand);
1539       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Expand);
1540       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Expand);
1541
1542       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1543       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1544
1545       if (Subtarget->hasVLX()) {
1546         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1547         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1548         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1549         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1550         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Expand);
1551         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Expand);
1552         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Expand);
1553         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Expand);
1554
1555         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1556         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1557         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1558         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1559       } else {
1560         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1561         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1562         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1563         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1564         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Expand);
1565         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Expand);
1566         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Expand);
1567         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Expand);
1568       }
1569     } // Subtarget->hasCDI()
1570
1571     if (Subtarget->hasDQI()) {
1572       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1573       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1574       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1575     }
1576     // Custom lower several nodes.
1577     for (MVT VT : MVT::vector_valuetypes()) {
1578       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1579       if (EltSize == 1) {
1580         setOperationAction(ISD::AND, VT, Legal);
1581         setOperationAction(ISD::OR,  VT, Legal);
1582         setOperationAction(ISD::XOR,  VT, Legal);
1583       }
1584       if ((VT.is128BitVector() || VT.is256BitVector()) && EltSize >= 32) {
1585         setOperationAction(ISD::MGATHER,  VT, Custom);
1586         setOperationAction(ISD::MSCATTER, VT, Custom);
1587       }
1588       // Extract subvector is special because the value type
1589       // (result) is 256/128-bit but the source is 512-bit wide.
1590       if (VT.is128BitVector() || VT.is256BitVector()) {
1591         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1592       }
1593       if (VT.getVectorElementType() == MVT::i1)
1594         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1595
1596       // Do not attempt to custom lower other non-512-bit vectors
1597       if (!VT.is512BitVector())
1598         continue;
1599
1600       if (EltSize >= 32) {
1601         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1602         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1603         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1604         setOperationAction(ISD::VSELECT,             VT, Legal);
1605         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1606         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1607         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1608         setOperationAction(ISD::MLOAD,               VT, Legal);
1609         setOperationAction(ISD::MSTORE,              VT, Legal);
1610         setOperationAction(ISD::MGATHER,  VT, Legal);
1611         setOperationAction(ISD::MSCATTER, VT, Custom);
1612       }
1613     }
1614     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1615       setOperationAction(ISD::SELECT, VT, Promote);
1616       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1617     }
1618   }// has  AVX-512
1619
1620   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1621     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1622     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1623
1624     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1625     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1626
1627     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1628     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1629     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1630     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1631     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1632     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1633     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1634     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1635     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1636     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1637     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1638     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1639     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1640     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1641     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1642     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1643     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1644     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1645     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1646     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1647     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1648     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1649     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1650     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1651     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1652     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1653     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1654     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1655     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1656     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1657     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1658     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1659     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1660     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1661     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1662     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1663     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1664     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1665     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1666     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1667     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1668     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1669
1670     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1671     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1672     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1673     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1674     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1675     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1676     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1677     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1678
1679     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1680     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1681     if (Subtarget->hasVLX())
1682       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1683
1684     if (Subtarget->hasCDI()) {
1685       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1686       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1687       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Expand);
1688       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Expand);
1689     }
1690
1691     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1692       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1693       setOperationAction(ISD::VSELECT,             VT, Legal);
1694       setOperationAction(ISD::SRL,                 VT, Custom);
1695       setOperationAction(ISD::SHL,                 VT, Custom);
1696       setOperationAction(ISD::SRA,                 VT, Custom);
1697
1698       setOperationAction(ISD::AND,    VT, Promote);
1699       AddPromotedToType (ISD::AND,    VT, MVT::v8i64);
1700       setOperationAction(ISD::OR,     VT, Promote);
1701       AddPromotedToType (ISD::OR,     VT, MVT::v8i64);
1702       setOperationAction(ISD::XOR,    VT, Promote);
1703       AddPromotedToType (ISD::XOR,    VT, MVT::v8i64);
1704     }
1705   }
1706
1707   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1708     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1709     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1710
1711     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1712     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1713     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1714     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1715     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1716     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1717     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1718     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1719     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1720     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1721     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1722     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1723
1724     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1725     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1726     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1727     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1728     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1729     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1730     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1731     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1732
1733     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1734     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1735     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1736     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1737     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1738     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1739     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1740     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1741   }
1742
1743   // We want to custom lower some of our intrinsics.
1744   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1745   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1746   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1747   if (!Subtarget->is64Bit()) {
1748     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1749     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1750   }
1751
1752   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1753   // handle type legalization for these operations here.
1754   //
1755   // FIXME: We really should do custom legalization for addition and
1756   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1757   // than generic legalization for 64-bit multiplication-with-overflow, though.
1758   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1759     if (VT == MVT::i64 && !Subtarget->is64Bit())
1760       continue;
1761     // Add/Sub/Mul with overflow operations are custom lowered.
1762     setOperationAction(ISD::SADDO, VT, Custom);
1763     setOperationAction(ISD::UADDO, VT, Custom);
1764     setOperationAction(ISD::SSUBO, VT, Custom);
1765     setOperationAction(ISD::USUBO, VT, Custom);
1766     setOperationAction(ISD::SMULO, VT, Custom);
1767     setOperationAction(ISD::UMULO, VT, Custom);
1768   }
1769
1770   if (!Subtarget->is64Bit()) {
1771     // These libcalls are not available in 32-bit.
1772     setLibcallName(RTLIB::SHL_I128, nullptr);
1773     setLibcallName(RTLIB::SRL_I128, nullptr);
1774     setLibcallName(RTLIB::SRA_I128, nullptr);
1775   }
1776
1777   // Combine sin / cos into one node or libcall if possible.
1778   if (Subtarget->hasSinCos()) {
1779     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1780     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1781     if (Subtarget->isTargetDarwin()) {
1782       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1783       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1784       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1785       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1786     }
1787   }
1788
1789   if (Subtarget->isTargetWin64()) {
1790     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1791     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1792     setOperationAction(ISD::SREM, MVT::i128, Custom);
1793     setOperationAction(ISD::UREM, MVT::i128, Custom);
1794     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1795     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1796   }
1797
1798   // We have target-specific dag combine patterns for the following nodes:
1799   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1800   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1801   setTargetDAGCombine(ISD::BITCAST);
1802   setTargetDAGCombine(ISD::VSELECT);
1803   setTargetDAGCombine(ISD::SELECT);
1804   setTargetDAGCombine(ISD::SHL);
1805   setTargetDAGCombine(ISD::SRA);
1806   setTargetDAGCombine(ISD::SRL);
1807   setTargetDAGCombine(ISD::OR);
1808   setTargetDAGCombine(ISD::AND);
1809   setTargetDAGCombine(ISD::ADD);
1810   setTargetDAGCombine(ISD::FADD);
1811   setTargetDAGCombine(ISD::FSUB);
1812   setTargetDAGCombine(ISD::FNEG);
1813   setTargetDAGCombine(ISD::FMA);
1814   setTargetDAGCombine(ISD::FMINNUM);
1815   setTargetDAGCombine(ISD::FMAXNUM);
1816   setTargetDAGCombine(ISD::SUB);
1817   setTargetDAGCombine(ISD::LOAD);
1818   setTargetDAGCombine(ISD::MLOAD);
1819   setTargetDAGCombine(ISD::STORE);
1820   setTargetDAGCombine(ISD::MSTORE);
1821   setTargetDAGCombine(ISD::TRUNCATE);
1822   setTargetDAGCombine(ISD::ZERO_EXTEND);
1823   setTargetDAGCombine(ISD::ANY_EXTEND);
1824   setTargetDAGCombine(ISD::SIGN_EXTEND);
1825   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1826   setTargetDAGCombine(ISD::SINT_TO_FP);
1827   setTargetDAGCombine(ISD::UINT_TO_FP);
1828   setTargetDAGCombine(ISD::SETCC);
1829   setTargetDAGCombine(ISD::BUILD_VECTOR);
1830   setTargetDAGCombine(ISD::MUL);
1831   setTargetDAGCombine(ISD::XOR);
1832   setTargetDAGCombine(ISD::MSCATTER);
1833   setTargetDAGCombine(ISD::MGATHER);
1834
1835   computeRegisterProperties(Subtarget->getRegisterInfo());
1836
1837   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1838   MaxStoresPerMemsetOptSize = 8;
1839   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1840   MaxStoresPerMemcpyOptSize = 4;
1841   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1842   MaxStoresPerMemmoveOptSize = 4;
1843   setPrefLoopAlignment(4); // 2^4 bytes.
1844
1845   // A predictable cmov does not hurt on an in-order CPU.
1846   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1847   PredictableSelectIsExpensive = !Subtarget->isAtom();
1848   EnableExtLdPromotion = true;
1849   setPrefFunctionAlignment(4); // 2^4 bytes.
1850
1851   verifyIntrinsicTables();
1852 }
1853
1854 // This has so far only been implemented for 64-bit MachO.
1855 bool X86TargetLowering::useLoadStackGuardNode() const {
1856   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1857 }
1858
1859 TargetLoweringBase::LegalizeTypeAction
1860 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1861   if (ExperimentalVectorWideningLegalization &&
1862       VT.getVectorNumElements() != 1 &&
1863       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1864     return TypeWidenVector;
1865
1866   return TargetLoweringBase::getPreferredVectorAction(VT);
1867 }
1868
1869 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1870                                           EVT VT) const {
1871   if (!VT.isVector())
1872     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1873
1874   if (VT.isSimple()) {
1875     MVT VVT = VT.getSimpleVT();
1876     const unsigned NumElts = VVT.getVectorNumElements();
1877     const MVT EltVT = VVT.getVectorElementType();
1878     if (VVT.is512BitVector()) {
1879       if (Subtarget->hasAVX512())
1880         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1881             EltVT == MVT::f32 || EltVT == MVT::f64)
1882           switch(NumElts) {
1883           case  8: return MVT::v8i1;
1884           case 16: return MVT::v16i1;
1885         }
1886       if (Subtarget->hasBWI())
1887         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1888           switch(NumElts) {
1889           case 32: return MVT::v32i1;
1890           case 64: return MVT::v64i1;
1891         }
1892     }
1893
1894     if (VVT.is256BitVector() || VVT.is128BitVector()) {
1895       if (Subtarget->hasVLX())
1896         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1897             EltVT == MVT::f32 || EltVT == MVT::f64)
1898           switch(NumElts) {
1899           case 2: return MVT::v2i1;
1900           case 4: return MVT::v4i1;
1901           case 8: return MVT::v8i1;
1902         }
1903       if (Subtarget->hasBWI() && Subtarget->hasVLX())
1904         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1905           switch(NumElts) {
1906           case  8: return MVT::v8i1;
1907           case 16: return MVT::v16i1;
1908           case 32: return MVT::v32i1;
1909         }
1910     }
1911   }
1912
1913   return VT.changeVectorElementTypeToInteger();
1914 }
1915
1916 /// Helper for getByValTypeAlignment to determine
1917 /// the desired ByVal argument alignment.
1918 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1919   if (MaxAlign == 16)
1920     return;
1921   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1922     if (VTy->getBitWidth() == 128)
1923       MaxAlign = 16;
1924   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1925     unsigned EltAlign = 0;
1926     getMaxByValAlign(ATy->getElementType(), EltAlign);
1927     if (EltAlign > MaxAlign)
1928       MaxAlign = EltAlign;
1929   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1930     for (auto *EltTy : STy->elements()) {
1931       unsigned EltAlign = 0;
1932       getMaxByValAlign(EltTy, EltAlign);
1933       if (EltAlign > MaxAlign)
1934         MaxAlign = EltAlign;
1935       if (MaxAlign == 16)
1936         break;
1937     }
1938   }
1939 }
1940
1941 /// Return the desired alignment for ByVal aggregate
1942 /// function arguments in the caller parameter area. For X86, aggregates
1943 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1944 /// are at 4-byte boundaries.
1945 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1946                                                   const DataLayout &DL) const {
1947   if (Subtarget->is64Bit()) {
1948     // Max of 8 and alignment of type.
1949     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1950     if (TyAlign > 8)
1951       return TyAlign;
1952     return 8;
1953   }
1954
1955   unsigned Align = 4;
1956   if (Subtarget->hasSSE1())
1957     getMaxByValAlign(Ty, Align);
1958   return Align;
1959 }
1960
1961 /// Returns the target specific optimal type for load
1962 /// and store operations as a result of memset, memcpy, and memmove
1963 /// lowering. If DstAlign is zero that means it's safe to destination
1964 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1965 /// means there isn't a need to check it against alignment requirement,
1966 /// probably because the source does not need to be loaded. If 'IsMemset' is
1967 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1968 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1969 /// source is constant so it does not need to be loaded.
1970 /// It returns EVT::Other if the type should be determined using generic
1971 /// target-independent logic.
1972 EVT
1973 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1974                                        unsigned DstAlign, unsigned SrcAlign,
1975                                        bool IsMemset, bool ZeroMemset,
1976                                        bool MemcpyStrSrc,
1977                                        MachineFunction &MF) const {
1978   const Function *F = MF.getFunction();
1979   if ((!IsMemset || ZeroMemset) &&
1980       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1981     if (Size >= 16 &&
1982         (!Subtarget->isUnalignedMem16Slow() ||
1983          ((DstAlign == 0 || DstAlign >= 16) &&
1984           (SrcAlign == 0 || SrcAlign >= 16)))) {
1985       if (Size >= 32) {
1986         // FIXME: Check if unaligned 32-byte accesses are slow.
1987         if (Subtarget->hasInt256())
1988           return MVT::v8i32;
1989         if (Subtarget->hasFp256())
1990           return MVT::v8f32;
1991       }
1992       if (Subtarget->hasSSE2())
1993         return MVT::v4i32;
1994       if (Subtarget->hasSSE1())
1995         return MVT::v4f32;
1996     } else if (!MemcpyStrSrc && Size >= 8 &&
1997                !Subtarget->is64Bit() &&
1998                Subtarget->hasSSE2()) {
1999       // Do not use f64 to lower memcpy if source is string constant. It's
2000       // better to use i32 to avoid the loads.
2001       return MVT::f64;
2002     }
2003   }
2004   // This is a compromise. If we reach here, unaligned accesses may be slow on
2005   // this target. However, creating smaller, aligned accesses could be even
2006   // slower and would certainly be a lot more code.
2007   if (Subtarget->is64Bit() && Size >= 8)
2008     return MVT::i64;
2009   return MVT::i32;
2010 }
2011
2012 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2013   if (VT == MVT::f32)
2014     return X86ScalarSSEf32;
2015   else if (VT == MVT::f64)
2016     return X86ScalarSSEf64;
2017   return true;
2018 }
2019
2020 bool
2021 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2022                                                   unsigned,
2023                                                   unsigned,
2024                                                   bool *Fast) const {
2025   if (Fast) {
2026     switch (VT.getSizeInBits()) {
2027     default:
2028       // 8-byte and under are always assumed to be fast.
2029       *Fast = true;
2030       break;
2031     case 128:
2032       *Fast = !Subtarget->isUnalignedMem16Slow();
2033       break;
2034     case 256:
2035       *Fast = !Subtarget->isUnalignedMem32Slow();
2036       break;
2037     // TODO: What about AVX-512 (512-bit) accesses?
2038     }
2039   }
2040   // Misaligned accesses of any size are always allowed.
2041   return true;
2042 }
2043
2044 /// Return the entry encoding for a jump table in the
2045 /// current function.  The returned value is a member of the
2046 /// MachineJumpTableInfo::JTEntryKind enum.
2047 unsigned X86TargetLowering::getJumpTableEncoding() const {
2048   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2049   // symbol.
2050   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2051       Subtarget->isPICStyleGOT())
2052     return MachineJumpTableInfo::EK_Custom32;
2053
2054   // Otherwise, use the normal jump table encoding heuristics.
2055   return TargetLowering::getJumpTableEncoding();
2056 }
2057
2058 bool X86TargetLowering::useSoftFloat() const {
2059   return Subtarget->useSoftFloat();
2060 }
2061
2062 const MCExpr *
2063 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2064                                              const MachineBasicBlock *MBB,
2065                                              unsigned uid,MCContext &Ctx) const{
2066   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2067          Subtarget->isPICStyleGOT());
2068   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2069   // entries.
2070   return MCSymbolRefExpr::create(MBB->getSymbol(),
2071                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2072 }
2073
2074 /// Returns relocation base for the given PIC jumptable.
2075 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2076                                                     SelectionDAG &DAG) const {
2077   if (!Subtarget->is64Bit())
2078     // This doesn't have SDLoc associated with it, but is not really the
2079     // same as a Register.
2080     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2081                        getPointerTy(DAG.getDataLayout()));
2082   return Table;
2083 }
2084
2085 /// This returns the relocation base for the given PIC jumptable,
2086 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2087 const MCExpr *X86TargetLowering::
2088 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2089                              MCContext &Ctx) const {
2090   // X86-64 uses RIP relative addressing based on the jump table label.
2091   if (Subtarget->isPICStyleRIPRel())
2092     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2093
2094   // Otherwise, the reference is relative to the PIC base.
2095   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2096 }
2097
2098 std::pair<const TargetRegisterClass *, uint8_t>
2099 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2100                                            MVT VT) const {
2101   const TargetRegisterClass *RRC = nullptr;
2102   uint8_t Cost = 1;
2103   switch (VT.SimpleTy) {
2104   default:
2105     return TargetLowering::findRepresentativeClass(TRI, VT);
2106   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2107     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2108     break;
2109   case MVT::x86mmx:
2110     RRC = &X86::VR64RegClass;
2111     break;
2112   case MVT::f32: case MVT::f64:
2113   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2114   case MVT::v4f32: case MVT::v2f64:
2115   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2116   case MVT::v4f64:
2117     RRC = &X86::VR128RegClass;
2118     break;
2119   }
2120   return std::make_pair(RRC, Cost);
2121 }
2122
2123 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2124                                                unsigned &Offset) const {
2125   if (!Subtarget->isTargetLinux())
2126     return false;
2127
2128   if (Subtarget->is64Bit()) {
2129     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2130     Offset = 0x28;
2131     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2132       AddressSpace = 256;
2133     else
2134       AddressSpace = 257;
2135   } else {
2136     // %gs:0x14 on i386
2137     Offset = 0x14;
2138     AddressSpace = 256;
2139   }
2140   return true;
2141 }
2142
2143 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2144   if (!Subtarget->isTargetAndroid())
2145     return TargetLowering::getSafeStackPointerLocation(IRB);
2146
2147   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2148   // definition of TLS_SLOT_SAFESTACK in
2149   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2150   unsigned AddressSpace, Offset;
2151   if (Subtarget->is64Bit()) {
2152     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2153     Offset = 0x48;
2154     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2155       AddressSpace = 256;
2156     else
2157       AddressSpace = 257;
2158   } else {
2159     // %gs:0x24 on i386
2160     Offset = 0x24;
2161     AddressSpace = 256;
2162   }
2163
2164   return ConstantExpr::getIntToPtr(
2165       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2166       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2167 }
2168
2169 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2170                                             unsigned DestAS) const {
2171   assert(SrcAS != DestAS && "Expected different address spaces!");
2172
2173   return SrcAS < 256 && DestAS < 256;
2174 }
2175
2176 //===----------------------------------------------------------------------===//
2177 //               Return Value Calling Convention Implementation
2178 //===----------------------------------------------------------------------===//
2179
2180 #include "X86GenCallingConv.inc"
2181
2182 bool X86TargetLowering::CanLowerReturn(
2183     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2184     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2185   SmallVector<CCValAssign, 16> RVLocs;
2186   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2187   return CCInfo.CheckReturn(Outs, RetCC_X86);
2188 }
2189
2190 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2191   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2192   return ScratchRegs;
2193 }
2194
2195 SDValue
2196 X86TargetLowering::LowerReturn(SDValue Chain,
2197                                CallingConv::ID CallConv, bool isVarArg,
2198                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2199                                const SmallVectorImpl<SDValue> &OutVals,
2200                                SDLoc dl, SelectionDAG &DAG) const {
2201   MachineFunction &MF = DAG.getMachineFunction();
2202   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2203
2204   if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2205     report_fatal_error("X86 interrupts may not return any value");
2206
2207   SmallVector<CCValAssign, 16> RVLocs;
2208   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2209   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2210
2211   SDValue Flag;
2212   SmallVector<SDValue, 6> RetOps;
2213   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2214   // Operand #1 = Bytes To Pop
2215   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2216                    MVT::i16));
2217
2218   // Copy the result values into the output registers.
2219   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2220     CCValAssign &VA = RVLocs[i];
2221     assert(VA.isRegLoc() && "Can only return in registers!");
2222     SDValue ValToCopy = OutVals[i];
2223     EVT ValVT = ValToCopy.getValueType();
2224
2225     // Promote values to the appropriate types.
2226     if (VA.getLocInfo() == CCValAssign::SExt)
2227       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2228     else if (VA.getLocInfo() == CCValAssign::ZExt)
2229       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2230     else if (VA.getLocInfo() == CCValAssign::AExt) {
2231       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2232         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2233       else
2234         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2235     }
2236     else if (VA.getLocInfo() == CCValAssign::BCvt)
2237       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2238
2239     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2240            "Unexpected FP-extend for return value.");
2241
2242     // If this is x86-64, and we disabled SSE, we can't return FP values,
2243     // or SSE or MMX vectors.
2244     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2245          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2246           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2247       report_fatal_error("SSE register return with SSE disabled");
2248     }
2249     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2250     // llvm-gcc has never done it right and no one has noticed, so this
2251     // should be OK for now.
2252     if (ValVT == MVT::f64 &&
2253         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2254       report_fatal_error("SSE2 register return with SSE2 disabled");
2255
2256     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2257     // the RET instruction and handled by the FP Stackifier.
2258     if (VA.getLocReg() == X86::FP0 ||
2259         VA.getLocReg() == X86::FP1) {
2260       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2261       // change the value to the FP stack register class.
2262       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2263         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2264       RetOps.push_back(ValToCopy);
2265       // Don't emit a copytoreg.
2266       continue;
2267     }
2268
2269     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2270     // which is returned in RAX / RDX.
2271     if (Subtarget->is64Bit()) {
2272       if (ValVT == MVT::x86mmx) {
2273         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2274           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2275           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2276                                   ValToCopy);
2277           // If we don't have SSE2 available, convert to v4f32 so the generated
2278           // register is legal.
2279           if (!Subtarget->hasSSE2())
2280             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2281         }
2282       }
2283     }
2284
2285     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2286     Flag = Chain.getValue(1);
2287     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2288   }
2289
2290   // All x86 ABIs require that for returning structs by value we copy
2291   // the sret argument into %rax/%eax (depending on ABI) for the return.
2292   // We saved the argument into a virtual register in the entry block,
2293   // so now we copy the value out and into %rax/%eax.
2294   //
2295   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2296   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2297   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2298   // either case FuncInfo->setSRetReturnReg() will have been called.
2299   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2300     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2301                                      getPointerTy(MF.getDataLayout()));
2302
2303     unsigned RetValReg
2304         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2305           X86::RAX : X86::EAX;
2306     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2307     Flag = Chain.getValue(1);
2308
2309     // RAX/EAX now acts like a return value.
2310     RetOps.push_back(
2311         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2312   }
2313
2314   const X86RegisterInfo *TRI = Subtarget->getRegisterInfo();
2315   const MCPhysReg *I =
2316       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2317   if (I) {
2318     for (; *I; ++I) {
2319       if (X86::GR64RegClass.contains(*I))
2320         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2321       else
2322         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2323     }
2324   }
2325
2326   RetOps[0] = Chain;  // Update chain.
2327
2328   // Add the flag if we have it.
2329   if (Flag.getNode())
2330     RetOps.push_back(Flag);
2331
2332   X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2333   if (CallConv == CallingConv::X86_INTR)
2334     opcode = X86ISD::IRET;
2335   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2336 }
2337
2338 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2339   if (N->getNumValues() != 1)
2340     return false;
2341   if (!N->hasNUsesOfValue(1, 0))
2342     return false;
2343
2344   SDValue TCChain = Chain;
2345   SDNode *Copy = *N->use_begin();
2346   if (Copy->getOpcode() == ISD::CopyToReg) {
2347     // If the copy has a glue operand, we conservatively assume it isn't safe to
2348     // perform a tail call.
2349     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2350       return false;
2351     TCChain = Copy->getOperand(0);
2352   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2353     return false;
2354
2355   bool HasRet = false;
2356   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2357        UI != UE; ++UI) {
2358     if (UI->getOpcode() != X86ISD::RET_FLAG)
2359       return false;
2360     // If we are returning more than one value, we can definitely
2361     // not make a tail call see PR19530
2362     if (UI->getNumOperands() > 4)
2363       return false;
2364     if (UI->getNumOperands() == 4 &&
2365         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2366       return false;
2367     HasRet = true;
2368   }
2369
2370   if (!HasRet)
2371     return false;
2372
2373   Chain = TCChain;
2374   return true;
2375 }
2376
2377 EVT
2378 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2379                                             ISD::NodeType ExtendKind) const {
2380   MVT ReturnMVT;
2381   // TODO: Is this also valid on 32-bit?
2382   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2383     ReturnMVT = MVT::i8;
2384   else
2385     ReturnMVT = MVT::i32;
2386
2387   EVT MinVT = getRegisterType(Context, ReturnMVT);
2388   return VT.bitsLT(MinVT) ? MinVT : VT;
2389 }
2390
2391 /// Lower the result values of a call into the
2392 /// appropriate copies out of appropriate physical registers.
2393 ///
2394 SDValue
2395 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2396                                    CallingConv::ID CallConv, bool isVarArg,
2397                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2398                                    SDLoc dl, SelectionDAG &DAG,
2399                                    SmallVectorImpl<SDValue> &InVals) const {
2400
2401   // Assign locations to each value returned by this call.
2402   SmallVector<CCValAssign, 16> RVLocs;
2403   bool Is64Bit = Subtarget->is64Bit();
2404   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2405                  *DAG.getContext());
2406   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2407
2408   // Copy all of the result registers out of their specified physreg.
2409   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2410     CCValAssign &VA = RVLocs[i];
2411     EVT CopyVT = VA.getLocVT();
2412
2413     // If this is x86-64, and we disabled SSE, we can't return FP values
2414     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2415         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2416       report_fatal_error("SSE register return with SSE disabled");
2417     }
2418
2419     // If we prefer to use the value in xmm registers, copy it out as f80 and
2420     // use a truncate to move it from fp stack reg to xmm reg.
2421     bool RoundAfterCopy = false;
2422     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2423         isScalarFPTypeInSSEReg(VA.getValVT())) {
2424       CopyVT = MVT::f80;
2425       RoundAfterCopy = (CopyVT != VA.getLocVT());
2426     }
2427
2428     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2429                                CopyVT, InFlag).getValue(1);
2430     SDValue Val = Chain.getValue(0);
2431
2432     if (RoundAfterCopy)
2433       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2434                         // This truncation won't change the value.
2435                         DAG.getIntPtrConstant(1, dl));
2436
2437     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2438       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2439
2440     InFlag = Chain.getValue(2);
2441     InVals.push_back(Val);
2442   }
2443
2444   return Chain;
2445 }
2446
2447 //===----------------------------------------------------------------------===//
2448 //                C & StdCall & Fast Calling Convention implementation
2449 //===----------------------------------------------------------------------===//
2450 //  StdCall calling convention seems to be standard for many Windows' API
2451 //  routines and around. It differs from C calling convention just a little:
2452 //  callee should clean up the stack, not caller. Symbols should be also
2453 //  decorated in some fancy way :) It doesn't support any vector arguments.
2454 //  For info on fast calling convention see Fast Calling Convention (tail call)
2455 //  implementation LowerX86_32FastCCCallTo.
2456
2457 /// CallIsStructReturn - Determines whether a call uses struct return
2458 /// semantics.
2459 enum StructReturnType {
2460   NotStructReturn,
2461   RegStructReturn,
2462   StackStructReturn
2463 };
2464 static StructReturnType
2465 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsMCU) {
2466   if (Outs.empty())
2467     return NotStructReturn;
2468
2469   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2470   if (!Flags.isSRet())
2471     return NotStructReturn;
2472   if (Flags.isInReg() || IsMCU)
2473     return RegStructReturn;
2474   return StackStructReturn;
2475 }
2476
2477 /// Determines whether a function uses struct return semantics.
2478 static StructReturnType
2479 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsMCU) {
2480   if (Ins.empty())
2481     return NotStructReturn;
2482
2483   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2484   if (!Flags.isSRet())
2485     return NotStructReturn;
2486   if (Flags.isInReg() || IsMCU)
2487     return RegStructReturn;
2488   return StackStructReturn;
2489 }
2490
2491 /// Make a copy of an aggregate at address specified by "Src" to address
2492 /// "Dst" with size and alignment information specified by the specific
2493 /// parameter attribute. The copy will be passed as a byval function parameter.
2494 static SDValue
2495 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2496                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2497                           SDLoc dl) {
2498   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2499
2500   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2501                        /*isVolatile*/false, /*AlwaysInline=*/true,
2502                        /*isTailCall*/false,
2503                        MachinePointerInfo(), MachinePointerInfo());
2504 }
2505
2506 /// Return true if the calling convention is one that we can guarantee TCO for.
2507 static bool canGuaranteeTCO(CallingConv::ID CC) {
2508   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2509           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2510 }
2511
2512 /// Return true if we might ever do TCO for calls with this calling convention.
2513 static bool mayTailCallThisCC(CallingConv::ID CC) {
2514   switch (CC) {
2515   // C calling conventions:
2516   case CallingConv::C:
2517   case CallingConv::X86_64_Win64:
2518   case CallingConv::X86_64_SysV:
2519   // Callee pop conventions:
2520   case CallingConv::X86_ThisCall:
2521   case CallingConv::X86_StdCall:
2522   case CallingConv::X86_VectorCall:
2523   case CallingConv::X86_FastCall:
2524     return true;
2525   default:
2526     return canGuaranteeTCO(CC);
2527   }
2528 }
2529
2530 /// Return true if the function is being made into a tailcall target by
2531 /// changing its ABI.
2532 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2533   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2534 }
2535
2536 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2537   auto Attr =
2538       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2539   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2540     return false;
2541
2542   CallSite CS(CI);
2543   CallingConv::ID CalleeCC = CS.getCallingConv();
2544   if (!mayTailCallThisCC(CalleeCC))
2545     return false;
2546
2547   return true;
2548 }
2549
2550 SDValue
2551 X86TargetLowering::LowerMemArgument(SDValue Chain,
2552                                     CallingConv::ID CallConv,
2553                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2554                                     SDLoc dl, SelectionDAG &DAG,
2555                                     const CCValAssign &VA,
2556                                     MachineFrameInfo *MFI,
2557                                     unsigned i) const {
2558   // Create the nodes corresponding to a load from this parameter slot.
2559   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2560   bool AlwaysUseMutable = shouldGuaranteeTCO(
2561       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2562   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2563   EVT ValVT;
2564
2565   // If value is passed by pointer we have address passed instead of the value
2566   // itself.
2567   bool ExtendedInMem = VA.isExtInLoc() &&
2568     VA.getValVT().getScalarType() == MVT::i1;
2569
2570   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2571     ValVT = VA.getLocVT();
2572   else
2573     ValVT = VA.getValVT();
2574
2575   // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2576   // taken by a return address.
2577   int Offset = 0;
2578   if (CallConv == CallingConv::X86_INTR) {
2579     const X86Subtarget& Subtarget =
2580         static_cast<const X86Subtarget&>(DAG.getSubtarget());
2581     // X86 interrupts may take one or two arguments.
2582     // On the stack there will be no return address as in regular call.
2583     // Offset of last argument need to be set to -4/-8 bytes.
2584     // Where offset of the first argument out of two, should be set to 0 bytes.
2585     Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2586   }
2587
2588   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2589   // changed with more analysis.
2590   // In case of tail call optimization mark all arguments mutable. Since they
2591   // could be overwritten by lowering of arguments in case of a tail call.
2592   if (Flags.isByVal()) {
2593     unsigned Bytes = Flags.getByValSize();
2594     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2595     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2596     // Adjust SP offset of interrupt parameter.
2597     if (CallConv == CallingConv::X86_INTR) {
2598       MFI->setObjectOffset(FI, Offset);
2599     }
2600     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2601   } else {
2602     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2603                                     VA.getLocMemOffset(), isImmutable);
2604     // Adjust SP offset of interrupt parameter.
2605     if (CallConv == CallingConv::X86_INTR) {
2606       MFI->setObjectOffset(FI, Offset);
2607     }
2608
2609     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2610     SDValue Val = DAG.getLoad(
2611         ValVT, dl, Chain, FIN,
2612         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2613         false, false, 0);
2614     return ExtendedInMem ?
2615       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2616   }
2617 }
2618
2619 // FIXME: Get this from tablegen.
2620 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2621                                                 const X86Subtarget *Subtarget) {
2622   assert(Subtarget->is64Bit());
2623
2624   if (Subtarget->isCallingConvWin64(CallConv)) {
2625     static const MCPhysReg GPR64ArgRegsWin64[] = {
2626       X86::RCX, X86::RDX, X86::R8,  X86::R9
2627     };
2628     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2629   }
2630
2631   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2632     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2633   };
2634   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2635 }
2636
2637 // FIXME: Get this from tablegen.
2638 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2639                                                 CallingConv::ID CallConv,
2640                                                 const X86Subtarget *Subtarget) {
2641   assert(Subtarget->is64Bit());
2642   if (Subtarget->isCallingConvWin64(CallConv)) {
2643     // The XMM registers which might contain var arg parameters are shadowed
2644     // in their paired GPR.  So we only need to save the GPR to their home
2645     // slots.
2646     // TODO: __vectorcall will change this.
2647     return None;
2648   }
2649
2650   const Function *Fn = MF.getFunction();
2651   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2652   bool isSoftFloat = Subtarget->useSoftFloat();
2653   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2654          "SSE register cannot be used when SSE is disabled!");
2655   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2656     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2657     // registers.
2658     return None;
2659
2660   static const MCPhysReg XMMArgRegs64Bit[] = {
2661     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2662     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2663   };
2664   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2665 }
2666
2667 SDValue X86TargetLowering::LowerFormalArguments(
2668     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2669     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2670     SmallVectorImpl<SDValue> &InVals) const {
2671   MachineFunction &MF = DAG.getMachineFunction();
2672   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2673   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2674
2675   const Function* Fn = MF.getFunction();
2676   if (Fn->hasExternalLinkage() &&
2677       Subtarget->isTargetCygMing() &&
2678       Fn->getName() == "main")
2679     FuncInfo->setForceFramePointer(true);
2680
2681   MachineFrameInfo *MFI = MF.getFrameInfo();
2682   bool Is64Bit = Subtarget->is64Bit();
2683   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2684
2685   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2686          "Var args not supported with calling convention fastcc, ghc or hipe");
2687
2688   if (CallConv == CallingConv::X86_INTR) {
2689     bool isLegal = Ins.size() == 1 ||
2690                    (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2691                                         (!Is64Bit && Ins[1].VT == MVT::i32)));
2692     if (!isLegal)
2693       report_fatal_error("X86 interrupts may take one or two arguments");
2694   }
2695
2696   // Assign locations to all of the incoming arguments.
2697   SmallVector<CCValAssign, 16> ArgLocs;
2698   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2699
2700   // Allocate shadow area for Win64
2701   if (IsWin64)
2702     CCInfo.AllocateStack(32, 8);
2703
2704   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2705
2706   unsigned LastVal = ~0U;
2707   SDValue ArgValue;
2708   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2709     CCValAssign &VA = ArgLocs[i];
2710     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2711     // places.
2712     assert(VA.getValNo() != LastVal &&
2713            "Don't support value assigned to multiple locs yet");
2714     (void)LastVal;
2715     LastVal = VA.getValNo();
2716
2717     if (VA.isRegLoc()) {
2718       EVT RegVT = VA.getLocVT();
2719       const TargetRegisterClass *RC;
2720       if (RegVT == MVT::i32)
2721         RC = &X86::GR32RegClass;
2722       else if (Is64Bit && RegVT == MVT::i64)
2723         RC = &X86::GR64RegClass;
2724       else if (RegVT == MVT::f32)
2725         RC = &X86::FR32RegClass;
2726       else if (RegVT == MVT::f64)
2727         RC = &X86::FR64RegClass;
2728       else if (RegVT == MVT::f128)
2729         RC = &X86::FR128RegClass;
2730       else if (RegVT.is512BitVector())
2731         RC = &X86::VR512RegClass;
2732       else if (RegVT.is256BitVector())
2733         RC = &X86::VR256RegClass;
2734       else if (RegVT.is128BitVector())
2735         RC = &X86::VR128RegClass;
2736       else if (RegVT == MVT::x86mmx)
2737         RC = &X86::VR64RegClass;
2738       else if (RegVT == MVT::i1)
2739         RC = &X86::VK1RegClass;
2740       else if (RegVT == MVT::v8i1)
2741         RC = &X86::VK8RegClass;
2742       else if (RegVT == MVT::v16i1)
2743         RC = &X86::VK16RegClass;
2744       else if (RegVT == MVT::v32i1)
2745         RC = &X86::VK32RegClass;
2746       else if (RegVT == MVT::v64i1)
2747         RC = &X86::VK64RegClass;
2748       else
2749         llvm_unreachable("Unknown argument type!");
2750
2751       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2752       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2753
2754       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2755       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2756       // right size.
2757       if (VA.getLocInfo() == CCValAssign::SExt)
2758         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2759                                DAG.getValueType(VA.getValVT()));
2760       else if (VA.getLocInfo() == CCValAssign::ZExt)
2761         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2762                                DAG.getValueType(VA.getValVT()));
2763       else if (VA.getLocInfo() == CCValAssign::BCvt)
2764         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2765
2766       if (VA.isExtInLoc()) {
2767         // Handle MMX values passed in XMM regs.
2768         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2769           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2770         else
2771           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2772       }
2773     } else {
2774       assert(VA.isMemLoc());
2775       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2776     }
2777
2778     // If value is passed via pointer - do a load.
2779     if (VA.getLocInfo() == CCValAssign::Indirect)
2780       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2781                              MachinePointerInfo(), false, false, false, 0);
2782
2783     InVals.push_back(ArgValue);
2784   }
2785
2786   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2787     // All x86 ABIs require that for returning structs by value we copy the
2788     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2789     // the argument into a virtual register so that we can access it from the
2790     // return points.
2791     if (Ins[i].Flags.isSRet()) {
2792       unsigned Reg = FuncInfo->getSRetReturnReg();
2793       if (!Reg) {
2794         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2795         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2796         FuncInfo->setSRetReturnReg(Reg);
2797       }
2798       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2799       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2800       break;
2801     }
2802   }
2803
2804   unsigned StackSize = CCInfo.getNextStackOffset();
2805   // Align stack specially for tail calls.
2806   if (shouldGuaranteeTCO(CallConv,
2807                          MF.getTarget().Options.GuaranteedTailCallOpt))
2808     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2809
2810   // If the function takes variable number of arguments, make a frame index for
2811   // the start of the first vararg value... for expansion of llvm.va_start. We
2812   // can skip this if there are no va_start calls.
2813   if (MFI->hasVAStart() &&
2814       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2815                    CallConv != CallingConv::X86_ThisCall))) {
2816     FuncInfo->setVarArgsFrameIndex(
2817         MFI->CreateFixedObject(1, StackSize, true));
2818   }
2819
2820   // Figure out if XMM registers are in use.
2821   assert(!(Subtarget->useSoftFloat() &&
2822            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2823          "SSE register cannot be used when SSE is disabled!");
2824
2825   // 64-bit calling conventions support varargs and register parameters, so we
2826   // have to do extra work to spill them in the prologue.
2827   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2828     // Find the first unallocated argument registers.
2829     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2830     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2831     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2832     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2833     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2834            "SSE register cannot be used when SSE is disabled!");
2835
2836     // Gather all the live in physical registers.
2837     SmallVector<SDValue, 6> LiveGPRs;
2838     SmallVector<SDValue, 8> LiveXMMRegs;
2839     SDValue ALVal;
2840     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2841       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2842       LiveGPRs.push_back(
2843           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2844     }
2845     if (!ArgXMMs.empty()) {
2846       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2847       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2848       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2849         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2850         LiveXMMRegs.push_back(
2851             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2852       }
2853     }
2854
2855     if (IsWin64) {
2856       // Get to the caller-allocated home save location.  Add 8 to account
2857       // for the return address.
2858       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2859       FuncInfo->setRegSaveFrameIndex(
2860           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2861       // Fixup to set vararg frame on shadow area (4 x i64).
2862       if (NumIntRegs < 4)
2863         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2864     } else {
2865       // For X86-64, if there are vararg parameters that are passed via
2866       // registers, then we must store them to their spots on the stack so
2867       // they may be loaded by deferencing the result of va_next.
2868       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2869       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2870       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2871           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2872     }
2873
2874     // Store the integer parameter registers.
2875     SmallVector<SDValue, 8> MemOps;
2876     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2877                                       getPointerTy(DAG.getDataLayout()));
2878     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2879     for (SDValue Val : LiveGPRs) {
2880       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2881                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2882       SDValue Store =
2883           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2884                        MachinePointerInfo::getFixedStack(
2885                            DAG.getMachineFunction(),
2886                            FuncInfo->getRegSaveFrameIndex(), Offset),
2887                        false, false, 0);
2888       MemOps.push_back(Store);
2889       Offset += 8;
2890     }
2891
2892     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2893       // Now store the XMM (fp + vector) parameter registers.
2894       SmallVector<SDValue, 12> SaveXMMOps;
2895       SaveXMMOps.push_back(Chain);
2896       SaveXMMOps.push_back(ALVal);
2897       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2898                              FuncInfo->getRegSaveFrameIndex(), dl));
2899       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2900                              FuncInfo->getVarArgsFPOffset(), dl));
2901       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2902                         LiveXMMRegs.end());
2903       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2904                                    MVT::Other, SaveXMMOps));
2905     }
2906
2907     if (!MemOps.empty())
2908       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2909   }
2910
2911   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2912     // Find the largest legal vector type.
2913     MVT VecVT = MVT::Other;
2914     // FIXME: Only some x86_32 calling conventions support AVX512.
2915     if (Subtarget->hasAVX512() &&
2916         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2917                      CallConv == CallingConv::Intel_OCL_BI)))
2918       VecVT = MVT::v16f32;
2919     else if (Subtarget->hasAVX())
2920       VecVT = MVT::v8f32;
2921     else if (Subtarget->hasSSE2())
2922       VecVT = MVT::v4f32;
2923
2924     // We forward some GPRs and some vector types.
2925     SmallVector<MVT, 2> RegParmTypes;
2926     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2927     RegParmTypes.push_back(IntVT);
2928     if (VecVT != MVT::Other)
2929       RegParmTypes.push_back(VecVT);
2930
2931     // Compute the set of forwarded registers. The rest are scratch.
2932     SmallVectorImpl<ForwardedRegister> &Forwards =
2933         FuncInfo->getForwardedMustTailRegParms();
2934     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2935
2936     // Conservatively forward AL on x86_64, since it might be used for varargs.
2937     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2938       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2939       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2940     }
2941
2942     // Copy all forwards from physical to virtual registers.
2943     for (ForwardedRegister &F : Forwards) {
2944       // FIXME: Can we use a less constrained schedule?
2945       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2946       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2947       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2948     }
2949   }
2950
2951   // Some CCs need callee pop.
2952   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2953                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2954     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2955   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
2956     // X86 interrupts must pop the error code if present
2957     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 8 : 4);
2958   } else {
2959     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2960     // If this is an sret function, the return should pop the hidden pointer.
2961     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2962         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2963         argsAreStructReturn(Ins, Subtarget->isTargetMCU()) == StackStructReturn)
2964       FuncInfo->setBytesToPopOnReturn(4);
2965   }
2966
2967   if (!Is64Bit) {
2968     // RegSaveFrameIndex is X86-64 only.
2969     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2970     if (CallConv == CallingConv::X86_FastCall ||
2971         CallConv == CallingConv::X86_ThisCall)
2972       // fastcc functions can't have varargs.
2973       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2974   }
2975
2976   FuncInfo->setArgumentStackSize(StackSize);
2977
2978   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2979     EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2980     if (Personality == EHPersonality::CoreCLR) {
2981       assert(Is64Bit);
2982       // TODO: Add a mechanism to frame lowering that will allow us to indicate
2983       // that we'd prefer this slot be allocated towards the bottom of the frame
2984       // (i.e. near the stack pointer after allocating the frame).  Every
2985       // funclet needs a copy of this slot in its (mostly empty) frame, and the
2986       // offset from the bottom of this and each funclet's frame must be the
2987       // same, so the size of funclets' (mostly empty) frames is dictated by
2988       // how far this slot is from the bottom (since they allocate just enough
2989       // space to accomodate holding this slot at the correct offset).
2990       int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2991       EHInfo->PSPSymFrameIdx = PSPSymFI;
2992     }
2993   }
2994
2995   return Chain;
2996 }
2997
2998 SDValue
2999 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
3000                                     SDValue StackPtr, SDValue Arg,
3001                                     SDLoc dl, SelectionDAG &DAG,
3002                                     const CCValAssign &VA,
3003                                     ISD::ArgFlagsTy Flags) const {
3004   unsigned LocMemOffset = VA.getLocMemOffset();
3005   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3006   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3007                        StackPtr, PtrOff);
3008   if (Flags.isByVal())
3009     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3010
3011   return DAG.getStore(
3012       Chain, dl, Arg, PtrOff,
3013       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
3014       false, false, 0);
3015 }
3016
3017 /// Emit a load of return address if tail call
3018 /// optimization is performed and it is required.
3019 SDValue
3020 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
3021                                            SDValue &OutRetAddr, SDValue Chain,
3022                                            bool IsTailCall, bool Is64Bit,
3023                                            int FPDiff, SDLoc dl) const {
3024   // Adjust the Return address stack slot.
3025   EVT VT = getPointerTy(DAG.getDataLayout());
3026   OutRetAddr = getReturnAddressFrameIndex(DAG);
3027
3028   // Load the "old" Return address.
3029   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
3030                            false, false, false, 0);
3031   return SDValue(OutRetAddr.getNode(), 1);
3032 }
3033
3034 /// Emit a store of the return address if tail call
3035 /// optimization is performed and it is required (FPDiff!=0).
3036 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3037                                         SDValue Chain, SDValue RetAddrFrIdx,
3038                                         EVT PtrVT, unsigned SlotSize,
3039                                         int FPDiff, SDLoc dl) {
3040   // Store the return address to the appropriate stack slot.
3041   if (!FPDiff) return Chain;
3042   // Calculate the new stack slot for the return address.
3043   int NewReturnAddrFI =
3044     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3045                                          false);
3046   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3047   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3048                        MachinePointerInfo::getFixedStack(
3049                            DAG.getMachineFunction(), NewReturnAddrFI),
3050                        false, false, 0);
3051   return Chain;
3052 }
3053
3054 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3055 /// operation of specified width.
3056 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
3057                        SDValue V2) {
3058   unsigned NumElems = VT.getVectorNumElements();
3059   SmallVector<int, 8> Mask;
3060   Mask.push_back(NumElems);
3061   for (unsigned i = 1; i != NumElems; ++i)
3062     Mask.push_back(i);
3063   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3064 }
3065
3066 SDValue
3067 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3068                              SmallVectorImpl<SDValue> &InVals) const {
3069   SelectionDAG &DAG                     = CLI.DAG;
3070   SDLoc &dl                             = CLI.DL;
3071   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3072   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3073   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3074   SDValue Chain                         = CLI.Chain;
3075   SDValue Callee                        = CLI.Callee;
3076   CallingConv::ID CallConv              = CLI.CallConv;
3077   bool &isTailCall                      = CLI.IsTailCall;
3078   bool isVarArg                         = CLI.IsVarArg;
3079
3080   MachineFunction &MF = DAG.getMachineFunction();
3081   bool Is64Bit        = Subtarget->is64Bit();
3082   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
3083   StructReturnType SR = callIsStructReturn(Outs, Subtarget->isTargetMCU());
3084   bool IsSibcall      = false;
3085   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3086   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3087
3088   if (CallConv == CallingConv::X86_INTR)
3089     report_fatal_error("X86 interrupts may not be called directly");
3090
3091   if (Attr.getValueAsString() == "true")
3092     isTailCall = false;
3093
3094   if (Subtarget->isPICStyleGOT() &&
3095       !MF.getTarget().Options.GuaranteedTailCallOpt) {
3096     // If we are using a GOT, disable tail calls to external symbols with
3097     // default visibility. Tail calling such a symbol requires using a GOT
3098     // relocation, which forces early binding of the symbol. This breaks code
3099     // that require lazy function symbol resolution. Using musttail or
3100     // GuaranteedTailCallOpt will override this.
3101     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3102     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3103                G->getGlobal()->hasDefaultVisibility()))
3104       isTailCall = false;
3105   }
3106
3107   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3108   if (IsMustTail) {
3109     // Force this to be a tail call.  The verifier rules are enough to ensure
3110     // that we can lower this successfully without moving the return address
3111     // around.
3112     isTailCall = true;
3113   } else if (isTailCall) {
3114     // Check if it's really possible to do a tail call.
3115     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3116                     isVarArg, SR != NotStructReturn,
3117                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3118                     Outs, OutVals, Ins, DAG);
3119
3120     // Sibcalls are automatically detected tailcalls which do not require
3121     // ABI changes.
3122     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3123       IsSibcall = true;
3124
3125     if (isTailCall)
3126       ++NumTailCalls;
3127   }
3128
3129   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3130          "Var args not supported with calling convention fastcc, ghc or hipe");
3131
3132   // Analyze operands of the call, assigning locations to each operand.
3133   SmallVector<CCValAssign, 16> ArgLocs;
3134   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3135
3136   // Allocate shadow area for Win64
3137   if (IsWin64)
3138     CCInfo.AllocateStack(32, 8);
3139
3140   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3141
3142   // Get a count of how many bytes are to be pushed on the stack.
3143   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3144   if (IsSibcall)
3145     // This is a sibcall. The memory operands are available in caller's
3146     // own caller's stack.
3147     NumBytes = 0;
3148   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3149            canGuaranteeTCO(CallConv))
3150     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3151
3152   int FPDiff = 0;
3153   if (isTailCall && !IsSibcall && !IsMustTail) {
3154     // Lower arguments at fp - stackoffset + fpdiff.
3155     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3156
3157     FPDiff = NumBytesCallerPushed - NumBytes;
3158
3159     // Set the delta of movement of the returnaddr stackslot.
3160     // But only set if delta is greater than previous delta.
3161     if (FPDiff < X86Info->getTCReturnAddrDelta())
3162       X86Info->setTCReturnAddrDelta(FPDiff);
3163   }
3164
3165   unsigned NumBytesToPush = NumBytes;
3166   unsigned NumBytesToPop = NumBytes;
3167
3168   // If we have an inalloca argument, all stack space has already been allocated
3169   // for us and be right at the top of the stack.  We don't support multiple
3170   // arguments passed in memory when using inalloca.
3171   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3172     NumBytesToPush = 0;
3173     if (!ArgLocs.back().isMemLoc())
3174       report_fatal_error("cannot use inalloca attribute on a register "
3175                          "parameter");
3176     if (ArgLocs.back().getLocMemOffset() != 0)
3177       report_fatal_error("any parameter with the inalloca attribute must be "
3178                          "the only memory argument");
3179   }
3180
3181   if (!IsSibcall)
3182     Chain = DAG.getCALLSEQ_START(
3183         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3184
3185   SDValue RetAddrFrIdx;
3186   // Load return address for tail calls.
3187   if (isTailCall && FPDiff)
3188     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3189                                     Is64Bit, FPDiff, dl);
3190
3191   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3192   SmallVector<SDValue, 8> MemOpChains;
3193   SDValue StackPtr;
3194
3195   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3196   // of tail call optimization arguments are handle later.
3197   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3198   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3199     // Skip inalloca arguments, they have already been written.
3200     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3201     if (Flags.isInAlloca())
3202       continue;
3203
3204     CCValAssign &VA = ArgLocs[i];
3205     EVT RegVT = VA.getLocVT();
3206     SDValue Arg = OutVals[i];
3207     bool isByVal = Flags.isByVal();
3208
3209     // Promote the value if needed.
3210     switch (VA.getLocInfo()) {
3211     default: llvm_unreachable("Unknown loc info!");
3212     case CCValAssign::Full: break;
3213     case CCValAssign::SExt:
3214       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3215       break;
3216     case CCValAssign::ZExt:
3217       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3218       break;
3219     case CCValAssign::AExt:
3220       if (Arg.getValueType().isVector() &&
3221           Arg.getValueType().getVectorElementType() == MVT::i1)
3222         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3223       else if (RegVT.is128BitVector()) {
3224         // Special case: passing MMX values in XMM registers.
3225         Arg = DAG.getBitcast(MVT::i64, Arg);
3226         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3227         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3228       } else
3229         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3230       break;
3231     case CCValAssign::BCvt:
3232       Arg = DAG.getBitcast(RegVT, Arg);
3233       break;
3234     case CCValAssign::Indirect: {
3235       // Store the argument.
3236       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3237       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3238       Chain = DAG.getStore(
3239           Chain, dl, Arg, SpillSlot,
3240           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3241           false, false, 0);
3242       Arg = SpillSlot;
3243       break;
3244     }
3245     }
3246
3247     if (VA.isRegLoc()) {
3248       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3249       if (isVarArg && IsWin64) {
3250         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3251         // shadow reg if callee is a varargs function.
3252         unsigned ShadowReg = 0;
3253         switch (VA.getLocReg()) {
3254         case X86::XMM0: ShadowReg = X86::RCX; break;
3255         case X86::XMM1: ShadowReg = X86::RDX; break;
3256         case X86::XMM2: ShadowReg = X86::R8; break;
3257         case X86::XMM3: ShadowReg = X86::R9; break;
3258         }
3259         if (ShadowReg)
3260           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3261       }
3262     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3263       assert(VA.isMemLoc());
3264       if (!StackPtr.getNode())
3265         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3266                                       getPointerTy(DAG.getDataLayout()));
3267       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3268                                              dl, DAG, VA, Flags));
3269     }
3270   }
3271
3272   if (!MemOpChains.empty())
3273     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3274
3275   if (Subtarget->isPICStyleGOT()) {
3276     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3277     // GOT pointer.
3278     if (!isTailCall) {
3279       RegsToPass.push_back(std::make_pair(
3280           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3281                                           getPointerTy(DAG.getDataLayout()))));
3282     } else {
3283       // If we are tail calling and generating PIC/GOT style code load the
3284       // address of the callee into ECX. The value in ecx is used as target of
3285       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3286       // for tail calls on PIC/GOT architectures. Normally we would just put the
3287       // address of GOT into ebx and then call target@PLT. But for tail calls
3288       // ebx would be restored (since ebx is callee saved) before jumping to the
3289       // target@PLT.
3290
3291       // Note: The actual moving to ECX is done further down.
3292       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3293       if (G && !G->getGlobal()->hasLocalLinkage() &&
3294           G->getGlobal()->hasDefaultVisibility())
3295         Callee = LowerGlobalAddress(Callee, DAG);
3296       else if (isa<ExternalSymbolSDNode>(Callee))
3297         Callee = LowerExternalSymbol(Callee, DAG);
3298     }
3299   }
3300
3301   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3302     // From AMD64 ABI document:
3303     // For calls that may call functions that use varargs or stdargs
3304     // (prototype-less calls or calls to functions containing ellipsis (...) in
3305     // the declaration) %al is used as hidden argument to specify the number
3306     // of SSE registers used. The contents of %al do not need to match exactly
3307     // the number of registers, but must be an ubound on the number of SSE
3308     // registers used and is in the range 0 - 8 inclusive.
3309
3310     // Count the number of XMM registers allocated.
3311     static const MCPhysReg XMMArgRegs[] = {
3312       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3313       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3314     };
3315     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3316     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3317            && "SSE registers cannot be used when SSE is disabled");
3318
3319     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3320                                         DAG.getConstant(NumXMMRegs, dl,
3321                                                         MVT::i8)));
3322   }
3323
3324   if (isVarArg && IsMustTail) {
3325     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3326     for (const auto &F : Forwards) {
3327       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3328       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3329     }
3330   }
3331
3332   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3333   // don't need this because the eligibility check rejects calls that require
3334   // shuffling arguments passed in memory.
3335   if (!IsSibcall && isTailCall) {
3336     // Force all the incoming stack arguments to be loaded from the stack
3337     // before any new outgoing arguments are stored to the stack, because the
3338     // outgoing stack slots may alias the incoming argument stack slots, and
3339     // the alias isn't otherwise explicit. This is slightly more conservative
3340     // than necessary, because it means that each store effectively depends
3341     // on every argument instead of just those arguments it would clobber.
3342     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3343
3344     SmallVector<SDValue, 8> MemOpChains2;
3345     SDValue FIN;
3346     int FI = 0;
3347     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3348       CCValAssign &VA = ArgLocs[i];
3349       if (VA.isRegLoc())
3350         continue;
3351       assert(VA.isMemLoc());
3352       SDValue Arg = OutVals[i];
3353       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3354       // Skip inalloca arguments.  They don't require any work.
3355       if (Flags.isInAlloca())
3356         continue;
3357       // Create frame index.
3358       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3359       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3360       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3361       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3362
3363       if (Flags.isByVal()) {
3364         // Copy relative to framepointer.
3365         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3366         if (!StackPtr.getNode())
3367           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3368                                         getPointerTy(DAG.getDataLayout()));
3369         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3370                              StackPtr, Source);
3371
3372         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3373                                                          ArgChain,
3374                                                          Flags, DAG, dl));
3375       } else {
3376         // Store relative to framepointer.
3377         MemOpChains2.push_back(DAG.getStore(
3378             ArgChain, dl, Arg, FIN,
3379             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3380             false, false, 0));
3381       }
3382     }
3383
3384     if (!MemOpChains2.empty())
3385       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3386
3387     // Store the return address to the appropriate stack slot.
3388     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3389                                      getPointerTy(DAG.getDataLayout()),
3390                                      RegInfo->getSlotSize(), FPDiff, dl);
3391   }
3392
3393   // Build a sequence of copy-to-reg nodes chained together with token chain
3394   // and flag operands which copy the outgoing args into registers.
3395   SDValue InFlag;
3396   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3397     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3398                              RegsToPass[i].second, InFlag);
3399     InFlag = Chain.getValue(1);
3400   }
3401
3402   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3403     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3404     // In the 64-bit large code model, we have to make all calls
3405     // through a register, since the call instruction's 32-bit
3406     // pc-relative offset may not be large enough to hold the whole
3407     // address.
3408   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3409     // If the callee is a GlobalAddress node (quite common, every direct call
3410     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3411     // it.
3412     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3413
3414     // We should use extra load for direct calls to dllimported functions in
3415     // non-JIT mode.
3416     const GlobalValue *GV = G->getGlobal();
3417     if (!GV->hasDLLImportStorageClass()) {
3418       unsigned char OpFlags = 0;
3419       bool ExtraLoad = false;
3420       unsigned WrapperKind = ISD::DELETED_NODE;
3421
3422       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3423       // external symbols most go through the PLT in PIC mode.  If the symbol
3424       // has hidden or protected visibility, or if it is static or local, then
3425       // we don't need to use the PLT - we can directly call it.
3426       if (Subtarget->isTargetELF() &&
3427           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3428           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3429         OpFlags = X86II::MO_PLT;
3430       } else if (Subtarget->isPICStyleStubAny() &&
3431                  !GV->isStrongDefinitionForLinker() &&
3432                  (!Subtarget->getTargetTriple().isMacOSX() ||
3433                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3434         // PC-relative references to external symbols should go through $stub,
3435         // unless we're building with the leopard linker or later, which
3436         // automatically synthesizes these stubs.
3437         OpFlags = X86II::MO_DARWIN_STUB;
3438       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3439                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3440         // If the function is marked as non-lazy, generate an indirect call
3441         // which loads from the GOT directly. This avoids runtime overhead
3442         // at the cost of eager binding (and one extra byte of encoding).
3443         OpFlags = X86II::MO_GOTPCREL;
3444         WrapperKind = X86ISD::WrapperRIP;
3445         ExtraLoad = true;
3446       }
3447
3448       Callee = DAG.getTargetGlobalAddress(
3449           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3450
3451       // Add a wrapper if needed.
3452       if (WrapperKind != ISD::DELETED_NODE)
3453         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3454                              getPointerTy(DAG.getDataLayout()), Callee);
3455       // Add extra indirection if needed.
3456       if (ExtraLoad)
3457         Callee = DAG.getLoad(
3458             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3459             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3460             false, 0);
3461     }
3462   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3463     unsigned char OpFlags = 0;
3464
3465     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3466     // external symbols should go through the PLT.
3467     if (Subtarget->isTargetELF() &&
3468         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3469       OpFlags = X86II::MO_PLT;
3470     } else if (Subtarget->isPICStyleStubAny() &&
3471                (!Subtarget->getTargetTriple().isMacOSX() ||
3472                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3473       // PC-relative references to external symbols should go through $stub,
3474       // unless we're building with the leopard linker or later, which
3475       // automatically synthesizes these stubs.
3476       OpFlags = X86II::MO_DARWIN_STUB;
3477     }
3478
3479     Callee = DAG.getTargetExternalSymbol(
3480         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3481   } else if (Subtarget->isTarget64BitILP32() &&
3482              Callee->getValueType(0) == MVT::i32) {
3483     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3484     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3485   }
3486
3487   // Returns a chain & a flag for retval copy to use.
3488   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3489   SmallVector<SDValue, 8> Ops;
3490
3491   if (!IsSibcall && isTailCall) {
3492     Chain = DAG.getCALLSEQ_END(Chain,
3493                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3494                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3495     InFlag = Chain.getValue(1);
3496   }
3497
3498   Ops.push_back(Chain);
3499   Ops.push_back(Callee);
3500
3501   if (isTailCall)
3502     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3503
3504   // Add argument registers to the end of the list so that they are known live
3505   // into the call.
3506   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3507     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3508                                   RegsToPass[i].second.getValueType()));
3509
3510   // Add a register mask operand representing the call-preserved registers.
3511   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3512   assert(Mask && "Missing call preserved mask for calling convention");
3513
3514   // If this is an invoke in a 32-bit function using a funclet-based
3515   // personality, assume the function clobbers all registers. If an exception
3516   // is thrown, the runtime will not restore CSRs.
3517   // FIXME: Model this more precisely so that we can register allocate across
3518   // the normal edge and spill and fill across the exceptional edge.
3519   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3520     const Function *CallerFn = MF.getFunction();
3521     EHPersonality Pers =
3522         CallerFn->hasPersonalityFn()
3523             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3524             : EHPersonality::Unknown;
3525     if (isFuncletEHPersonality(Pers))
3526       Mask = RegInfo->getNoPreservedMask();
3527   }
3528
3529   Ops.push_back(DAG.getRegisterMask(Mask));
3530
3531   if (InFlag.getNode())
3532     Ops.push_back(InFlag);
3533
3534   if (isTailCall) {
3535     // We used to do:
3536     //// If this is the first return lowered for this function, add the regs
3537     //// to the liveout set for the function.
3538     // This isn't right, although it's probably harmless on x86; liveouts
3539     // should be computed from returns not tail calls.  Consider a void
3540     // function making a tail call to a function returning int.
3541     MF.getFrameInfo()->setHasTailCall();
3542     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3543   }
3544
3545   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3546   InFlag = Chain.getValue(1);
3547
3548   // Create the CALLSEQ_END node.
3549   unsigned NumBytesForCalleeToPop;
3550   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3551                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3552     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3553   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3554            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3555            SR == StackStructReturn)
3556     // If this is a call to a struct-return function, the callee
3557     // pops the hidden struct pointer, so we have to push it back.
3558     // This is common for Darwin/X86, Linux & Mingw32 targets.
3559     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3560     NumBytesForCalleeToPop = 4;
3561   else
3562     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3563
3564   // Returns a flag for retval copy to use.
3565   if (!IsSibcall) {
3566     Chain = DAG.getCALLSEQ_END(Chain,
3567                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3568                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3569                                                      true),
3570                                InFlag, dl);
3571     InFlag = Chain.getValue(1);
3572   }
3573
3574   // Handle result values, copying them out of physregs into vregs that we
3575   // return.
3576   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3577                          Ins, dl, DAG, InVals);
3578 }
3579
3580 //===----------------------------------------------------------------------===//
3581 //                Fast Calling Convention (tail call) implementation
3582 //===----------------------------------------------------------------------===//
3583
3584 //  Like std call, callee cleans arguments, convention except that ECX is
3585 //  reserved for storing the tail called function address. Only 2 registers are
3586 //  free for argument passing (inreg). Tail call optimization is performed
3587 //  provided:
3588 //                * tailcallopt is enabled
3589 //                * caller/callee are fastcc
3590 //  On X86_64 architecture with GOT-style position independent code only local
3591 //  (within module) calls are supported at the moment.
3592 //  To keep the stack aligned according to platform abi the function
3593 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3594 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3595 //  If a tail called function callee has more arguments than the caller the
3596 //  caller needs to make sure that there is room to move the RETADDR to. This is
3597 //  achieved by reserving an area the size of the argument delta right after the
3598 //  original RETADDR, but before the saved framepointer or the spilled registers
3599 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3600 //  stack layout:
3601 //    arg1
3602 //    arg2
3603 //    RETADDR
3604 //    [ new RETADDR
3605 //      move area ]
3606 //    (possible EBP)
3607 //    ESI
3608 //    EDI
3609 //    local1 ..
3610
3611 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3612 /// requirement.
3613 unsigned
3614 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3615                                                SelectionDAG& DAG) const {
3616   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3617   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3618   unsigned StackAlignment = TFI.getStackAlignment();
3619   uint64_t AlignMask = StackAlignment - 1;
3620   int64_t Offset = StackSize;
3621   unsigned SlotSize = RegInfo->getSlotSize();
3622   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3623     // Number smaller than 12 so just add the difference.
3624     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3625   } else {
3626     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3627     Offset = ((~AlignMask) & Offset) + StackAlignment +
3628       (StackAlignment-SlotSize);
3629   }
3630   return Offset;
3631 }
3632
3633 /// Return true if the given stack call argument is already available in the
3634 /// same position (relatively) of the caller's incoming argument stack.
3635 static
3636 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3637                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3638                          const X86InstrInfo *TII) {
3639   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3640   int FI = INT_MAX;
3641   if (Arg.getOpcode() == ISD::CopyFromReg) {
3642     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3643     if (!TargetRegisterInfo::isVirtualRegister(VR))
3644       return false;
3645     MachineInstr *Def = MRI->getVRegDef(VR);
3646     if (!Def)
3647       return false;
3648     if (!Flags.isByVal()) {
3649       if (!TII->isLoadFromStackSlot(Def, FI))
3650         return false;
3651     } else {
3652       unsigned Opcode = Def->getOpcode();
3653       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3654            Opcode == X86::LEA64_32r) &&
3655           Def->getOperand(1).isFI()) {
3656         FI = Def->getOperand(1).getIndex();
3657         Bytes = Flags.getByValSize();
3658       } else
3659         return false;
3660     }
3661   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3662     if (Flags.isByVal())
3663       // ByVal argument is passed in as a pointer but it's now being
3664       // dereferenced. e.g.
3665       // define @foo(%struct.X* %A) {
3666       //   tail call @bar(%struct.X* byval %A)
3667       // }
3668       return false;
3669     SDValue Ptr = Ld->getBasePtr();
3670     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3671     if (!FINode)
3672       return false;
3673     FI = FINode->getIndex();
3674   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3675     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3676     FI = FINode->getIndex();
3677     Bytes = Flags.getByValSize();
3678   } else
3679     return false;
3680
3681   assert(FI != INT_MAX);
3682   if (!MFI->isFixedObjectIndex(FI))
3683     return false;
3684   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3685 }
3686
3687 /// Check whether the call is eligible for tail call optimization. Targets
3688 /// that want to do tail call optimization should implement this function.
3689 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3690     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3691     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3692     const SmallVectorImpl<ISD::OutputArg> &Outs,
3693     const SmallVectorImpl<SDValue> &OutVals,
3694     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3695   if (!mayTailCallThisCC(CalleeCC))
3696     return false;
3697
3698   // If -tailcallopt is specified, make fastcc functions tail-callable.
3699   MachineFunction &MF = DAG.getMachineFunction();
3700   const Function *CallerF = MF.getFunction();
3701
3702   // If the function return type is x86_fp80 and the callee return type is not,
3703   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3704   // perform a tailcall optimization here.
3705   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3706     return false;
3707
3708   CallingConv::ID CallerCC = CallerF->getCallingConv();
3709   bool CCMatch = CallerCC == CalleeCC;
3710   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3711   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3712
3713   // Win64 functions have extra shadow space for argument homing. Don't do the
3714   // sibcall if the caller and callee have mismatched expectations for this
3715   // space.
3716   if (IsCalleeWin64 != IsCallerWin64)
3717     return false;
3718
3719   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3720     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3721       return true;
3722     return false;
3723   }
3724
3725   // Look for obvious safe cases to perform tail call optimization that do not
3726   // require ABI changes. This is what gcc calls sibcall.
3727
3728   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3729   // emit a special epilogue.
3730   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3731   if (RegInfo->needsStackRealignment(MF))
3732     return false;
3733
3734   // Also avoid sibcall optimization if either caller or callee uses struct
3735   // return semantics.
3736   if (isCalleeStructRet || isCallerStructRet)
3737     return false;
3738
3739   // Do not sibcall optimize vararg calls unless all arguments are passed via
3740   // registers.
3741   if (isVarArg && !Outs.empty()) {
3742     // Optimizing for varargs on Win64 is unlikely to be safe without
3743     // additional testing.
3744     if (IsCalleeWin64 || IsCallerWin64)
3745       return false;
3746
3747     SmallVector<CCValAssign, 16> ArgLocs;
3748     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3749                    *DAG.getContext());
3750
3751     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3752     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3753       if (!ArgLocs[i].isRegLoc())
3754         return false;
3755   }
3756
3757   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3758   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3759   // this into a sibcall.
3760   bool Unused = false;
3761   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3762     if (!Ins[i].Used) {
3763       Unused = true;
3764       break;
3765     }
3766   }
3767   if (Unused) {
3768     SmallVector<CCValAssign, 16> RVLocs;
3769     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3770                    *DAG.getContext());
3771     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3772     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3773       CCValAssign &VA = RVLocs[i];
3774       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3775         return false;
3776     }
3777   }
3778
3779   // If the calling conventions do not match, then we'd better make sure the
3780   // results are returned in the same way as what the caller expects.
3781   if (!CCMatch) {
3782     SmallVector<CCValAssign, 16> RVLocs1;
3783     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3784                     *DAG.getContext());
3785     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3786
3787     SmallVector<CCValAssign, 16> RVLocs2;
3788     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3789                     *DAG.getContext());
3790     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3791
3792     if (RVLocs1.size() != RVLocs2.size())
3793       return false;
3794     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3795       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3796         return false;
3797       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3798         return false;
3799       if (RVLocs1[i].isRegLoc()) {
3800         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3801           return false;
3802       } else {
3803         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3804           return false;
3805       }
3806     }
3807   }
3808
3809   unsigned StackArgsSize = 0;
3810
3811   // If the callee takes no arguments then go on to check the results of the
3812   // call.
3813   if (!Outs.empty()) {
3814     // Check if stack adjustment is needed. For now, do not do this if any
3815     // argument is passed on the stack.
3816     SmallVector<CCValAssign, 16> ArgLocs;
3817     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3818                    *DAG.getContext());
3819
3820     // Allocate shadow area for Win64
3821     if (IsCalleeWin64)
3822       CCInfo.AllocateStack(32, 8);
3823
3824     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3825     StackArgsSize = CCInfo.getNextStackOffset();
3826
3827     if (CCInfo.getNextStackOffset()) {
3828       // Check if the arguments are already laid out in the right way as
3829       // the caller's fixed stack objects.
3830       MachineFrameInfo *MFI = MF.getFrameInfo();
3831       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3832       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3833       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3834         CCValAssign &VA = ArgLocs[i];
3835         SDValue Arg = OutVals[i];
3836         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3837         if (VA.getLocInfo() == CCValAssign::Indirect)
3838           return false;
3839         if (!VA.isRegLoc()) {
3840           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3841                                    MFI, MRI, TII))
3842             return false;
3843         }
3844       }
3845     }
3846
3847     // If the tailcall address may be in a register, then make sure it's
3848     // possible to register allocate for it. In 32-bit, the call address can
3849     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3850     // callee-saved registers are restored. These happen to be the same
3851     // registers used to pass 'inreg' arguments so watch out for those.
3852     if (!Subtarget->is64Bit() &&
3853         ((!isa<GlobalAddressSDNode>(Callee) &&
3854           !isa<ExternalSymbolSDNode>(Callee)) ||
3855          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3856       unsigned NumInRegs = 0;
3857       // In PIC we need an extra register to formulate the address computation
3858       // for the callee.
3859       unsigned MaxInRegs =
3860         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3861
3862       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3863         CCValAssign &VA = ArgLocs[i];
3864         if (!VA.isRegLoc())
3865           continue;
3866         unsigned Reg = VA.getLocReg();
3867         switch (Reg) {
3868         default: break;
3869         case X86::EAX: case X86::EDX: case X86::ECX:
3870           if (++NumInRegs == MaxInRegs)
3871             return false;
3872           break;
3873         }
3874       }
3875     }
3876   }
3877
3878   bool CalleeWillPop =
3879       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3880                        MF.getTarget().Options.GuaranteedTailCallOpt);
3881
3882   if (unsigned BytesToPop =
3883           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3884     // If we have bytes to pop, the callee must pop them.
3885     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3886     if (!CalleePopMatches)
3887       return false;
3888   } else if (CalleeWillPop && StackArgsSize > 0) {
3889     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3890     return false;
3891   }
3892
3893   return true;
3894 }
3895
3896 FastISel *
3897 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3898                                   const TargetLibraryInfo *libInfo) const {
3899   return X86::createFastISel(funcInfo, libInfo);
3900 }
3901
3902 //===----------------------------------------------------------------------===//
3903 //                           Other Lowering Hooks
3904 //===----------------------------------------------------------------------===//
3905
3906 static bool MayFoldLoad(SDValue Op) {
3907   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3908 }
3909
3910 static bool MayFoldIntoStore(SDValue Op) {
3911   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3912 }
3913
3914 static bool isTargetShuffle(unsigned Opcode) {
3915   switch(Opcode) {
3916   default: return false;
3917   case X86ISD::BLENDI:
3918   case X86ISD::PSHUFB:
3919   case X86ISD::PSHUFD:
3920   case X86ISD::PSHUFHW:
3921   case X86ISD::PSHUFLW:
3922   case X86ISD::SHUFP:
3923   case X86ISD::INSERTPS:
3924   case X86ISD::PALIGNR:
3925   case X86ISD::MOVLHPS:
3926   case X86ISD::MOVLHPD:
3927   case X86ISD::MOVHLPS:
3928   case X86ISD::MOVLPS:
3929   case X86ISD::MOVLPD:
3930   case X86ISD::MOVSHDUP:
3931   case X86ISD::MOVSLDUP:
3932   case X86ISD::MOVDDUP:
3933   case X86ISD::MOVSS:
3934   case X86ISD::MOVSD:
3935   case X86ISD::UNPCKL:
3936   case X86ISD::UNPCKH:
3937   case X86ISD::VPERMILPI:
3938   case X86ISD::VPERM2X128:
3939   case X86ISD::VPERMI:
3940   case X86ISD::VPERMV:
3941   case X86ISD::VPERMV3:
3942     return true;
3943   }
3944 }
3945
3946 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3947                                     SDValue V1, unsigned TargetMask,
3948                                     SelectionDAG &DAG) {
3949   switch(Opc) {
3950   default: llvm_unreachable("Unknown x86 shuffle node");
3951   case X86ISD::PSHUFD:
3952   case X86ISD::PSHUFHW:
3953   case X86ISD::PSHUFLW:
3954   case X86ISD::VPERMILPI:
3955   case X86ISD::VPERMI:
3956     return DAG.getNode(Opc, dl, VT, V1,
3957                        DAG.getConstant(TargetMask, dl, MVT::i8));
3958   }
3959 }
3960
3961 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3962                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3963   switch(Opc) {
3964   default: llvm_unreachable("Unknown x86 shuffle node");
3965   case X86ISD::MOVLHPS:
3966   case X86ISD::MOVLHPD:
3967   case X86ISD::MOVHLPS:
3968   case X86ISD::MOVLPS:
3969   case X86ISD::MOVLPD:
3970   case X86ISD::MOVSS:
3971   case X86ISD::MOVSD:
3972   case X86ISD::UNPCKL:
3973   case X86ISD::UNPCKH:
3974     return DAG.getNode(Opc, dl, VT, V1, V2);
3975   }
3976 }
3977
3978 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3979   MachineFunction &MF = DAG.getMachineFunction();
3980   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3981   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3982   int ReturnAddrIndex = FuncInfo->getRAIndex();
3983
3984   if (ReturnAddrIndex == 0) {
3985     // Set up a frame object for the return address.
3986     unsigned SlotSize = RegInfo->getSlotSize();
3987     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3988                                                            -(int64_t)SlotSize,
3989                                                            false);
3990     FuncInfo->setRAIndex(ReturnAddrIndex);
3991   }
3992
3993   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3994 }
3995
3996 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3997                                        bool hasSymbolicDisplacement) {
3998   // Offset should fit into 32 bit immediate field.
3999   if (!isInt<32>(Offset))
4000     return false;
4001
4002   // If we don't have a symbolic displacement - we don't have any extra
4003   // restrictions.
4004   if (!hasSymbolicDisplacement)
4005     return true;
4006
4007   // FIXME: Some tweaks might be needed for medium code model.
4008   if (M != CodeModel::Small && M != CodeModel::Kernel)
4009     return false;
4010
4011   // For small code model we assume that latest object is 16MB before end of 31
4012   // bits boundary. We may also accept pretty large negative constants knowing
4013   // that all objects are in the positive half of address space.
4014   if (M == CodeModel::Small && Offset < 16*1024*1024)
4015     return true;
4016
4017   // For kernel code model we know that all object resist in the negative half
4018   // of 32bits address space. We may not accept negative offsets, since they may
4019   // be just off and we may accept pretty large positive ones.
4020   if (M == CodeModel::Kernel && Offset >= 0)
4021     return true;
4022
4023   return false;
4024 }
4025
4026 /// Determines whether the callee is required to pop its own arguments.
4027 /// Callee pop is necessary to support tail calls.
4028 bool X86::isCalleePop(CallingConv::ID CallingConv,
4029                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4030   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4031   // can guarantee TCO.
4032   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4033     return true;
4034
4035   switch (CallingConv) {
4036   default:
4037     return false;
4038   case CallingConv::X86_StdCall:
4039   case CallingConv::X86_FastCall:
4040   case CallingConv::X86_ThisCall:
4041   case CallingConv::X86_VectorCall:
4042     return !is64Bit;
4043   }
4044 }
4045
4046 /// \brief Return true if the condition is an unsigned comparison operation.
4047 static bool isX86CCUnsigned(unsigned X86CC) {
4048   switch (X86CC) {
4049   default: llvm_unreachable("Invalid integer condition!");
4050   case X86::COND_E:     return true;
4051   case X86::COND_G:     return false;
4052   case X86::COND_GE:    return false;
4053   case X86::COND_L:     return false;
4054   case X86::COND_LE:    return false;
4055   case X86::COND_NE:    return true;
4056   case X86::COND_B:     return true;
4057   case X86::COND_A:     return true;
4058   case X86::COND_BE:    return true;
4059   case X86::COND_AE:    return true;
4060   }
4061 }
4062
4063 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4064   switch (SetCCOpcode) {
4065   default: llvm_unreachable("Invalid integer condition!");
4066   case ISD::SETEQ:  return X86::COND_E;
4067   case ISD::SETGT:  return X86::COND_G;
4068   case ISD::SETGE:  return X86::COND_GE;
4069   case ISD::SETLT:  return X86::COND_L;
4070   case ISD::SETLE:  return X86::COND_LE;
4071   case ISD::SETNE:  return X86::COND_NE;
4072   case ISD::SETULT: return X86::COND_B;
4073   case ISD::SETUGT: return X86::COND_A;
4074   case ISD::SETULE: return X86::COND_BE;
4075   case ISD::SETUGE: return X86::COND_AE;
4076   }
4077 }
4078
4079 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4080 /// condition code, returning the condition code and the LHS/RHS of the
4081 /// comparison to make.
4082 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4083                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4084   if (!isFP) {
4085     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4086       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4087         // X > -1   -> X == 0, jump !sign.
4088         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4089         return X86::COND_NS;
4090       }
4091       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4092         // X < 0   -> X == 0, jump on sign.
4093         return X86::COND_S;
4094       }
4095       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4096         // X < 1   -> X <= 0
4097         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4098         return X86::COND_LE;
4099       }
4100     }
4101
4102     return TranslateIntegerX86CC(SetCCOpcode);
4103   }
4104
4105   // First determine if it is required or is profitable to flip the operands.
4106
4107   // If LHS is a foldable load, but RHS is not, flip the condition.
4108   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4109       !ISD::isNON_EXTLoad(RHS.getNode())) {
4110     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4111     std::swap(LHS, RHS);
4112   }
4113
4114   switch (SetCCOpcode) {
4115   default: break;
4116   case ISD::SETOLT:
4117   case ISD::SETOLE:
4118   case ISD::SETUGT:
4119   case ISD::SETUGE:
4120     std::swap(LHS, RHS);
4121     break;
4122   }
4123
4124   // On a floating point condition, the flags are set as follows:
4125   // ZF  PF  CF   op
4126   //  0 | 0 | 0 | X > Y
4127   //  0 | 0 | 1 | X < Y
4128   //  1 | 0 | 0 | X == Y
4129   //  1 | 1 | 1 | unordered
4130   switch (SetCCOpcode) {
4131   default: llvm_unreachable("Condcode should be pre-legalized away");
4132   case ISD::SETUEQ:
4133   case ISD::SETEQ:   return X86::COND_E;
4134   case ISD::SETOLT:              // flipped
4135   case ISD::SETOGT:
4136   case ISD::SETGT:   return X86::COND_A;
4137   case ISD::SETOLE:              // flipped
4138   case ISD::SETOGE:
4139   case ISD::SETGE:   return X86::COND_AE;
4140   case ISD::SETUGT:              // flipped
4141   case ISD::SETULT:
4142   case ISD::SETLT:   return X86::COND_B;
4143   case ISD::SETUGE:              // flipped
4144   case ISD::SETULE:
4145   case ISD::SETLE:   return X86::COND_BE;
4146   case ISD::SETONE:
4147   case ISD::SETNE:   return X86::COND_NE;
4148   case ISD::SETUO:   return X86::COND_P;
4149   case ISD::SETO:    return X86::COND_NP;
4150   case ISD::SETOEQ:
4151   case ISD::SETUNE:  return X86::COND_INVALID;
4152   }
4153 }
4154
4155 /// Is there a floating point cmov for the specific X86 condition code?
4156 /// Current x86 isa includes the following FP cmov instructions:
4157 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4158 static bool hasFPCMov(unsigned X86CC) {
4159   switch (X86CC) {
4160   default:
4161     return false;
4162   case X86::COND_B:
4163   case X86::COND_BE:
4164   case X86::COND_E:
4165   case X86::COND_P:
4166   case X86::COND_A:
4167   case X86::COND_AE:
4168   case X86::COND_NE:
4169   case X86::COND_NP:
4170     return true;
4171   }
4172 }
4173
4174
4175 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
4176                                            const CallInst &I,
4177                                            unsigned Intrinsic) const {
4178
4179   const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
4180   if (!IntrData)
4181     return false;
4182
4183   switch (IntrData->Type) {
4184   case LOADA:
4185   case LOADU: {
4186     Info.opc = ISD::INTRINSIC_W_CHAIN;
4187     Info.memVT = MVT::getVT(I.getType());
4188     Info.ptrVal = I.getArgOperand(0);
4189     Info.offset = 0;
4190     Info.align = (IntrData->Type == LOADA ? Info.memVT.getSizeInBits()/8 : 1);
4191     Info.vol = false;
4192     Info.readMem = true;
4193     Info.writeMem = false;
4194     return true;
4195   }
4196   default:
4197     break;
4198   }
4199
4200   return false;
4201 }
4202
4203 /// Returns true if the target can instruction select the
4204 /// specified FP immediate natively. If false, the legalizer will
4205 /// materialize the FP immediate as a load from a constant pool.
4206 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4207   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4208     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4209       return true;
4210   }
4211   return false;
4212 }
4213
4214 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4215                                               ISD::LoadExtType ExtTy,
4216                                               EVT NewVT) const {
4217   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4218   // relocation target a movq or addq instruction: don't let the load shrink.
4219   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4220   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4221     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4222       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4223   return true;
4224 }
4225
4226 /// \brief Returns true if it is beneficial to convert a load of a constant
4227 /// to just the constant itself.
4228 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4229                                                           Type *Ty) const {
4230   assert(Ty->isIntegerTy());
4231
4232   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4233   if (BitSize == 0 || BitSize > 64)
4234     return false;
4235   return true;
4236 }
4237
4238 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4239                                                 unsigned Index) const {
4240   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4241     return false;
4242
4243   return (Index == 0 || Index == ResVT.getVectorNumElements());
4244 }
4245
4246 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4247   // Speculate cttz only if we can directly use TZCNT.
4248   return Subtarget->hasBMI();
4249 }
4250
4251 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4252   // Speculate ctlz only if we can directly use LZCNT.
4253   return Subtarget->hasLZCNT();
4254 }
4255
4256 /// Return true if every element in Mask, beginning
4257 /// from position Pos and ending in Pos+Size is undef.
4258 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4259   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4260     if (0 <= Mask[i])
4261       return false;
4262   return true;
4263 }
4264
4265 /// Return true if Val is undef or if its value falls within the
4266 /// specified range (L, H].
4267 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4268   return (Val < 0) || (Val >= Low && Val < Hi);
4269 }
4270
4271 /// Val is either less than zero (undef) or equal to the specified value.
4272 static bool isUndefOrEqual(int Val, int CmpVal) {
4273   return (Val < 0 || Val == CmpVal);
4274 }
4275
4276 /// Return true if every element in Mask, beginning
4277 /// from position Pos and ending in Pos+Size, falls within the specified
4278 /// sequential range (Low, Low+Size]. or is undef.
4279 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4280                                        unsigned Pos, unsigned Size, int Low) {
4281   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4282     if (!isUndefOrEqual(Mask[i], Low))
4283       return false;
4284   return true;
4285 }
4286
4287 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4288 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4289 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4290   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4291   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4292     return false;
4293
4294   // The index should be aligned on a vecWidth-bit boundary.
4295   uint64_t Index =
4296     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4297
4298   MVT VT = N->getSimpleValueType(0);
4299   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4300   bool Result = (Index * ElSize) % vecWidth == 0;
4301
4302   return Result;
4303 }
4304
4305 /// Return true if the specified INSERT_SUBVECTOR
4306 /// operand specifies a subvector insert that is suitable for input to
4307 /// insertion of 128 or 256-bit subvectors
4308 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4309   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4310   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4311     return false;
4312   // The index should be aligned on a vecWidth-bit boundary.
4313   uint64_t Index =
4314     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4315
4316   MVT VT = N->getSimpleValueType(0);
4317   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4318   bool Result = (Index * ElSize) % vecWidth == 0;
4319
4320   return Result;
4321 }
4322
4323 bool X86::isVINSERT128Index(SDNode *N) {
4324   return isVINSERTIndex(N, 128);
4325 }
4326
4327 bool X86::isVINSERT256Index(SDNode *N) {
4328   return isVINSERTIndex(N, 256);
4329 }
4330
4331 bool X86::isVEXTRACT128Index(SDNode *N) {
4332   return isVEXTRACTIndex(N, 128);
4333 }
4334
4335 bool X86::isVEXTRACT256Index(SDNode *N) {
4336   return isVEXTRACTIndex(N, 256);
4337 }
4338
4339 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4340   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4341   assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4342          "Illegal extract subvector for VEXTRACT");
4343
4344   uint64_t Index =
4345     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4346
4347   MVT VecVT = N->getOperand(0).getSimpleValueType();
4348   MVT ElVT = VecVT.getVectorElementType();
4349
4350   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4351   return Index / NumElemsPerChunk;
4352 }
4353
4354 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4355   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4356   assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4357          "Illegal insert subvector for VINSERT");
4358
4359   uint64_t Index =
4360     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4361
4362   MVT VecVT = N->getSimpleValueType(0);
4363   MVT ElVT = VecVT.getVectorElementType();
4364
4365   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4366   return Index / NumElemsPerChunk;
4367 }
4368
4369 /// Return the appropriate immediate to extract the specified
4370 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4371 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4372   return getExtractVEXTRACTImmediate(N, 128);
4373 }
4374
4375 /// Return the appropriate immediate to extract the specified
4376 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4377 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4378   return getExtractVEXTRACTImmediate(N, 256);
4379 }
4380
4381 /// Return the appropriate immediate to insert at the specified
4382 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4383 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4384   return getInsertVINSERTImmediate(N, 128);
4385 }
4386
4387 /// Return the appropriate immediate to insert at the specified
4388 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4389 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4390   return getInsertVINSERTImmediate(N, 256);
4391 }
4392
4393 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4394 bool X86::isZeroNode(SDValue Elt) {
4395   return isNullConstant(Elt) || isNullFPConstant(Elt);
4396 }
4397
4398 // Build a vector of constants
4399 // Use an UNDEF node if MaskElt == -1.
4400 // Spilt 64-bit constants in the 32-bit mode.
4401 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4402                               SelectionDAG &DAG,
4403                               SDLoc dl, bool IsMask = false) {
4404
4405   SmallVector<SDValue, 32>  Ops;
4406   bool Split = false;
4407
4408   MVT ConstVecVT = VT;
4409   unsigned NumElts = VT.getVectorNumElements();
4410   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4411   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4412     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4413     Split = true;
4414   }
4415
4416   MVT EltVT = ConstVecVT.getVectorElementType();
4417   for (unsigned i = 0; i < NumElts; ++i) {
4418     bool IsUndef = Values[i] < 0 && IsMask;
4419     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4420       DAG.getConstant(Values[i], dl, EltVT);
4421     Ops.push_back(OpNode);
4422     if (Split)
4423       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4424                     DAG.getConstant(0, dl, EltVT));
4425   }
4426   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4427   if (Split)
4428     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4429   return ConstsNode;
4430 }
4431
4432 /// Returns a vector of specified type with all zero elements.
4433 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4434                              SelectionDAG &DAG, SDLoc dl) {
4435   assert(VT.isVector() && "Expected a vector type");
4436
4437   // Always build SSE zero vectors as <4 x i32> bitcasted
4438   // to their dest type. This ensures they get CSE'd.
4439   SDValue Vec;
4440   if (VT.is128BitVector()) {  // SSE
4441     if (Subtarget->hasSSE2()) {  // SSE2
4442       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4443       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4444     } else { // SSE1
4445       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4446       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4447     }
4448   } else if (VT.is256BitVector()) { // AVX
4449     if (Subtarget->hasInt256()) { // AVX2
4450       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4451       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4452       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4453     } else {
4454       // 256-bit logic and arithmetic instructions in AVX are all
4455       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4456       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4457       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4458       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4459     }
4460   } else if (VT.is512BitVector()) { // AVX-512
4461       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4462       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4463                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4464       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4465   } else if (VT.getVectorElementType() == MVT::i1) {
4466
4467     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4468             && "Unexpected vector type");
4469     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4470             && "Unexpected vector type");
4471     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4472     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4473     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4474   } else
4475     llvm_unreachable("Unexpected vector type");
4476
4477   return DAG.getBitcast(VT, Vec);
4478 }
4479
4480 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4481                                 SelectionDAG &DAG, SDLoc dl,
4482                                 unsigned vectorWidth) {
4483   assert((vectorWidth == 128 || vectorWidth == 256) &&
4484          "Unsupported vector width");
4485   EVT VT = Vec.getValueType();
4486   EVT ElVT = VT.getVectorElementType();
4487   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4488   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4489                                   VT.getVectorNumElements()/Factor);
4490
4491   // Extract from UNDEF is UNDEF.
4492   if (Vec.getOpcode() == ISD::UNDEF)
4493     return DAG.getUNDEF(ResultVT);
4494
4495   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4496   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4497   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4498
4499   // This is the index of the first element of the vectorWidth-bit chunk
4500   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4501   IdxVal &= ~(ElemsPerChunk - 1);
4502
4503   // If the input is a buildvector just emit a smaller one.
4504   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4505     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4506                        makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4507
4508   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4509   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4510 }
4511
4512 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4513 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4514 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4515 /// instructions or a simple subregister reference. Idx is an index in the
4516 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4517 /// lowering EXTRACT_VECTOR_ELT operations easier.
4518 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4519                                    SelectionDAG &DAG, SDLoc dl) {
4520   assert((Vec.getValueType().is256BitVector() ||
4521           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4522   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4523 }
4524
4525 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4526 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4527                                    SelectionDAG &DAG, SDLoc dl) {
4528   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4529   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4530 }
4531
4532 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4533                                unsigned IdxVal, SelectionDAG &DAG,
4534                                SDLoc dl, unsigned vectorWidth) {
4535   assert((vectorWidth == 128 || vectorWidth == 256) &&
4536          "Unsupported vector width");
4537   // Inserting UNDEF is Result
4538   if (Vec.getOpcode() == ISD::UNDEF)
4539     return Result;
4540   EVT VT = Vec.getValueType();
4541   EVT ElVT = VT.getVectorElementType();
4542   EVT ResultVT = Result.getValueType();
4543
4544   // Insert the relevant vectorWidth bits.
4545   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4546   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4547
4548   // This is the index of the first element of the vectorWidth-bit chunk
4549   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4550   IdxVal &= ~(ElemsPerChunk - 1);
4551
4552   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4553   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4554 }
4555
4556 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4557 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4558 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4559 /// simple superregister reference.  Idx is an index in the 128 bits
4560 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4561 /// lowering INSERT_VECTOR_ELT operations easier.
4562 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4563                                   SelectionDAG &DAG, SDLoc dl) {
4564   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4565
4566   // For insertion into the zero index (low half) of a 256-bit vector, it is
4567   // more efficient to generate a blend with immediate instead of an insert*128.
4568   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4569   // extend the subvector to the size of the result vector. Make sure that
4570   // we are not recursing on that node by checking for undef here.
4571   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4572       Result.getOpcode() != ISD::UNDEF) {
4573     EVT ResultVT = Result.getValueType();
4574     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4575     SDValue Undef = DAG.getUNDEF(ResultVT);
4576     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4577                                  Vec, ZeroIndex);
4578
4579     // The blend instruction, and therefore its mask, depend on the data type.
4580     MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4581     if (ScalarType.isFloatingPoint()) {
4582       // Choose either vblendps (float) or vblendpd (double).
4583       unsigned ScalarSize = ScalarType.getSizeInBits();
4584       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4585       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4586       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4587       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4588     }
4589
4590     const X86Subtarget &Subtarget =
4591     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4592
4593     // AVX2 is needed for 256-bit integer blend support.
4594     // Integers must be cast to 32-bit because there is only vpblendd;
4595     // vpblendw can't be used for this because it has a handicapped mask.
4596
4597     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4598     // is still more efficient than using the wrong domain vinsertf128 that
4599     // will be created by InsertSubVector().
4600     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4601
4602     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4603     Result = DAG.getBitcast(CastVT, Result);
4604     Vec256 = DAG.getBitcast(CastVT, Vec256);
4605     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4606     return DAG.getBitcast(ResultVT, Vec256);
4607   }
4608
4609   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4610 }
4611
4612 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4613                                   SelectionDAG &DAG, SDLoc dl) {
4614   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4615   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4616 }
4617
4618 /// Insert i1-subvector to i1-vector.
4619 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4620
4621   SDLoc dl(Op);
4622   SDValue Vec = Op.getOperand(0);
4623   SDValue SubVec = Op.getOperand(1);
4624   SDValue Idx = Op.getOperand(2);
4625
4626   if (!isa<ConstantSDNode>(Idx))
4627     return SDValue();
4628
4629   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4630   if (IdxVal == 0  && Vec.isUndef()) // the operation is legal
4631     return Op;
4632
4633   MVT OpVT = Op.getSimpleValueType();
4634   MVT SubVecVT = SubVec.getSimpleValueType();
4635   unsigned NumElems = OpVT.getVectorNumElements();
4636   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4637
4638   assert(IdxVal + SubVecNumElems <= NumElems &&
4639          IdxVal % SubVecVT.getSizeInBits() == 0 &&
4640          "Unexpected index value in INSERT_SUBVECTOR");
4641
4642   // There are 3 possible cases:
4643   // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4644   // 2. Subvector should be inserted in the upper part
4645   //    (IdxVal + SubVecNumElems == NumElems)
4646   // 3. Subvector should be inserted in the middle (for example v2i1
4647   //    to v16i1, index 2)
4648
4649   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4650   SDValue Undef = DAG.getUNDEF(OpVT);
4651   SDValue WideSubVec =
4652     DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4653   if (Vec.isUndef())
4654     return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4655       DAG.getConstant(IdxVal, dl, MVT::i8));
4656
4657   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4658     unsigned ShiftLeft = NumElems - SubVecNumElems;
4659     unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4660     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4661       DAG.getConstant(ShiftLeft, dl, MVT::i8));
4662     return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4663       DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4664   }
4665
4666   if (IdxVal == 0) {
4667     // Zero lower bits of the Vec
4668     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4669     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4670     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4671     // Merge them together
4672     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4673   }
4674
4675   // Simple case when we put subvector in the upper part
4676   if (IdxVal + SubVecNumElems == NumElems) {
4677     // Zero upper bits of the Vec
4678     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4679                         DAG.getConstant(IdxVal, dl, MVT::i8));
4680     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4681     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4682     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4683     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4684   }
4685   // Subvector should be inserted in the middle - use shuffle
4686   SmallVector<int, 64> Mask;
4687   for (unsigned i = 0; i < NumElems; ++i)
4688     Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4689                     i : i + NumElems);
4690   return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4691 }
4692
4693 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4694 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4695 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4696 /// large BUILD_VECTORS.
4697 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4698                                    unsigned NumElems, SelectionDAG &DAG,
4699                                    SDLoc dl) {
4700   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4701   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4702 }
4703
4704 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4705                                    unsigned NumElems, SelectionDAG &DAG,
4706                                    SDLoc dl) {
4707   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4708   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4709 }
4710
4711 /// Returns a vector of specified type with all bits set.
4712 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4713 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4714 /// Then bitcast to their original type, ensuring they get CSE'd.
4715 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4716                              SelectionDAG &DAG, SDLoc dl) {
4717   assert(VT.isVector() && "Expected a vector type");
4718
4719   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4720   SDValue Vec;
4721   if (VT.is512BitVector()) {
4722     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4723                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4724     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4725   } else if (VT.is256BitVector()) {
4726     if (Subtarget->hasInt256()) { // AVX2
4727       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4728       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4729     } else { // AVX
4730       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4731       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4732     }
4733   } else if (VT.is128BitVector()) {
4734     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4735   } else
4736     llvm_unreachable("Unexpected vector type");
4737
4738   return DAG.getBitcast(VT, Vec);
4739 }
4740
4741 /// Returns a vector_shuffle node for an unpackl operation.
4742 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4743                           SDValue V2) {
4744   unsigned NumElems = VT.getVectorNumElements();
4745   SmallVector<int, 8> Mask;
4746   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4747     Mask.push_back(i);
4748     Mask.push_back(i + NumElems);
4749   }
4750   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4751 }
4752
4753 /// Returns a vector_shuffle node for an unpackh operation.
4754 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4755                           SDValue V2) {
4756   unsigned NumElems = VT.getVectorNumElements();
4757   SmallVector<int, 8> Mask;
4758   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4759     Mask.push_back(i + Half);
4760     Mask.push_back(i + NumElems + Half);
4761   }
4762   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4763 }
4764
4765 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4766 /// This produces a shuffle where the low element of V2 is swizzled into the
4767 /// zero/undef vector, landing at element Idx.
4768 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4769 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4770                                            bool IsZero,
4771                                            const X86Subtarget *Subtarget,
4772                                            SelectionDAG &DAG) {
4773   MVT VT = V2.getSimpleValueType();
4774   SDValue V1 = IsZero
4775     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4776   unsigned NumElems = VT.getVectorNumElements();
4777   SmallVector<int, 16> MaskVec;
4778   for (unsigned i = 0; i != NumElems; ++i)
4779     // If this is the insertion idx, put the low elt of V2 here.
4780     MaskVec.push_back(i == Idx ? NumElems : i);
4781   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4782 }
4783
4784 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4785 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4786 /// uses one source. Note that this will set IsUnary for shuffles which use a
4787 /// single input multiple times, and in those cases it will
4788 /// adjust the mask to only have indices within that single input.
4789 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
4790                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4791   unsigned NumElems = VT.getVectorNumElements();
4792   SDValue ImmN;
4793
4794   IsUnary = false;
4795   bool IsFakeUnary = false;
4796   switch(N->getOpcode()) {
4797   case X86ISD::BLENDI:
4798     ImmN = N->getOperand(N->getNumOperands()-1);
4799     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4800     break;
4801   case X86ISD::SHUFP:
4802     ImmN = N->getOperand(N->getNumOperands()-1);
4803     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4804     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4805     break;
4806   case X86ISD::INSERTPS:
4807     ImmN = N->getOperand(N->getNumOperands()-1);
4808     DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4809     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4810     break;
4811   case X86ISD::UNPCKH:
4812     DecodeUNPCKHMask(VT, Mask);
4813     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4814     break;
4815   case X86ISD::UNPCKL:
4816     DecodeUNPCKLMask(VT, Mask);
4817     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4818     break;
4819   case X86ISD::MOVHLPS:
4820     DecodeMOVHLPSMask(NumElems, Mask);
4821     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4822     break;
4823   case X86ISD::MOVLHPS:
4824     DecodeMOVLHPSMask(NumElems, Mask);
4825     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4826     break;
4827   case X86ISD::PALIGNR:
4828     ImmN = N->getOperand(N->getNumOperands()-1);
4829     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4830     break;
4831   case X86ISD::PSHUFD:
4832   case X86ISD::VPERMILPI:
4833     ImmN = N->getOperand(N->getNumOperands()-1);
4834     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4835     IsUnary = true;
4836     break;
4837   case X86ISD::PSHUFHW:
4838     ImmN = N->getOperand(N->getNumOperands()-1);
4839     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4840     IsUnary = true;
4841     break;
4842   case X86ISD::PSHUFLW:
4843     ImmN = N->getOperand(N->getNumOperands()-1);
4844     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4845     IsUnary = true;
4846     break;
4847   case X86ISD::PSHUFB: {
4848     IsUnary = true;
4849     SDValue MaskNode = N->getOperand(1);
4850     while (MaskNode->getOpcode() == ISD::BITCAST)
4851       MaskNode = MaskNode->getOperand(0);
4852
4853     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4854       // If we have a build-vector, then things are easy.
4855       MVT VT = MaskNode.getSimpleValueType();
4856       assert(VT.isVector() &&
4857              "Can't produce a non-vector with a build_vector!");
4858       if (!VT.isInteger())
4859         return false;
4860
4861       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4862
4863       SmallVector<uint64_t, 32> RawMask;
4864       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4865         SDValue Op = MaskNode->getOperand(i);
4866         if (Op->getOpcode() == ISD::UNDEF) {
4867           RawMask.push_back((uint64_t)SM_SentinelUndef);
4868           continue;
4869         }
4870         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4871         if (!CN)
4872           return false;
4873         APInt MaskElement = CN->getAPIntValue();
4874
4875         // We now have to decode the element which could be any integer size and
4876         // extract each byte of it.
4877         for (int j = 0; j < NumBytesPerElement; ++j) {
4878           // Note that this is x86 and so always little endian: the low byte is
4879           // the first byte of the mask.
4880           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4881           MaskElement = MaskElement.lshr(8);
4882         }
4883       }
4884       DecodePSHUFBMask(RawMask, Mask);
4885       break;
4886     }
4887
4888     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4889     if (!MaskLoad)
4890       return false;
4891
4892     SDValue Ptr = MaskLoad->getBasePtr();
4893     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4894         Ptr->getOpcode() == X86ISD::WrapperRIP)
4895       Ptr = Ptr->getOperand(0);
4896
4897     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4898     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4899       return false;
4900
4901     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4902       DecodePSHUFBMask(C, Mask);
4903       break;
4904     }
4905
4906     return false;
4907   }
4908   case X86ISD::VPERMI:
4909     ImmN = N->getOperand(N->getNumOperands()-1);
4910     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4911     IsUnary = true;
4912     break;
4913   case X86ISD::MOVSS:
4914   case X86ISD::MOVSD:
4915     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4916     break;
4917   case X86ISD::VPERM2X128:
4918     ImmN = N->getOperand(N->getNumOperands()-1);
4919     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4920     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4921     break;
4922   case X86ISD::MOVSLDUP:
4923     DecodeMOVSLDUPMask(VT, Mask);
4924     IsUnary = true;
4925     break;
4926   case X86ISD::MOVSHDUP:
4927     DecodeMOVSHDUPMask(VT, Mask);
4928     IsUnary = true;
4929     break;
4930   case X86ISD::MOVDDUP:
4931     DecodeMOVDDUPMask(VT, Mask);
4932     IsUnary = true;
4933     break;
4934   case X86ISD::MOVLHPD:
4935   case X86ISD::MOVLPD:
4936   case X86ISD::MOVLPS:
4937     // Not yet implemented
4938     return false;
4939   case X86ISD::VPERMV: {
4940     IsUnary = true;
4941     SDValue MaskNode = N->getOperand(0);
4942     while (MaskNode->getOpcode() == ISD::BITCAST)
4943       MaskNode = MaskNode->getOperand(0);
4944
4945     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4946     SmallVector<uint64_t, 32> RawMask;
4947     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4948       // If we have a build-vector, then things are easy.
4949       assert(MaskNode.getSimpleValueType().isInteger() &&
4950              MaskNode.getSimpleValueType().getVectorNumElements() ==
4951              VT.getVectorNumElements());
4952
4953       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4954         SDValue Op = MaskNode->getOperand(i);
4955         if (Op->getOpcode() == ISD::UNDEF)
4956           RawMask.push_back((uint64_t)SM_SentinelUndef);
4957         else if (isa<ConstantSDNode>(Op)) {
4958           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4959           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4960         } else
4961           return false;
4962       }
4963       DecodeVPERMVMask(RawMask, Mask);
4964       break;
4965     }
4966     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4967       unsigned NumEltsInMask = MaskNode->getNumOperands();
4968       MaskNode = MaskNode->getOperand(0);
4969       if (auto *CN = dyn_cast<ConstantSDNode>(MaskNode)) {
4970         APInt MaskEltValue = CN->getAPIntValue();
4971         for (unsigned i = 0; i < NumEltsInMask; ++i)
4972           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4973         DecodeVPERMVMask(RawMask, Mask);
4974         break;
4975       }
4976       // It may be a scalar load
4977     }
4978
4979     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4980     if (!MaskLoad)
4981       return false;
4982
4983     SDValue Ptr = MaskLoad->getBasePtr();
4984     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4985         Ptr->getOpcode() == X86ISD::WrapperRIP)
4986       Ptr = Ptr->getOperand(0);
4987
4988     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4989     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4990       return false;
4991
4992     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4993       DecodeVPERMVMask(C, VT, Mask);
4994       break;
4995     }
4996     return false;
4997   }
4998   case X86ISD::VPERMV3: {
4999     IsUnary = false;
5000     SDValue MaskNode = N->getOperand(1);
5001     while (MaskNode->getOpcode() == ISD::BITCAST)
5002       MaskNode = MaskNode->getOperand(1);
5003
5004     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5005       // If we have a build-vector, then things are easy.
5006       assert(MaskNode.getSimpleValueType().isInteger() &&
5007              MaskNode.getSimpleValueType().getVectorNumElements() ==
5008              VT.getVectorNumElements());
5009
5010       SmallVector<uint64_t, 32> RawMask;
5011       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
5012
5013       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
5014         SDValue Op = MaskNode->getOperand(i);
5015         if (Op->getOpcode() == ISD::UNDEF)
5016           RawMask.push_back((uint64_t)SM_SentinelUndef);
5017         else {
5018           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5019           if (!CN)
5020             return false;
5021           APInt MaskElement = CN->getAPIntValue();
5022           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
5023         }
5024       }
5025       DecodeVPERMV3Mask(RawMask, Mask);
5026       break;
5027     }
5028
5029     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5030     if (!MaskLoad)
5031       return false;
5032
5033     SDValue Ptr = MaskLoad->getBasePtr();
5034     if (Ptr->getOpcode() == X86ISD::Wrapper ||
5035         Ptr->getOpcode() == X86ISD::WrapperRIP)
5036       Ptr = Ptr->getOperand(0);
5037
5038     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5039     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5040       return false;
5041
5042     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5043       DecodeVPERMV3Mask(C, VT, Mask);
5044       break;
5045     }
5046     return false;
5047   }
5048   default: llvm_unreachable("unknown target shuffle node");
5049   }
5050
5051   // Empty mask indicates the decode failed.
5052   if (Mask.empty())
5053     return false;
5054
5055   // Check if we're getting a shuffle mask with zero'd elements.
5056   if (!AllowSentinelZero)
5057     if (std::any_of(Mask.begin(), Mask.end(),
5058                     [](int M){ return M == SM_SentinelZero; }))
5059       return false;
5060
5061   // If we have a fake unary shuffle, the shuffle mask is spread across two
5062   // inputs that are actually the same node. Re-map the mask to always point
5063   // into the first input.
5064   if (IsFakeUnary)
5065     for (int &M : Mask)
5066       if (M >= (int)Mask.size())
5067         M -= Mask.size();
5068
5069   return true;
5070 }
5071
5072 /// Returns the scalar element that will make up the ith
5073 /// element of the result of the vector shuffle.
5074 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5075                                    unsigned Depth) {
5076   if (Depth == 6)
5077     return SDValue();  // Limit search depth.
5078
5079   SDValue V = SDValue(N, 0);
5080   EVT VT = V.getValueType();
5081   unsigned Opcode = V.getOpcode();
5082
5083   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5084   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5085     int Elt = SV->getMaskElt(Index);
5086
5087     if (Elt < 0)
5088       return DAG.getUNDEF(VT.getVectorElementType());
5089
5090     unsigned NumElems = VT.getVectorNumElements();
5091     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5092                                          : SV->getOperand(1);
5093     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5094   }
5095
5096   // Recurse into target specific vector shuffles to find scalars.
5097   if (isTargetShuffle(Opcode)) {
5098     MVT ShufVT = V.getSimpleValueType();
5099     int NumElems = (int)ShufVT.getVectorNumElements();
5100     SmallVector<int, 16> ShuffleMask;
5101     bool IsUnary;
5102
5103     if (!getTargetShuffleMask(N, ShufVT, false, ShuffleMask, IsUnary))
5104       return SDValue();
5105
5106     int Elt = ShuffleMask[Index];
5107     if (Elt == SM_SentinelUndef)
5108       return DAG.getUNDEF(ShufVT.getVectorElementType());
5109
5110     assert(0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range");
5111     SDValue NewV = (Elt < NumElems) ? N->getOperand(0) : N->getOperand(1);
5112     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5113                                Depth+1);
5114   }
5115
5116   // Actual nodes that may contain scalar elements
5117   if (Opcode == ISD::BITCAST) {
5118     V = V.getOperand(0);
5119     EVT SrcVT = V.getValueType();
5120     unsigned NumElems = VT.getVectorNumElements();
5121
5122     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5123       return SDValue();
5124   }
5125
5126   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5127     return (Index == 0) ? V.getOperand(0)
5128                         : DAG.getUNDEF(VT.getVectorElementType());
5129
5130   if (V.getOpcode() == ISD::BUILD_VECTOR)
5131     return V.getOperand(Index);
5132
5133   return SDValue();
5134 }
5135
5136 /// Custom lower build_vector of v16i8.
5137 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5138                                        unsigned NumNonZero, unsigned NumZero,
5139                                        SelectionDAG &DAG,
5140                                        const X86Subtarget* Subtarget,
5141                                        const TargetLowering &TLI) {
5142   if (NumNonZero > 8)
5143     return SDValue();
5144
5145   SDLoc dl(Op);
5146   SDValue V;
5147   bool First = true;
5148
5149   // SSE4.1 - use PINSRB to insert each byte directly.
5150   if (Subtarget->hasSSE41()) {
5151     for (unsigned i = 0; i < 16; ++i) {
5152       bool isNonZero = (NonZeros & (1 << i)) != 0;
5153       if (isNonZero) {
5154         if (First) {
5155           if (NumZero)
5156             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5157           else
5158             V = DAG.getUNDEF(MVT::v16i8);
5159           First = false;
5160         }
5161         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5162                         MVT::v16i8, V, Op.getOperand(i),
5163                         DAG.getIntPtrConstant(i, dl));
5164       }
5165     }
5166
5167     return V;
5168   }
5169
5170   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5171   for (unsigned i = 0; i < 16; ++i) {
5172     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5173     if (ThisIsNonZero && First) {
5174       if (NumZero)
5175         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5176       else
5177         V = DAG.getUNDEF(MVT::v8i16);
5178       First = false;
5179     }
5180
5181     if ((i & 1) != 0) {
5182       SDValue ThisElt, LastElt;
5183       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5184       if (LastIsNonZero) {
5185         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5186                               MVT::i16, Op.getOperand(i-1));
5187       }
5188       if (ThisIsNonZero) {
5189         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5190         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5191                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
5192         if (LastIsNonZero)
5193           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5194       } else
5195         ThisElt = LastElt;
5196
5197       if (ThisElt.getNode())
5198         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5199                         DAG.getIntPtrConstant(i/2, dl));
5200     }
5201   }
5202
5203   return DAG.getBitcast(MVT::v16i8, V);
5204 }
5205
5206 /// Custom lower build_vector of v8i16.
5207 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5208                                      unsigned NumNonZero, unsigned NumZero,
5209                                      SelectionDAG &DAG,
5210                                      const X86Subtarget* Subtarget,
5211                                      const TargetLowering &TLI) {
5212   if (NumNonZero > 4)
5213     return SDValue();
5214
5215   SDLoc dl(Op);
5216   SDValue V;
5217   bool First = true;
5218   for (unsigned i = 0; i < 8; ++i) {
5219     bool isNonZero = (NonZeros & (1 << i)) != 0;
5220     if (isNonZero) {
5221       if (First) {
5222         if (NumZero)
5223           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5224         else
5225           V = DAG.getUNDEF(MVT::v8i16);
5226         First = false;
5227       }
5228       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5229                       MVT::v8i16, V, Op.getOperand(i),
5230                       DAG.getIntPtrConstant(i, dl));
5231     }
5232   }
5233
5234   return V;
5235 }
5236
5237 /// Custom lower build_vector of v4i32 or v4f32.
5238 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5239                                      const X86Subtarget *Subtarget,
5240                                      const TargetLowering &TLI) {
5241   // Find all zeroable elements.
5242   std::bitset<4> Zeroable;
5243   for (int i=0; i < 4; ++i) {
5244     SDValue Elt = Op->getOperand(i);
5245     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5246   }
5247   assert(Zeroable.size() - Zeroable.count() > 1 &&
5248          "We expect at least two non-zero elements!");
5249
5250   // We only know how to deal with build_vector nodes where elements are either
5251   // zeroable or extract_vector_elt with constant index.
5252   SDValue FirstNonZero;
5253   unsigned FirstNonZeroIdx;
5254   for (unsigned i=0; i < 4; ++i) {
5255     if (Zeroable[i])
5256       continue;
5257     SDValue Elt = Op->getOperand(i);
5258     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5259         !isa<ConstantSDNode>(Elt.getOperand(1)))
5260       return SDValue();
5261     // Make sure that this node is extracting from a 128-bit vector.
5262     MVT VT = Elt.getOperand(0).getSimpleValueType();
5263     if (!VT.is128BitVector())
5264       return SDValue();
5265     if (!FirstNonZero.getNode()) {
5266       FirstNonZero = Elt;
5267       FirstNonZeroIdx = i;
5268     }
5269   }
5270
5271   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5272   SDValue V1 = FirstNonZero.getOperand(0);
5273   MVT VT = V1.getSimpleValueType();
5274
5275   // See if this build_vector can be lowered as a blend with zero.
5276   SDValue Elt;
5277   unsigned EltMaskIdx, EltIdx;
5278   int Mask[4];
5279   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5280     if (Zeroable[EltIdx]) {
5281       // The zero vector will be on the right hand side.
5282       Mask[EltIdx] = EltIdx+4;
5283       continue;
5284     }
5285
5286     Elt = Op->getOperand(EltIdx);
5287     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5288     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5289     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5290       break;
5291     Mask[EltIdx] = EltIdx;
5292   }
5293
5294   if (EltIdx == 4) {
5295     // Let the shuffle legalizer deal with blend operations.
5296     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5297     if (V1.getSimpleValueType() != VT)
5298       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5299     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5300   }
5301
5302   // See if we can lower this build_vector to a INSERTPS.
5303   if (!Subtarget->hasSSE41())
5304     return SDValue();
5305
5306   SDValue V2 = Elt.getOperand(0);
5307   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5308     V1 = SDValue();
5309
5310   bool CanFold = true;
5311   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5312     if (Zeroable[i])
5313       continue;
5314
5315     SDValue Current = Op->getOperand(i);
5316     SDValue SrcVector = Current->getOperand(0);
5317     if (!V1.getNode())
5318       V1 = SrcVector;
5319     CanFold = SrcVector == V1 &&
5320       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5321   }
5322
5323   if (!CanFold)
5324     return SDValue();
5325
5326   assert(V1.getNode() && "Expected at least two non-zero elements!");
5327   if (V1.getSimpleValueType() != MVT::v4f32)
5328     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5329   if (V2.getSimpleValueType() != MVT::v4f32)
5330     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5331
5332   // Ok, we can emit an INSERTPS instruction.
5333   unsigned ZMask = Zeroable.to_ulong();
5334
5335   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5336   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5337   SDLoc DL(Op);
5338   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5339                                DAG.getIntPtrConstant(InsertPSMask, DL));
5340   return DAG.getBitcast(VT, Result);
5341 }
5342
5343 /// Return a vector logical shift node.
5344 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5345                          unsigned NumBits, SelectionDAG &DAG,
5346                          const TargetLowering &TLI, SDLoc dl) {
5347   assert(VT.is128BitVector() && "Unknown type for VShift");
5348   MVT ShVT = MVT::v2i64;
5349   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5350   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5351   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5352   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5353   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5354   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5355 }
5356
5357 static SDValue
5358 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5359
5360   // Check if the scalar load can be widened into a vector load. And if
5361   // the address is "base + cst" see if the cst can be "absorbed" into
5362   // the shuffle mask.
5363   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5364     SDValue Ptr = LD->getBasePtr();
5365     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5366       return SDValue();
5367     EVT PVT = LD->getValueType(0);
5368     if (PVT != MVT::i32 && PVT != MVT::f32)
5369       return SDValue();
5370
5371     int FI = -1;
5372     int64_t Offset = 0;
5373     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5374       FI = FINode->getIndex();
5375       Offset = 0;
5376     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5377                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5378       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5379       Offset = Ptr.getConstantOperandVal(1);
5380       Ptr = Ptr.getOperand(0);
5381     } else {
5382       return SDValue();
5383     }
5384
5385     // FIXME: 256-bit vector instructions don't require a strict alignment,
5386     // improve this code to support it better.
5387     unsigned RequiredAlign = VT.getSizeInBits()/8;
5388     SDValue Chain = LD->getChain();
5389     // Make sure the stack object alignment is at least 16 or 32.
5390     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5391     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5392       if (MFI->isFixedObjectIndex(FI)) {
5393         // Can't change the alignment. FIXME: It's possible to compute
5394         // the exact stack offset and reference FI + adjust offset instead.
5395         // If someone *really* cares about this. That's the way to implement it.
5396         return SDValue();
5397       } else {
5398         MFI->setObjectAlignment(FI, RequiredAlign);
5399       }
5400     }
5401
5402     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5403     // Ptr + (Offset & ~15).
5404     if (Offset < 0)
5405       return SDValue();
5406     if ((Offset % RequiredAlign) & 3)
5407       return SDValue();
5408     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5409     if (StartOffset) {
5410       SDLoc DL(Ptr);
5411       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5412                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5413     }
5414
5415     int EltNo = (Offset - StartOffset) >> 2;
5416     unsigned NumElems = VT.getVectorNumElements();
5417
5418     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5419     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5420                              LD->getPointerInfo().getWithOffset(StartOffset),
5421                              false, false, false, 0);
5422
5423     SmallVector<int, 8> Mask(NumElems, EltNo);
5424
5425     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5426   }
5427
5428   return SDValue();
5429 }
5430
5431 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5432 /// elements can be replaced by a single large load which has the same value as
5433 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5434 ///
5435 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5436 ///
5437 /// FIXME: we'd also like to handle the case where the last elements are zero
5438 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5439 /// There's even a handy isZeroNode for that purpose.
5440 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5441                                         SDLoc &DL, SelectionDAG &DAG,
5442                                         bool isAfterLegalize) {
5443   unsigned NumElems = Elts.size();
5444
5445   LoadSDNode *LDBase = nullptr;
5446   unsigned LastLoadedElt = -1U;
5447
5448   // For each element in the initializer, see if we've found a load or an undef.
5449   // If we don't find an initial load element, or later load elements are
5450   // non-consecutive, bail out.
5451   for (unsigned i = 0; i < NumElems; ++i) {
5452     SDValue Elt = Elts[i];
5453     // Look through a bitcast.
5454     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5455       Elt = Elt.getOperand(0);
5456     if (!Elt.getNode() ||
5457         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5458       return SDValue();
5459     if (!LDBase) {
5460       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5461         return SDValue();
5462       LDBase = cast<LoadSDNode>(Elt.getNode());
5463       LastLoadedElt = i;
5464       continue;
5465     }
5466     if (Elt.getOpcode() == ISD::UNDEF)
5467       continue;
5468
5469     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5470     EVT LdVT = Elt.getValueType();
5471     // Each loaded element must be the correct fractional portion of the
5472     // requested vector load.
5473     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5474       return SDValue();
5475     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5476       return SDValue();
5477     LastLoadedElt = i;
5478   }
5479
5480   // If we have found an entire vector of loads and undefs, then return a large
5481   // load of the entire vector width starting at the base pointer.  If we found
5482   // consecutive loads for the low half, generate a vzext_load node.
5483   if (LastLoadedElt == NumElems - 1) {
5484     assert(LDBase && "Did not find base load for merging consecutive loads");
5485     EVT EltVT = LDBase->getValueType(0);
5486     // Ensure that the input vector size for the merged loads matches the
5487     // cumulative size of the input elements.
5488     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5489       return SDValue();
5490
5491     if (isAfterLegalize &&
5492         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5493       return SDValue();
5494
5495     SDValue NewLd = SDValue();
5496
5497     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5498                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5499                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5500                         LDBase->getAlignment());
5501
5502     if (LDBase->hasAnyUseOfValue(1)) {
5503       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5504                                      SDValue(LDBase, 1),
5505                                      SDValue(NewLd.getNode(), 1));
5506       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5507       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5508                              SDValue(NewLd.getNode(), 1));
5509     }
5510
5511     return NewLd;
5512   }
5513
5514   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5515   //of a v4i32 / v4f32. It's probably worth generalizing.
5516   EVT EltVT = VT.getVectorElementType();
5517   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5518       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5519     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5520     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5521     SDValue ResNode =
5522         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5523                                 LDBase->getPointerInfo(),
5524                                 LDBase->getAlignment(),
5525                                 false/*isVolatile*/, true/*ReadMem*/,
5526                                 false/*WriteMem*/);
5527
5528     // Make sure the newly-created LOAD is in the same position as LDBase in
5529     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5530     // update uses of LDBase's output chain to use the TokenFactor.
5531     if (LDBase->hasAnyUseOfValue(1)) {
5532       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5533                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5534       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5535       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5536                              SDValue(ResNode.getNode(), 1));
5537     }
5538
5539     return DAG.getBitcast(VT, ResNode);
5540   }
5541   return SDValue();
5542 }
5543
5544 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5545 /// to generate a splat value for the following cases:
5546 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5547 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5548 /// a scalar load, or a constant.
5549 /// The VBROADCAST node is returned when a pattern is found,
5550 /// or SDValue() otherwise.
5551 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5552                                     SelectionDAG &DAG) {
5553   // VBROADCAST requires AVX.
5554   // TODO: Splats could be generated for non-AVX CPUs using SSE
5555   // instructions, but there's less potential gain for only 128-bit vectors.
5556   if (!Subtarget->hasAVX())
5557     return SDValue();
5558
5559   MVT VT = Op.getSimpleValueType();
5560   SDLoc dl(Op);
5561
5562   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5563          "Unsupported vector type for broadcast.");
5564
5565   SDValue Ld;
5566   bool ConstSplatVal;
5567
5568   switch (Op.getOpcode()) {
5569     default:
5570       // Unknown pattern found.
5571       return SDValue();
5572
5573     case ISD::BUILD_VECTOR: {
5574       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5575       BitVector UndefElements;
5576       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5577
5578       // We need a splat of a single value to use broadcast, and it doesn't
5579       // make any sense if the value is only in one element of the vector.
5580       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5581         return SDValue();
5582
5583       Ld = Splat;
5584       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5585                        Ld.getOpcode() == ISD::ConstantFP);
5586
5587       // Make sure that all of the users of a non-constant load are from the
5588       // BUILD_VECTOR node.
5589       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5590         return SDValue();
5591       break;
5592     }
5593
5594     case ISD::VECTOR_SHUFFLE: {
5595       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5596
5597       // Shuffles must have a splat mask where the first element is
5598       // broadcasted.
5599       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5600         return SDValue();
5601
5602       SDValue Sc = Op.getOperand(0);
5603       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5604           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5605
5606         if (!Subtarget->hasInt256())
5607           return SDValue();
5608
5609         // Use the register form of the broadcast instruction available on AVX2.
5610         if (VT.getSizeInBits() >= 256)
5611           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5612         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5613       }
5614
5615       Ld = Sc.getOperand(0);
5616       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5617                        Ld.getOpcode() == ISD::ConstantFP);
5618
5619       // The scalar_to_vector node and the suspected
5620       // load node must have exactly one user.
5621       // Constants may have multiple users.
5622
5623       // AVX-512 has register version of the broadcast
5624       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5625         Ld.getValueType().getSizeInBits() >= 32;
5626       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5627           !hasRegVer))
5628         return SDValue();
5629       break;
5630     }
5631   }
5632
5633   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5634   bool IsGE256 = (VT.getSizeInBits() >= 256);
5635
5636   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5637   // instruction to save 8 or more bytes of constant pool data.
5638   // TODO: If multiple splats are generated to load the same constant,
5639   // it may be detrimental to overall size. There needs to be a way to detect
5640   // that condition to know if this is truly a size win.
5641   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5642
5643   // Handle broadcasting a single constant scalar from the constant pool
5644   // into a vector.
5645   // On Sandybridge (no AVX2), it is still better to load a constant vector
5646   // from the constant pool and not to broadcast it from a scalar.
5647   // But override that restriction when optimizing for size.
5648   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5649   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5650     EVT CVT = Ld.getValueType();
5651     assert(!CVT.isVector() && "Must not broadcast a vector type");
5652
5653     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5654     // For size optimization, also splat v2f64 and v2i64, and for size opt
5655     // with AVX2, also splat i8 and i16.
5656     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5657     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5658         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5659       const Constant *C = nullptr;
5660       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5661         C = CI->getConstantIntValue();
5662       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5663         C = CF->getConstantFPValue();
5664
5665       assert(C && "Invalid constant type");
5666
5667       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5668       SDValue CP =
5669           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5670       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5671       Ld = DAG.getLoad(
5672           CVT, dl, DAG.getEntryNode(), CP,
5673           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5674           false, false, Alignment);
5675
5676       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5677     }
5678   }
5679
5680   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5681
5682   // Handle AVX2 in-register broadcasts.
5683   if (!IsLoad && Subtarget->hasInt256() &&
5684       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5685     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5686
5687   // The scalar source must be a normal load.
5688   if (!IsLoad)
5689     return SDValue();
5690
5691   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5692       (Subtarget->hasVLX() && ScalarSize == 64))
5693     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5694
5695   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5696   // double since there is no vbroadcastsd xmm
5697   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5698     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5699       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5700   }
5701
5702   // Unsupported broadcast.
5703   return SDValue();
5704 }
5705
5706 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5707 /// underlying vector and index.
5708 ///
5709 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5710 /// index.
5711 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5712                                          SDValue ExtIdx) {
5713   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5714   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5715     return Idx;
5716
5717   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5718   // lowered this:
5719   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5720   // to:
5721   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5722   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5723   //                           undef)
5724   //                       Constant<0>)
5725   // In this case the vector is the extract_subvector expression and the index
5726   // is 2, as specified by the shuffle.
5727   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5728   SDValue ShuffleVec = SVOp->getOperand(0);
5729   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5730   assert(ShuffleVecVT.getVectorElementType() ==
5731          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5732
5733   int ShuffleIdx = SVOp->getMaskElt(Idx);
5734   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5735     ExtractedFromVec = ShuffleVec;
5736     return ShuffleIdx;
5737   }
5738   return Idx;
5739 }
5740
5741 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5742   MVT VT = Op.getSimpleValueType();
5743
5744   // Skip if insert_vec_elt is not supported.
5745   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5746   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5747     return SDValue();
5748
5749   SDLoc DL(Op);
5750   unsigned NumElems = Op.getNumOperands();
5751
5752   SDValue VecIn1;
5753   SDValue VecIn2;
5754   SmallVector<unsigned, 4> InsertIndices;
5755   SmallVector<int, 8> Mask(NumElems, -1);
5756
5757   for (unsigned i = 0; i != NumElems; ++i) {
5758     unsigned Opc = Op.getOperand(i).getOpcode();
5759
5760     if (Opc == ISD::UNDEF)
5761       continue;
5762
5763     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5764       // Quit if more than 1 elements need inserting.
5765       if (InsertIndices.size() > 1)
5766         return SDValue();
5767
5768       InsertIndices.push_back(i);
5769       continue;
5770     }
5771
5772     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5773     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5774     // Quit if non-constant index.
5775     if (!isa<ConstantSDNode>(ExtIdx))
5776       return SDValue();
5777     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5778
5779     // Quit if extracted from vector of different type.
5780     if (ExtractedFromVec.getValueType() != VT)
5781       return SDValue();
5782
5783     if (!VecIn1.getNode())
5784       VecIn1 = ExtractedFromVec;
5785     else if (VecIn1 != ExtractedFromVec) {
5786       if (!VecIn2.getNode())
5787         VecIn2 = ExtractedFromVec;
5788       else if (VecIn2 != ExtractedFromVec)
5789         // Quit if more than 2 vectors to shuffle
5790         return SDValue();
5791     }
5792
5793     if (ExtractedFromVec == VecIn1)
5794       Mask[i] = Idx;
5795     else if (ExtractedFromVec == VecIn2)
5796       Mask[i] = Idx + NumElems;
5797   }
5798
5799   if (!VecIn1.getNode())
5800     return SDValue();
5801
5802   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5803   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5804   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5805     unsigned Idx = InsertIndices[i];
5806     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5807                      DAG.getIntPtrConstant(Idx, DL));
5808   }
5809
5810   return NV;
5811 }
5812
5813 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5814   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5815          Op.getScalarValueSizeInBits() == 1 &&
5816          "Can not convert non-constant vector");
5817   uint64_t Immediate = 0;
5818   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5819     SDValue In = Op.getOperand(idx);
5820     if (In.getOpcode() != ISD::UNDEF)
5821       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5822   }
5823   SDLoc dl(Op);
5824   MVT VT =
5825    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5826   return DAG.getConstant(Immediate, dl, VT);
5827 }
5828 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5829 SDValue
5830 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5831
5832   MVT VT = Op.getSimpleValueType();
5833   assert((VT.getVectorElementType() == MVT::i1) &&
5834          "Unexpected type in LowerBUILD_VECTORvXi1!");
5835
5836   SDLoc dl(Op);
5837   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5838     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5839     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5840     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5841   }
5842
5843   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5844     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5845     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5846     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5847   }
5848
5849   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5850     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5851     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5852       return DAG.getBitcast(VT, Imm);
5853     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5854     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5855                         DAG.getIntPtrConstant(0, dl));
5856   }
5857
5858   // Vector has one or more non-const elements
5859   uint64_t Immediate = 0;
5860   SmallVector<unsigned, 16> NonConstIdx;
5861   bool IsSplat = true;
5862   bool HasConstElts = false;
5863   int SplatIdx = -1;
5864   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5865     SDValue In = Op.getOperand(idx);
5866     if (In.getOpcode() == ISD::UNDEF)
5867       continue;
5868     if (!isa<ConstantSDNode>(In))
5869       NonConstIdx.push_back(idx);
5870     else {
5871       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5872       HasConstElts = true;
5873     }
5874     if (SplatIdx == -1)
5875       SplatIdx = idx;
5876     else if (In != Op.getOperand(SplatIdx))
5877       IsSplat = false;
5878   }
5879
5880   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5881   if (IsSplat)
5882     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5883                        DAG.getConstant(1, dl, VT),
5884                        DAG.getConstant(0, dl, VT));
5885
5886   // insert elements one by one
5887   SDValue DstVec;
5888   SDValue Imm;
5889   if (Immediate) {
5890     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5891     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5892   }
5893   else if (HasConstElts)
5894     Imm = DAG.getConstant(0, dl, VT);
5895   else
5896     Imm = DAG.getUNDEF(VT);
5897   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5898     DstVec = DAG.getBitcast(VT, Imm);
5899   else {
5900     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5901     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5902                          DAG.getIntPtrConstant(0, dl));
5903   }
5904
5905   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5906     unsigned InsertIdx = NonConstIdx[i];
5907     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5908                          Op.getOperand(InsertIdx),
5909                          DAG.getIntPtrConstant(InsertIdx, dl));
5910   }
5911   return DstVec;
5912 }
5913
5914 /// \brief Return true if \p N implements a horizontal binop and return the
5915 /// operands for the horizontal binop into V0 and V1.
5916 ///
5917 /// This is a helper function of LowerToHorizontalOp().
5918 /// This function checks that the build_vector \p N in input implements a
5919 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5920 /// operation to match.
5921 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5922 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5923 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5924 /// arithmetic sub.
5925 ///
5926 /// This function only analyzes elements of \p N whose indices are
5927 /// in range [BaseIdx, LastIdx).
5928 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5929                               SelectionDAG &DAG,
5930                               unsigned BaseIdx, unsigned LastIdx,
5931                               SDValue &V0, SDValue &V1) {
5932   EVT VT = N->getValueType(0);
5933
5934   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5935   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5936          "Invalid Vector in input!");
5937
5938   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5939   bool CanFold = true;
5940   unsigned ExpectedVExtractIdx = BaseIdx;
5941   unsigned NumElts = LastIdx - BaseIdx;
5942   V0 = DAG.getUNDEF(VT);
5943   V1 = DAG.getUNDEF(VT);
5944
5945   // Check if N implements a horizontal binop.
5946   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5947     SDValue Op = N->getOperand(i + BaseIdx);
5948
5949     // Skip UNDEFs.
5950     if (Op->getOpcode() == ISD::UNDEF) {
5951       // Update the expected vector extract index.
5952       if (i * 2 == NumElts)
5953         ExpectedVExtractIdx = BaseIdx;
5954       ExpectedVExtractIdx += 2;
5955       continue;
5956     }
5957
5958     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5959
5960     if (!CanFold)
5961       break;
5962
5963     SDValue Op0 = Op.getOperand(0);
5964     SDValue Op1 = Op.getOperand(1);
5965
5966     // Try to match the following pattern:
5967     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5968     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5969         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5970         Op0.getOperand(0) == Op1.getOperand(0) &&
5971         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5972         isa<ConstantSDNode>(Op1.getOperand(1)));
5973     if (!CanFold)
5974       break;
5975
5976     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5977     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5978
5979     if (i * 2 < NumElts) {
5980       if (V0.getOpcode() == ISD::UNDEF) {
5981         V0 = Op0.getOperand(0);
5982         if (V0.getValueType() != VT)
5983           return false;
5984       }
5985     } else {
5986       if (V1.getOpcode() == ISD::UNDEF) {
5987         V1 = Op0.getOperand(0);
5988         if (V1.getValueType() != VT)
5989           return false;
5990       }
5991       if (i * 2 == NumElts)
5992         ExpectedVExtractIdx = BaseIdx;
5993     }
5994
5995     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5996     if (I0 == ExpectedVExtractIdx)
5997       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5998     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5999       // Try to match the following dag sequence:
6000       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6001       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6002     } else
6003       CanFold = false;
6004
6005     ExpectedVExtractIdx += 2;
6006   }
6007
6008   return CanFold;
6009 }
6010
6011 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6012 /// a concat_vector.
6013 ///
6014 /// This is a helper function of LowerToHorizontalOp().
6015 /// This function expects two 256-bit vectors called V0 and V1.
6016 /// At first, each vector is split into two separate 128-bit vectors.
6017 /// Then, the resulting 128-bit vectors are used to implement two
6018 /// horizontal binary operations.
6019 ///
6020 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6021 ///
6022 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6023 /// the two new horizontal binop.
6024 /// When Mode is set, the first horizontal binop dag node would take as input
6025 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6026 /// horizontal binop dag node would take as input the lower 128-bit of V1
6027 /// and the upper 128-bit of V1.
6028 ///   Example:
6029 ///     HADD V0_LO, V0_HI
6030 ///     HADD V1_LO, V1_HI
6031 ///
6032 /// Otherwise, the first horizontal binop dag node takes as input the lower
6033 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6034 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
6035 ///   Example:
6036 ///     HADD V0_LO, V1_LO
6037 ///     HADD V0_HI, V1_HI
6038 ///
6039 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6040 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6041 /// the upper 128-bits of the result.
6042 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6043                                      SDLoc DL, SelectionDAG &DAG,
6044                                      unsigned X86Opcode, bool Mode,
6045                                      bool isUndefLO, bool isUndefHI) {
6046   EVT VT = V0.getValueType();
6047   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6048          "Invalid nodes in input!");
6049
6050   unsigned NumElts = VT.getVectorNumElements();
6051   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6052   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6053   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6054   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6055   EVT NewVT = V0_LO.getValueType();
6056
6057   SDValue LO = DAG.getUNDEF(NewVT);
6058   SDValue HI = DAG.getUNDEF(NewVT);
6059
6060   if (Mode) {
6061     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6062     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6063       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6064     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6065       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6066   } else {
6067     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6068     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6069                        V1_LO->getOpcode() != ISD::UNDEF))
6070       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6071
6072     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6073                        V1_HI->getOpcode() != ISD::UNDEF))
6074       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6075   }
6076
6077   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6078 }
6079
6080 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6081 /// node.
6082 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6083                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6084   MVT VT = BV->getSimpleValueType(0);
6085   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6086       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6087     return SDValue();
6088
6089   SDLoc DL(BV);
6090   unsigned NumElts = VT.getVectorNumElements();
6091   SDValue InVec0 = DAG.getUNDEF(VT);
6092   SDValue InVec1 = DAG.getUNDEF(VT);
6093
6094   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6095           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6096
6097   // Odd-numbered elements in the input build vector are obtained from
6098   // adding two integer/float elements.
6099   // Even-numbered elements in the input build vector are obtained from
6100   // subtracting two integer/float elements.
6101   unsigned ExpectedOpcode = ISD::FSUB;
6102   unsigned NextExpectedOpcode = ISD::FADD;
6103   bool AddFound = false;
6104   bool SubFound = false;
6105
6106   for (unsigned i = 0, e = NumElts; i != e; ++i) {
6107     SDValue Op = BV->getOperand(i);
6108
6109     // Skip 'undef' values.
6110     unsigned Opcode = Op.getOpcode();
6111     if (Opcode == ISD::UNDEF) {
6112       std::swap(ExpectedOpcode, NextExpectedOpcode);
6113       continue;
6114     }
6115
6116     // Early exit if we found an unexpected opcode.
6117     if (Opcode != ExpectedOpcode)
6118       return SDValue();
6119
6120     SDValue Op0 = Op.getOperand(0);
6121     SDValue Op1 = Op.getOperand(1);
6122
6123     // Try to match the following pattern:
6124     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6125     // Early exit if we cannot match that sequence.
6126     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6127         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6128         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6129         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6130         Op0.getOperand(1) != Op1.getOperand(1))
6131       return SDValue();
6132
6133     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6134     if (I0 != i)
6135       return SDValue();
6136
6137     // We found a valid add/sub node. Update the information accordingly.
6138     if (i & 1)
6139       AddFound = true;
6140     else
6141       SubFound = true;
6142
6143     // Update InVec0 and InVec1.
6144     if (InVec0.getOpcode() == ISD::UNDEF) {
6145       InVec0 = Op0.getOperand(0);
6146       if (InVec0.getSimpleValueType() != VT)
6147         return SDValue();
6148     }
6149     if (InVec1.getOpcode() == ISD::UNDEF) {
6150       InVec1 = Op1.getOperand(0);
6151       if (InVec1.getSimpleValueType() != VT)
6152         return SDValue();
6153     }
6154
6155     // Make sure that operands in input to each add/sub node always
6156     // come from a same pair of vectors.
6157     if (InVec0 != Op0.getOperand(0)) {
6158       if (ExpectedOpcode == ISD::FSUB)
6159         return SDValue();
6160
6161       // FADD is commutable. Try to commute the operands
6162       // and then test again.
6163       std::swap(Op0, Op1);
6164       if (InVec0 != Op0.getOperand(0))
6165         return SDValue();
6166     }
6167
6168     if (InVec1 != Op1.getOperand(0))
6169       return SDValue();
6170
6171     // Update the pair of expected opcodes.
6172     std::swap(ExpectedOpcode, NextExpectedOpcode);
6173   }
6174
6175   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6176   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6177       InVec1.getOpcode() != ISD::UNDEF)
6178     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6179
6180   return SDValue();
6181 }
6182
6183 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6184 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6185                                    const X86Subtarget *Subtarget,
6186                                    SelectionDAG &DAG) {
6187   MVT VT = BV->getSimpleValueType(0);
6188   unsigned NumElts = VT.getVectorNumElements();
6189   unsigned NumUndefsLO = 0;
6190   unsigned NumUndefsHI = 0;
6191   unsigned Half = NumElts/2;
6192
6193   // Count the number of UNDEF operands in the build_vector in input.
6194   for (unsigned i = 0, e = Half; i != e; ++i)
6195     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6196       NumUndefsLO++;
6197
6198   for (unsigned i = Half, e = NumElts; i != e; ++i)
6199     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6200       NumUndefsHI++;
6201
6202   // Early exit if this is either a build_vector of all UNDEFs or all the
6203   // operands but one are UNDEF.
6204   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6205     return SDValue();
6206
6207   SDLoc DL(BV);
6208   SDValue InVec0, InVec1;
6209   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6210     // Try to match an SSE3 float HADD/HSUB.
6211     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6212       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6213
6214     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6215       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6216   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6217     // Try to match an SSSE3 integer HADD/HSUB.
6218     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6219       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6220
6221     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6222       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6223   }
6224
6225   if (!Subtarget->hasAVX())
6226     return SDValue();
6227
6228   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6229     // Try to match an AVX horizontal add/sub of packed single/double
6230     // precision floating point values from 256-bit vectors.
6231     SDValue InVec2, InVec3;
6232     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6233         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6234         ((InVec0.getOpcode() == ISD::UNDEF ||
6235           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6236         ((InVec1.getOpcode() == ISD::UNDEF ||
6237           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6238       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6239
6240     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6241         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6242         ((InVec0.getOpcode() == ISD::UNDEF ||
6243           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6244         ((InVec1.getOpcode() == ISD::UNDEF ||
6245           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6246       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6247   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6248     // Try to match an AVX2 horizontal add/sub of signed integers.
6249     SDValue InVec2, InVec3;
6250     unsigned X86Opcode;
6251     bool CanFold = true;
6252
6253     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6254         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6255         ((InVec0.getOpcode() == ISD::UNDEF ||
6256           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6257         ((InVec1.getOpcode() == ISD::UNDEF ||
6258           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6259       X86Opcode = X86ISD::HADD;
6260     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6261         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6262         ((InVec0.getOpcode() == ISD::UNDEF ||
6263           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6264         ((InVec1.getOpcode() == ISD::UNDEF ||
6265           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6266       X86Opcode = X86ISD::HSUB;
6267     else
6268       CanFold = false;
6269
6270     if (CanFold) {
6271       // Fold this build_vector into a single horizontal add/sub.
6272       // Do this only if the target has AVX2.
6273       if (Subtarget->hasAVX2())
6274         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6275
6276       // Do not try to expand this build_vector into a pair of horizontal
6277       // add/sub if we can emit a pair of scalar add/sub.
6278       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6279         return SDValue();
6280
6281       // Convert this build_vector into a pair of horizontal binop followed by
6282       // a concat vector.
6283       bool isUndefLO = NumUndefsLO == Half;
6284       bool isUndefHI = NumUndefsHI == Half;
6285       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6286                                    isUndefLO, isUndefHI);
6287     }
6288   }
6289
6290   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6291        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6292     unsigned X86Opcode;
6293     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6294       X86Opcode = X86ISD::HADD;
6295     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6296       X86Opcode = X86ISD::HSUB;
6297     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6298       X86Opcode = X86ISD::FHADD;
6299     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6300       X86Opcode = X86ISD::FHSUB;
6301     else
6302       return SDValue();
6303
6304     // Don't try to expand this build_vector into a pair of horizontal add/sub
6305     // if we can simply emit a pair of scalar add/sub.
6306     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6307       return SDValue();
6308
6309     // Convert this build_vector into two horizontal add/sub followed by
6310     // a concat vector.
6311     bool isUndefLO = NumUndefsLO == Half;
6312     bool isUndefHI = NumUndefsHI == Half;
6313     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6314                                  isUndefLO, isUndefHI);
6315   }
6316
6317   return SDValue();
6318 }
6319
6320 SDValue
6321 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6322   SDLoc dl(Op);
6323
6324   MVT VT = Op.getSimpleValueType();
6325   MVT ExtVT = VT.getVectorElementType();
6326   unsigned NumElems = Op.getNumOperands();
6327
6328   // Generate vectors for predicate vectors.
6329   if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6330     return LowerBUILD_VECTORvXi1(Op, DAG);
6331
6332   // Vectors containing all zeros can be matched by pxor and xorps later
6333   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6334     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6335     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6336     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6337       return Op;
6338
6339     return getZeroVector(VT, Subtarget, DAG, dl);
6340   }
6341
6342   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6343   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6344   // vpcmpeqd on 256-bit vectors.
6345   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6346     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6347       return Op;
6348
6349     if (!VT.is512BitVector())
6350       return getOnesVector(VT, Subtarget, DAG, dl);
6351   }
6352
6353   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6354   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6355     return AddSub;
6356   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6357     return HorizontalOp;
6358   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6359     return Broadcast;
6360
6361   unsigned EVTBits = ExtVT.getSizeInBits();
6362
6363   unsigned NumZero  = 0;
6364   unsigned NumNonZero = 0;
6365   uint64_t NonZeros = 0;
6366   bool IsAllConstants = true;
6367   SmallSet<SDValue, 8> Values;
6368   for (unsigned i = 0; i < NumElems; ++i) {
6369     SDValue Elt = Op.getOperand(i);
6370     if (Elt.getOpcode() == ISD::UNDEF)
6371       continue;
6372     Values.insert(Elt);
6373     if (Elt.getOpcode() != ISD::Constant &&
6374         Elt.getOpcode() != ISD::ConstantFP)
6375       IsAllConstants = false;
6376     if (X86::isZeroNode(Elt))
6377       NumZero++;
6378     else {
6379       assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6380       NonZeros |= ((uint64_t)1 << i);
6381       NumNonZero++;
6382     }
6383   }
6384
6385   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6386   if (NumNonZero == 0)
6387     return DAG.getUNDEF(VT);
6388
6389   // Special case for single non-zero, non-undef, element.
6390   if (NumNonZero == 1) {
6391     unsigned Idx = countTrailingZeros(NonZeros);
6392     SDValue Item = Op.getOperand(Idx);
6393
6394     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6395     // the value are obviously zero, truncate the value to i32 and do the
6396     // insertion that way.  Only do this if the value is non-constant or if the
6397     // value is a constant being inserted into element 0.  It is cheaper to do
6398     // a constant pool load than it is to do a movd + shuffle.
6399     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6400         (!IsAllConstants || Idx == 0)) {
6401       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6402         // Handle SSE only.
6403         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6404         MVT VecVT = MVT::v4i32;
6405
6406         // Truncate the value (which may itself be a constant) to i32, and
6407         // convert it to a vector with movd (S2V+shuffle to zero extend).
6408         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6409         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6410         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6411                                       Item, Idx * 2, true, Subtarget, DAG));
6412       }
6413     }
6414
6415     // If we have a constant or non-constant insertion into the low element of
6416     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6417     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6418     // depending on what the source datatype is.
6419     if (Idx == 0) {
6420       if (NumZero == 0)
6421         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6422
6423       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6424           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6425         if (VT.is512BitVector()) {
6426           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6427           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6428                              Item, DAG.getIntPtrConstant(0, dl));
6429         }
6430         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6431                "Expected an SSE value type!");
6432         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6433         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6434         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6435       }
6436
6437       // We can't directly insert an i8 or i16 into a vector, so zero extend
6438       // it to i32 first.
6439       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6440         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6441         if (VT.is256BitVector()) {
6442           if (Subtarget->hasAVX()) {
6443             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6444             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6445           } else {
6446             // Without AVX, we need to extend to a 128-bit vector and then
6447             // insert into the 256-bit vector.
6448             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6449             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6450             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6451           }
6452         } else {
6453           assert(VT.is128BitVector() && "Expected an SSE value type!");
6454           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6455           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6456         }
6457         return DAG.getBitcast(VT, Item);
6458       }
6459     }
6460
6461     // Is it a vector logical left shift?
6462     if (NumElems == 2 && Idx == 1 &&
6463         X86::isZeroNode(Op.getOperand(0)) &&
6464         !X86::isZeroNode(Op.getOperand(1))) {
6465       unsigned NumBits = VT.getSizeInBits();
6466       return getVShift(true, VT,
6467                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6468                                    VT, Op.getOperand(1)),
6469                        NumBits/2, DAG, *this, dl);
6470     }
6471
6472     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6473       return SDValue();
6474
6475     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6476     // is a non-constant being inserted into an element other than the low one,
6477     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6478     // movd/movss) to move this into the low element, then shuffle it into
6479     // place.
6480     if (EVTBits == 32) {
6481       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6482       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6483     }
6484   }
6485
6486   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6487   if (Values.size() == 1) {
6488     if (EVTBits == 32) {
6489       // Instead of a shuffle like this:
6490       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6491       // Check if it's possible to issue this instead.
6492       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6493       unsigned Idx = countTrailingZeros(NonZeros);
6494       SDValue Item = Op.getOperand(Idx);
6495       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6496         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6497     }
6498     return SDValue();
6499   }
6500
6501   // A vector full of immediates; various special cases are already
6502   // handled, so this is best done with a single constant-pool load.
6503   if (IsAllConstants)
6504     return SDValue();
6505
6506   // For AVX-length vectors, see if we can use a vector load to get all of the
6507   // elements, otherwise build the individual 128-bit pieces and use
6508   // shuffles to put them in place.
6509   if (VT.is256BitVector() || VT.is512BitVector()) {
6510     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6511
6512     // Check for a build vector of consecutive loads.
6513     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6514       return LD;
6515
6516     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6517
6518     // Build both the lower and upper subvector.
6519     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6520                                 makeArrayRef(&V[0], NumElems/2));
6521     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6522                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6523
6524     // Recreate the wider vector with the lower and upper part.
6525     if (VT.is256BitVector())
6526       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6527     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6528   }
6529
6530   // Let legalizer expand 2-wide build_vectors.
6531   if (EVTBits == 64) {
6532     if (NumNonZero == 1) {
6533       // One half is zero or undef.
6534       unsigned Idx = countTrailingZeros(NonZeros);
6535       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6536                                Op.getOperand(Idx));
6537       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6538     }
6539     return SDValue();
6540   }
6541
6542   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6543   if (EVTBits == 8 && NumElems == 16)
6544     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6545                                           DAG, Subtarget, *this))
6546       return V;
6547
6548   if (EVTBits == 16 && NumElems == 8)
6549     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6550                                           DAG, Subtarget, *this))
6551       return V;
6552
6553   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6554   if (EVTBits == 32 && NumElems == 4)
6555     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6556       return V;
6557
6558   // If element VT is == 32 bits, turn it into a number of shuffles.
6559   SmallVector<SDValue, 8> V(NumElems);
6560   if (NumElems == 4 && NumZero > 0) {
6561     for (unsigned i = 0; i < 4; ++i) {
6562       bool isZero = !(NonZeros & (1ULL << i));
6563       if (isZero)
6564         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6565       else
6566         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6567     }
6568
6569     for (unsigned i = 0; i < 2; ++i) {
6570       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6571         default: break;
6572         case 0:
6573           V[i] = V[i*2];  // Must be a zero vector.
6574           break;
6575         case 1:
6576           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6577           break;
6578         case 2:
6579           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6580           break;
6581         case 3:
6582           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6583           break;
6584       }
6585     }
6586
6587     bool Reverse1 = (NonZeros & 0x3) == 2;
6588     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6589     int MaskVec[] = {
6590       Reverse1 ? 1 : 0,
6591       Reverse1 ? 0 : 1,
6592       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6593       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6594     };
6595     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6596   }
6597
6598   if (Values.size() > 1 && VT.is128BitVector()) {
6599     // Check for a build vector of consecutive loads.
6600     for (unsigned i = 0; i < NumElems; ++i)
6601       V[i] = Op.getOperand(i);
6602
6603     // Check for elements which are consecutive loads.
6604     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6605       return LD;
6606
6607     // Check for a build vector from mostly shuffle plus few inserting.
6608     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6609       return Sh;
6610
6611     // For SSE 4.1, use insertps to put the high elements into the low element.
6612     if (Subtarget->hasSSE41()) {
6613       SDValue Result;
6614       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6615         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6616       else
6617         Result = DAG.getUNDEF(VT);
6618
6619       for (unsigned i = 1; i < NumElems; ++i) {
6620         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6621         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6622                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6623       }
6624       return Result;
6625     }
6626
6627     // Otherwise, expand into a number of unpckl*, start by extending each of
6628     // our (non-undef) elements to the full vector width with the element in the
6629     // bottom slot of the vector (which generates no code for SSE).
6630     for (unsigned i = 0; i < NumElems; ++i) {
6631       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6632         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6633       else
6634         V[i] = DAG.getUNDEF(VT);
6635     }
6636
6637     // Next, we iteratively mix elements, e.g. for v4f32:
6638     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6639     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6640     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6641     unsigned EltStride = NumElems >> 1;
6642     while (EltStride != 0) {
6643       for (unsigned i = 0; i < EltStride; ++i) {
6644         // If V[i+EltStride] is undef and this is the first round of mixing,
6645         // then it is safe to just drop this shuffle: V[i] is already in the
6646         // right place, the one element (since it's the first round) being
6647         // inserted as undef can be dropped.  This isn't safe for successive
6648         // rounds because they will permute elements within both vectors.
6649         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6650             EltStride == NumElems/2)
6651           continue;
6652
6653         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6654       }
6655       EltStride >>= 1;
6656     }
6657     return V[0];
6658   }
6659   return SDValue();
6660 }
6661
6662 // 256-bit AVX can use the vinsertf128 instruction
6663 // to create 256-bit vectors from two other 128-bit ones.
6664 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6665   SDLoc dl(Op);
6666   MVT ResVT = Op.getSimpleValueType();
6667
6668   assert((ResVT.is256BitVector() ||
6669           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6670
6671   SDValue V1 = Op.getOperand(0);
6672   SDValue V2 = Op.getOperand(1);
6673   unsigned NumElems = ResVT.getVectorNumElements();
6674   if (ResVT.is256BitVector())
6675     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6676
6677   if (Op.getNumOperands() == 4) {
6678     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6679                                   ResVT.getVectorNumElements()/2);
6680     SDValue V3 = Op.getOperand(2);
6681     SDValue V4 = Op.getOperand(3);
6682     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6683       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6684   }
6685   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6686 }
6687
6688 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6689                                        const X86Subtarget *Subtarget,
6690                                        SelectionDAG & DAG) {
6691   SDLoc dl(Op);
6692   MVT ResVT = Op.getSimpleValueType();
6693   unsigned NumOfOperands = Op.getNumOperands();
6694
6695   assert(isPowerOf2_32(NumOfOperands) &&
6696          "Unexpected number of operands in CONCAT_VECTORS");
6697
6698   SDValue Undef = DAG.getUNDEF(ResVT);
6699   if (NumOfOperands > 2) {
6700     // Specialize the cases when all, or all but one, of the operands are undef.
6701     unsigned NumOfDefinedOps = 0;
6702     unsigned OpIdx = 0;
6703     for (unsigned i = 0; i < NumOfOperands; i++)
6704       if (!Op.getOperand(i).isUndef()) {
6705         NumOfDefinedOps++;
6706         OpIdx = i;
6707       }
6708     if (NumOfDefinedOps == 0)
6709       return Undef;
6710     if (NumOfDefinedOps == 1) {
6711       unsigned SubVecNumElts =
6712         Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6713       SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6714       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6715                          Op.getOperand(OpIdx), IdxVal);
6716     }
6717
6718     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6719                                   ResVT.getVectorNumElements()/2);
6720     SmallVector<SDValue, 2> Ops;
6721     for (unsigned i = 0; i < NumOfOperands/2; i++)
6722       Ops.push_back(Op.getOperand(i));
6723     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6724     Ops.clear();
6725     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6726       Ops.push_back(Op.getOperand(i));
6727     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6728     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6729   }
6730
6731   // 2 operands
6732   SDValue V1 = Op.getOperand(0);
6733   SDValue V2 = Op.getOperand(1);
6734   unsigned NumElems = ResVT.getVectorNumElements();
6735   assert(V1.getValueType() == V2.getValueType() &&
6736          V1.getValueType().getVectorNumElements() == NumElems/2 &&
6737          "Unexpected operands in CONCAT_VECTORS");
6738
6739   if (ResVT.getSizeInBits() >= 16)
6740     return Op; // The operation is legal with KUNPCK
6741
6742   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6743   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6744   SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6745   if (IsZeroV1 && IsZeroV2)
6746     return ZeroVec;
6747
6748   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6749   if (V2.isUndef())
6750     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6751   if (IsZeroV2)
6752     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6753
6754   SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6755   if (V1.isUndef())
6756     V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6757
6758   if (IsZeroV1)
6759     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6760
6761   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6762   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6763 }
6764
6765 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6766                                    const X86Subtarget *Subtarget,
6767                                    SelectionDAG &DAG) {
6768   MVT VT = Op.getSimpleValueType();
6769   if (VT.getVectorElementType() == MVT::i1)
6770     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6771
6772   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6773          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6774           Op.getNumOperands() == 4)));
6775
6776   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6777   // from two other 128-bit ones.
6778
6779   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6780   return LowerAVXCONCAT_VECTORS(Op, DAG);
6781 }
6782
6783 //===----------------------------------------------------------------------===//
6784 // Vector shuffle lowering
6785 //
6786 // This is an experimental code path for lowering vector shuffles on x86. It is
6787 // designed to handle arbitrary vector shuffles and blends, gracefully
6788 // degrading performance as necessary. It works hard to recognize idiomatic
6789 // shuffles and lower them to optimal instruction patterns without leaving
6790 // a framework that allows reasonably efficient handling of all vector shuffle
6791 // patterns.
6792 //===----------------------------------------------------------------------===//
6793
6794 /// \brief Tiny helper function to identify a no-op mask.
6795 ///
6796 /// This is a somewhat boring predicate function. It checks whether the mask
6797 /// array input, which is assumed to be a single-input shuffle mask of the kind
6798 /// used by the X86 shuffle instructions (not a fully general
6799 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6800 /// in-place shuffle are 'no-op's.
6801 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6802   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6803     if (Mask[i] != -1 && Mask[i] != i)
6804       return false;
6805   return true;
6806 }
6807
6808 /// \brief Helper function to classify a mask as a single-input mask.
6809 ///
6810 /// This isn't a generic single-input test because in the vector shuffle
6811 /// lowering we canonicalize single inputs to be the first input operand. This
6812 /// means we can more quickly test for a single input by only checking whether
6813 /// an input from the second operand exists. We also assume that the size of
6814 /// mask corresponds to the size of the input vectors which isn't true in the
6815 /// fully general case.
6816 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6817   for (int M : Mask)
6818     if (M >= (int)Mask.size())
6819       return false;
6820   return true;
6821 }
6822
6823 /// \brief Test whether there are elements crossing 128-bit lanes in this
6824 /// shuffle mask.
6825 ///
6826 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6827 /// and we routinely test for these.
6828 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6829   int LaneSize = 128 / VT.getScalarSizeInBits();
6830   int Size = Mask.size();
6831   for (int i = 0; i < Size; ++i)
6832     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6833       return true;
6834   return false;
6835 }
6836
6837 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6838 ///
6839 /// This checks a shuffle mask to see if it is performing the same
6840 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6841 /// that it is also not lane-crossing. It may however involve a blend from the
6842 /// same lane of a second vector.
6843 ///
6844 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6845 /// non-trivial to compute in the face of undef lanes. The representation is
6846 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6847 /// entries from both V1 and V2 inputs to the wider mask.
6848 static bool
6849 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6850                                 SmallVectorImpl<int> &RepeatedMask) {
6851   int LaneSize = 128 / VT.getScalarSizeInBits();
6852   RepeatedMask.resize(LaneSize, -1);
6853   int Size = Mask.size();
6854   for (int i = 0; i < Size; ++i) {
6855     if (Mask[i] < 0)
6856       continue;
6857     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6858       // This entry crosses lanes, so there is no way to model this shuffle.
6859       return false;
6860
6861     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6862     if (RepeatedMask[i % LaneSize] == -1)
6863       // This is the first non-undef entry in this slot of a 128-bit lane.
6864       RepeatedMask[i % LaneSize] =
6865           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6866     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6867       // Found a mismatch with the repeated mask.
6868       return false;
6869   }
6870   return true;
6871 }
6872
6873 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6874 /// arguments.
6875 ///
6876 /// This is a fast way to test a shuffle mask against a fixed pattern:
6877 ///
6878 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6879 ///
6880 /// It returns true if the mask is exactly as wide as the argument list, and
6881 /// each element of the mask is either -1 (signifying undef) or the value given
6882 /// in the argument.
6883 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6884                                 ArrayRef<int> ExpectedMask) {
6885   if (Mask.size() != ExpectedMask.size())
6886     return false;
6887
6888   int Size = Mask.size();
6889
6890   // If the values are build vectors, we can look through them to find
6891   // equivalent inputs that make the shuffles equivalent.
6892   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6893   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6894
6895   for (int i = 0; i < Size; ++i)
6896     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6897       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6898       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6899       if (!MaskBV || !ExpectedBV ||
6900           MaskBV->getOperand(Mask[i] % Size) !=
6901               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6902         return false;
6903     }
6904
6905   return true;
6906 }
6907
6908 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6909 ///
6910 /// This helper function produces an 8-bit shuffle immediate corresponding to
6911 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6912 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6913 /// example.
6914 ///
6915 /// NB: We rely heavily on "undef" masks preserving the input lane.
6916 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6917                                           SelectionDAG &DAG) {
6918   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6919   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6920   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6921   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6922   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6923
6924   unsigned Imm = 0;
6925   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6926   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6927   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6928   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6929   return DAG.getConstant(Imm, DL, MVT::i8);
6930 }
6931
6932 /// \brief Compute whether each element of a shuffle is zeroable.
6933 ///
6934 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6935 /// Either it is an undef element in the shuffle mask, the element of the input
6936 /// referenced is undef, or the element of the input referenced is known to be
6937 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6938 /// as many lanes with this technique as possible to simplify the remaining
6939 /// shuffle.
6940 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6941                                                      SDValue V1, SDValue V2) {
6942   SmallBitVector Zeroable(Mask.size(), false);
6943
6944   while (V1.getOpcode() == ISD::BITCAST)
6945     V1 = V1->getOperand(0);
6946   while (V2.getOpcode() == ISD::BITCAST)
6947     V2 = V2->getOperand(0);
6948
6949   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6950   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6951
6952   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6953     int M = Mask[i];
6954     // Handle the easy cases.
6955     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6956       Zeroable[i] = true;
6957       continue;
6958     }
6959
6960     // If this is an index into a build_vector node (which has the same number
6961     // of elements), dig out the input value and use it.
6962     SDValue V = M < Size ? V1 : V2;
6963     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6964       continue;
6965
6966     SDValue Input = V.getOperand(M % Size);
6967     // The UNDEF opcode check really should be dead code here, but not quite
6968     // worth asserting on (it isn't invalid, just unexpected).
6969     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6970       Zeroable[i] = true;
6971   }
6972
6973   return Zeroable;
6974 }
6975
6976 // X86 has dedicated unpack instructions that can handle specific blend
6977 // operations: UNPCKH and UNPCKL.
6978 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6979                                            SDValue V1, SDValue V2,
6980                                            SelectionDAG &DAG) {
6981   int NumElts = VT.getVectorNumElements();
6982   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6983   SmallVector<int, 8> Unpckl;
6984   SmallVector<int, 8> Unpckh;
6985
6986   for (int i = 0; i < NumElts; ++i) {
6987     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6988     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6989     int HiPos = LoPos + NumEltsInLane / 2;
6990     Unpckl.push_back(LoPos);
6991     Unpckh.push_back(HiPos);
6992   }
6993
6994   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6995     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6996   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6997     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6998
6999   // Commute and try again.
7000   ShuffleVectorSDNode::commuteMask(Unpckl);
7001   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
7002     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
7003
7004   ShuffleVectorSDNode::commuteMask(Unpckh);
7005   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
7006     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
7007
7008   return SDValue();
7009 }
7010
7011 /// \brief Try to emit a bitmask instruction for a shuffle.
7012 ///
7013 /// This handles cases where we can model a blend exactly as a bitmask due to
7014 /// one of the inputs being zeroable.
7015 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
7016                                            SDValue V2, ArrayRef<int> Mask,
7017                                            SelectionDAG &DAG) {
7018   MVT EltVT = VT.getVectorElementType();
7019   int NumEltBits = EltVT.getSizeInBits();
7020   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
7021   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
7022   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7023                                     IntEltVT);
7024   if (EltVT.isFloatingPoint()) {
7025     Zero = DAG.getBitcast(EltVT, Zero);
7026     AllOnes = DAG.getBitcast(EltVT, AllOnes);
7027   }
7028   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
7029   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7030   SDValue V;
7031   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7032     if (Zeroable[i])
7033       continue;
7034     if (Mask[i] % Size != i)
7035       return SDValue(); // Not a blend.
7036     if (!V)
7037       V = Mask[i] < Size ? V1 : V2;
7038     else if (V != (Mask[i] < Size ? V1 : V2))
7039       return SDValue(); // Can only let one input through the mask.
7040
7041     VMaskOps[i] = AllOnes;
7042   }
7043   if (!V)
7044     return SDValue(); // No non-zeroable elements!
7045
7046   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
7047   V = DAG.getNode(VT.isFloatingPoint()
7048                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7049                   DL, VT, V, VMask);
7050   return V;
7051 }
7052
7053 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7054 ///
7055 /// This is used as a fallback approach when first class blend instructions are
7056 /// unavailable. Currently it is only suitable for integer vectors, but could
7057 /// be generalized for floating point vectors if desirable.
7058 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
7059                                             SDValue V2, ArrayRef<int> Mask,
7060                                             SelectionDAG &DAG) {
7061   assert(VT.isInteger() && "Only supports integer vector types!");
7062   MVT EltVT = VT.getVectorElementType();
7063   int NumEltBits = EltVT.getSizeInBits();
7064   SDValue Zero = DAG.getConstant(0, DL, EltVT);
7065   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7066                                     EltVT);
7067   SmallVector<SDValue, 16> MaskOps;
7068   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7069     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
7070       return SDValue(); // Shuffled input!
7071     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7072   }
7073
7074   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
7075   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7076   // We have to cast V2 around.
7077   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7078   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7079                                       DAG.getBitcast(MaskVT, V1Mask),
7080                                       DAG.getBitcast(MaskVT, V2)));
7081   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7082 }
7083
7084 /// \brief Try to emit a blend instruction for a shuffle.
7085 ///
7086 /// This doesn't do any checks for the availability of instructions for blending
7087 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7088 /// be matched in the backend with the type given. What it does check for is
7089 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7090 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7091                                          SDValue V2, ArrayRef<int> Original,
7092                                          const X86Subtarget *Subtarget,
7093                                          SelectionDAG &DAG) {
7094   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7095   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7096   SmallVector<int, 8> Mask(Original.begin(), Original.end());
7097   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7098   bool ForceV1Zero = false, ForceV2Zero = false;
7099
7100   // Attempt to generate the binary blend mask. If an input is zero then
7101   // we can use any lane.
7102   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7103   unsigned BlendMask = 0;
7104   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7105     int M = Mask[i];
7106     if (M < 0)
7107       continue;
7108     if (M == i)
7109       continue;
7110     if (M == i + Size) {
7111       BlendMask |= 1u << i;
7112       continue;
7113     }
7114     if (Zeroable[i]) {
7115       if (V1IsZero) {
7116         ForceV1Zero = true;
7117         Mask[i] = i;
7118         continue;
7119       }
7120       if (V2IsZero) {
7121         ForceV2Zero = true;
7122         BlendMask |= 1u << i;
7123         Mask[i] = i + Size;
7124         continue;
7125       }
7126     }
7127     return SDValue(); // Shuffled input!
7128   }
7129
7130   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7131   if (ForceV1Zero)
7132     V1 = getZeroVector(VT, Subtarget, DAG, DL);
7133   if (ForceV2Zero)
7134     V2 = getZeroVector(VT, Subtarget, DAG, DL);
7135
7136   auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7137     unsigned ScaledMask = 0;
7138     for (int i = 0; i != Size; ++i)
7139       if (BlendMask & (1u << i))
7140         for (int j = 0; j != Scale; ++j)
7141           ScaledMask |= 1u << (i * Scale + j);
7142     return ScaledMask;
7143   };
7144
7145   switch (VT.SimpleTy) {
7146   case MVT::v2f64:
7147   case MVT::v4f32:
7148   case MVT::v4f64:
7149   case MVT::v8f32:
7150     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7151                        DAG.getConstant(BlendMask, DL, MVT::i8));
7152
7153   case MVT::v4i64:
7154   case MVT::v8i32:
7155     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7156     // FALLTHROUGH
7157   case MVT::v2i64:
7158   case MVT::v4i32:
7159     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7160     // that instruction.
7161     if (Subtarget->hasAVX2()) {
7162       // Scale the blend by the number of 32-bit dwords per element.
7163       int Scale =  VT.getScalarSizeInBits() / 32;
7164       BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7165       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7166       V1 = DAG.getBitcast(BlendVT, V1);
7167       V2 = DAG.getBitcast(BlendVT, V2);
7168       return DAG.getBitcast(
7169           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7170                           DAG.getConstant(BlendMask, DL, MVT::i8)));
7171     }
7172     // FALLTHROUGH
7173   case MVT::v8i16: {
7174     // For integer shuffles we need to expand the mask and cast the inputs to
7175     // v8i16s prior to blending.
7176     int Scale = 8 / VT.getVectorNumElements();
7177     BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7178     V1 = DAG.getBitcast(MVT::v8i16, V1);
7179     V2 = DAG.getBitcast(MVT::v8i16, V2);
7180     return DAG.getBitcast(VT,
7181                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7182                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
7183   }
7184
7185   case MVT::v16i16: {
7186     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7187     SmallVector<int, 8> RepeatedMask;
7188     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7189       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7190       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7191       BlendMask = 0;
7192       for (int i = 0; i < 8; ++i)
7193         if (RepeatedMask[i] >= 16)
7194           BlendMask |= 1u << i;
7195       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7196                          DAG.getConstant(BlendMask, DL, MVT::i8));
7197     }
7198   }
7199     // FALLTHROUGH
7200   case MVT::v16i8:
7201   case MVT::v32i8: {
7202     assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7203            "256-bit byte-blends require AVX2 support!");
7204
7205     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7206     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7207       return Masked;
7208
7209     // Scale the blend by the number of bytes per element.
7210     int Scale = VT.getScalarSizeInBits() / 8;
7211
7212     // This form of blend is always done on bytes. Compute the byte vector
7213     // type.
7214     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7215
7216     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7217     // mix of LLVM's code generator and the x86 backend. We tell the code
7218     // generator that boolean values in the elements of an x86 vector register
7219     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7220     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7221     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7222     // of the element (the remaining are ignored) and 0 in that high bit would
7223     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7224     // the LLVM model for boolean values in vector elements gets the relevant
7225     // bit set, it is set backwards and over constrained relative to x86's
7226     // actual model.
7227     SmallVector<SDValue, 32> VSELECTMask;
7228     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7229       for (int j = 0; j < Scale; ++j)
7230         VSELECTMask.push_back(
7231             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7232                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7233                                           MVT::i8));
7234
7235     V1 = DAG.getBitcast(BlendVT, V1);
7236     V2 = DAG.getBitcast(BlendVT, V2);
7237     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7238                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7239                                                       BlendVT, VSELECTMask),
7240                                           V1, V2));
7241   }
7242
7243   default:
7244     llvm_unreachable("Not a supported integer vector type!");
7245   }
7246 }
7247
7248 /// \brief Try to lower as a blend of elements from two inputs followed by
7249 /// a single-input permutation.
7250 ///
7251 /// This matches the pattern where we can blend elements from two inputs and
7252 /// then reduce the shuffle to a single-input permutation.
7253 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7254                                                    SDValue V2,
7255                                                    ArrayRef<int> Mask,
7256                                                    SelectionDAG &DAG) {
7257   // We build up the blend mask while checking whether a blend is a viable way
7258   // to reduce the shuffle.
7259   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7260   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7261
7262   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7263     if (Mask[i] < 0)
7264       continue;
7265
7266     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7267
7268     if (BlendMask[Mask[i] % Size] == -1)
7269       BlendMask[Mask[i] % Size] = Mask[i];
7270     else if (BlendMask[Mask[i] % Size] != Mask[i])
7271       return SDValue(); // Can't blend in the needed input!
7272
7273     PermuteMask[i] = Mask[i] % Size;
7274   }
7275
7276   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7277   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7278 }
7279
7280 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7281 /// blends and permutes.
7282 ///
7283 /// This matches the extremely common pattern for handling combined
7284 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7285 /// operations. It will try to pick the best arrangement of shuffles and
7286 /// blends.
7287 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7288                                                           SDValue V1,
7289                                                           SDValue V2,
7290                                                           ArrayRef<int> Mask,
7291                                                           SelectionDAG &DAG) {
7292   // Shuffle the input elements into the desired positions in V1 and V2 and
7293   // blend them together.
7294   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7295   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7296   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7297   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7298     if (Mask[i] >= 0 && Mask[i] < Size) {
7299       V1Mask[i] = Mask[i];
7300       BlendMask[i] = i;
7301     } else if (Mask[i] >= Size) {
7302       V2Mask[i] = Mask[i] - Size;
7303       BlendMask[i] = i + Size;
7304     }
7305
7306   // Try to lower with the simpler initial blend strategy unless one of the
7307   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7308   // shuffle may be able to fold with a load or other benefit. However, when
7309   // we'll have to do 2x as many shuffles in order to achieve this, blending
7310   // first is a better strategy.
7311   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7312     if (SDValue BlendPerm =
7313             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7314       return BlendPerm;
7315
7316   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7317   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7318   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7319 }
7320
7321 /// \brief Try to lower a vector shuffle as a byte rotation.
7322 ///
7323 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7324 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7325 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7326 /// try to generically lower a vector shuffle through such an pattern. It
7327 /// does not check for the profitability of lowering either as PALIGNR or
7328 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7329 /// This matches shuffle vectors that look like:
7330 ///
7331 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7332 ///
7333 /// Essentially it concatenates V1 and V2, shifts right by some number of
7334 /// elements, and takes the low elements as the result. Note that while this is
7335 /// specified as a *right shift* because x86 is little-endian, it is a *left
7336 /// rotate* of the vector lanes.
7337 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7338                                               SDValue V2,
7339                                               ArrayRef<int> Mask,
7340                                               const X86Subtarget *Subtarget,
7341                                               SelectionDAG &DAG) {
7342   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7343
7344   int NumElts = Mask.size();
7345   int NumLanes = VT.getSizeInBits() / 128;
7346   int NumLaneElts = NumElts / NumLanes;
7347
7348   // We need to detect various ways of spelling a rotation:
7349   //   [11, 12, 13, 14, 15,  0,  1,  2]
7350   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7351   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7352   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7353   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7354   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7355   int Rotation = 0;
7356   SDValue Lo, Hi;
7357   for (int l = 0; l < NumElts; l += NumLaneElts) {
7358     for (int i = 0; i < NumLaneElts; ++i) {
7359       if (Mask[l + i] == -1)
7360         continue;
7361       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7362
7363       // Get the mod-Size index and lane correct it.
7364       int LaneIdx = (Mask[l + i] % NumElts) - l;
7365       // Make sure it was in this lane.
7366       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7367         return SDValue();
7368
7369       // Determine where a rotated vector would have started.
7370       int StartIdx = i - LaneIdx;
7371       if (StartIdx == 0)
7372         // The identity rotation isn't interesting, stop.
7373         return SDValue();
7374
7375       // If we found the tail of a vector the rotation must be the missing
7376       // front. If we found the head of a vector, it must be how much of the
7377       // head.
7378       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7379
7380       if (Rotation == 0)
7381         Rotation = CandidateRotation;
7382       else if (Rotation != CandidateRotation)
7383         // The rotations don't match, so we can't match this mask.
7384         return SDValue();
7385
7386       // Compute which value this mask is pointing at.
7387       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7388
7389       // Compute which of the two target values this index should be assigned
7390       // to. This reflects whether the high elements are remaining or the low
7391       // elements are remaining.
7392       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7393
7394       // Either set up this value if we've not encountered it before, or check
7395       // that it remains consistent.
7396       if (!TargetV)
7397         TargetV = MaskV;
7398       else if (TargetV != MaskV)
7399         // This may be a rotation, but it pulls from the inputs in some
7400         // unsupported interleaving.
7401         return SDValue();
7402     }
7403   }
7404
7405   // Check that we successfully analyzed the mask, and normalize the results.
7406   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7407   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7408   if (!Lo)
7409     Lo = Hi;
7410   else if (!Hi)
7411     Hi = Lo;
7412
7413   // The actual rotate instruction rotates bytes, so we need to scale the
7414   // rotation based on how many bytes are in the vector lane.
7415   int Scale = 16 / NumLaneElts;
7416
7417   // SSSE3 targets can use the palignr instruction.
7418   if (Subtarget->hasSSSE3()) {
7419     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7420     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7421     Lo = DAG.getBitcast(AlignVT, Lo);
7422     Hi = DAG.getBitcast(AlignVT, Hi);
7423
7424     return DAG.getBitcast(
7425         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7426                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7427   }
7428
7429   assert(VT.is128BitVector() &&
7430          "Rotate-based lowering only supports 128-bit lowering!");
7431   assert(Mask.size() <= 16 &&
7432          "Can shuffle at most 16 bytes in a 128-bit vector!");
7433
7434   // Default SSE2 implementation
7435   int LoByteShift = 16 - Rotation * Scale;
7436   int HiByteShift = Rotation * Scale;
7437
7438   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7439   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7440   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7441
7442   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7443                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7444   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7445                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7446   return DAG.getBitcast(VT,
7447                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7448 }
7449
7450 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7451 ///
7452 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7453 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7454 /// matches elements from one of the input vectors shuffled to the left or
7455 /// right with zeroable elements 'shifted in'. It handles both the strictly
7456 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7457 /// quad word lane.
7458 ///
7459 /// PSHL : (little-endian) left bit shift.
7460 /// [ zz, 0, zz,  2 ]
7461 /// [ -1, 4, zz, -1 ]
7462 /// PSRL : (little-endian) right bit shift.
7463 /// [  1, zz,  3, zz]
7464 /// [ -1, -1,  7, zz]
7465 /// PSLLDQ : (little-endian) left byte shift
7466 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7467 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7468 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7469 /// PSRLDQ : (little-endian) right byte shift
7470 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7471 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7472 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7473 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7474                                          SDValue V2, ArrayRef<int> Mask,
7475                                          SelectionDAG &DAG) {
7476   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7477
7478   int Size = Mask.size();
7479   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7480
7481   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7482     for (int i = 0; i < Size; i += Scale)
7483       for (int j = 0; j < Shift; ++j)
7484         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7485           return false;
7486
7487     return true;
7488   };
7489
7490   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7491     for (int i = 0; i != Size; i += Scale) {
7492       unsigned Pos = Left ? i + Shift : i;
7493       unsigned Low = Left ? i : i + Shift;
7494       unsigned Len = Scale - Shift;
7495       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7496                                       Low + (V == V1 ? 0 : Size)))
7497         return SDValue();
7498     }
7499
7500     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7501     bool ByteShift = ShiftEltBits > 64;
7502     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7503                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7504     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7505
7506     // Normalize the scale for byte shifts to still produce an i64 element
7507     // type.
7508     Scale = ByteShift ? Scale / 2 : Scale;
7509
7510     // We need to round trip through the appropriate type for the shift.
7511     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7512     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7513     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7514            "Illegal integer vector type");
7515     V = DAG.getBitcast(ShiftVT, V);
7516
7517     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7518                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7519     return DAG.getBitcast(VT, V);
7520   };
7521
7522   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7523   // keep doubling the size of the integer elements up to that. We can
7524   // then shift the elements of the integer vector by whole multiples of
7525   // their width within the elements of the larger integer vector. Test each
7526   // multiple to see if we can find a match with the moved element indices
7527   // and that the shifted in elements are all zeroable.
7528   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7529     for (int Shift = 1; Shift != Scale; ++Shift)
7530       for (bool Left : {true, false})
7531         if (CheckZeros(Shift, Scale, Left))
7532           for (SDValue V : {V1, V2})
7533             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7534               return Match;
7535
7536   // no match
7537   return SDValue();
7538 }
7539
7540 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7541 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7542                                            SDValue V2, ArrayRef<int> Mask,
7543                                            SelectionDAG &DAG) {
7544   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7545   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7546
7547   int Size = Mask.size();
7548   int HalfSize = Size / 2;
7549   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7550
7551   // Upper half must be undefined.
7552   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7553     return SDValue();
7554
7555   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7556   // Remainder of lower half result is zero and upper half is all undef.
7557   auto LowerAsEXTRQ = [&]() {
7558     // Determine the extraction length from the part of the
7559     // lower half that isn't zeroable.
7560     int Len = HalfSize;
7561     for (; Len > 0; --Len)
7562       if (!Zeroable[Len - 1])
7563         break;
7564     assert(Len > 0 && "Zeroable shuffle mask");
7565
7566     // Attempt to match first Len sequential elements from the lower half.
7567     SDValue Src;
7568     int Idx = -1;
7569     for (int i = 0; i != Len; ++i) {
7570       int M = Mask[i];
7571       if (M < 0)
7572         continue;
7573       SDValue &V = (M < Size ? V1 : V2);
7574       M = M % Size;
7575
7576       // The extracted elements must start at a valid index and all mask
7577       // elements must be in the lower half.
7578       if (i > M || M >= HalfSize)
7579         return SDValue();
7580
7581       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7582         Src = V;
7583         Idx = M - i;
7584         continue;
7585       }
7586       return SDValue();
7587     }
7588
7589     if (Idx < 0)
7590       return SDValue();
7591
7592     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7593     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7594     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7595     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7596                        DAG.getConstant(BitLen, DL, MVT::i8),
7597                        DAG.getConstant(BitIdx, DL, MVT::i8));
7598   };
7599
7600   if (SDValue ExtrQ = LowerAsEXTRQ())
7601     return ExtrQ;
7602
7603   // INSERTQ: Extract lowest Len elements from lower half of second source and
7604   // insert over first source, starting at Idx.
7605   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7606   auto LowerAsInsertQ = [&]() {
7607     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7608       SDValue Base;
7609
7610       // Attempt to match first source from mask before insertion point.
7611       if (isUndefInRange(Mask, 0, Idx)) {
7612         /* EMPTY */
7613       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7614         Base = V1;
7615       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7616         Base = V2;
7617       } else {
7618         continue;
7619       }
7620
7621       // Extend the extraction length looking to match both the insertion of
7622       // the second source and the remaining elements of the first.
7623       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7624         SDValue Insert;
7625         int Len = Hi - Idx;
7626
7627         // Match insertion.
7628         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7629           Insert = V1;
7630         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7631           Insert = V2;
7632         } else {
7633           continue;
7634         }
7635
7636         // Match the remaining elements of the lower half.
7637         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7638           /* EMPTY */
7639         } else if ((!Base || (Base == V1)) &&
7640                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7641           Base = V1;
7642         } else if ((!Base || (Base == V2)) &&
7643                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7644                                               Size + Hi)) {
7645           Base = V2;
7646         } else {
7647           continue;
7648         }
7649
7650         // We may not have a base (first source) - this can safely be undefined.
7651         if (!Base)
7652           Base = DAG.getUNDEF(VT);
7653
7654         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7655         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7656         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7657                            DAG.getConstant(BitLen, DL, MVT::i8),
7658                            DAG.getConstant(BitIdx, DL, MVT::i8));
7659       }
7660     }
7661
7662     return SDValue();
7663   };
7664
7665   if (SDValue InsertQ = LowerAsInsertQ())
7666     return InsertQ;
7667
7668   return SDValue();
7669 }
7670
7671 /// \brief Lower a vector shuffle as a zero or any extension.
7672 ///
7673 /// Given a specific number of elements, element bit width, and extension
7674 /// stride, produce either a zero or any extension based on the available
7675 /// features of the subtarget. The extended elements are consecutive and
7676 /// begin and can start from an offseted element index in the input; to
7677 /// avoid excess shuffling the offset must either being in the bottom lane
7678 /// or at the start of a higher lane. All extended elements must be from
7679 /// the same lane.
7680 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7681     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7682     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7683   assert(Scale > 1 && "Need a scale to extend.");
7684   int EltBits = VT.getScalarSizeInBits();
7685   int NumElements = VT.getVectorNumElements();
7686   int NumEltsPerLane = 128 / EltBits;
7687   int OffsetLane = Offset / NumEltsPerLane;
7688   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7689          "Only 8, 16, and 32 bit elements can be extended.");
7690   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7691   assert(0 <= Offset && "Extension offset must be positive.");
7692   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7693          "Extension offset must be in the first lane or start an upper lane.");
7694
7695   // Check that an index is in same lane as the base offset.
7696   auto SafeOffset = [&](int Idx) {
7697     return OffsetLane == (Idx / NumEltsPerLane);
7698   };
7699
7700   // Shift along an input so that the offset base moves to the first element.
7701   auto ShuffleOffset = [&](SDValue V) {
7702     if (!Offset)
7703       return V;
7704
7705     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7706     for (int i = 0; i * Scale < NumElements; ++i) {
7707       int SrcIdx = i + Offset;
7708       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7709     }
7710     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7711   };
7712
7713   // Found a valid zext mask! Try various lowering strategies based on the
7714   // input type and available ISA extensions.
7715   if (Subtarget->hasSSE41()) {
7716     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7717     // PUNPCK will catch this in a later shuffle match.
7718     if (Offset && Scale == 2 && VT.is128BitVector())
7719       return SDValue();
7720     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7721                                  NumElements / Scale);
7722     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7723     return DAG.getBitcast(VT, InputV);
7724   }
7725
7726   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7727
7728   // For any extends we can cheat for larger element sizes and use shuffle
7729   // instructions that can fold with a load and/or copy.
7730   if (AnyExt && EltBits == 32) {
7731     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7732                          -1};
7733     return DAG.getBitcast(
7734         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7735                         DAG.getBitcast(MVT::v4i32, InputV),
7736                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7737   }
7738   if (AnyExt && EltBits == 16 && Scale > 2) {
7739     int PSHUFDMask[4] = {Offset / 2, -1,
7740                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7741     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7742                          DAG.getBitcast(MVT::v4i32, InputV),
7743                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7744     int PSHUFWMask[4] = {1, -1, -1, -1};
7745     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7746     return DAG.getBitcast(
7747         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7748                         DAG.getBitcast(MVT::v8i16, InputV),
7749                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7750   }
7751
7752   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7753   // to 64-bits.
7754   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7755     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7756     assert(VT.is128BitVector() && "Unexpected vector width!");
7757
7758     int LoIdx = Offset * EltBits;
7759     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7760                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7761                                          DAG.getConstant(EltBits, DL, MVT::i8),
7762                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7763
7764     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7765         !SafeOffset(Offset + 1))
7766       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7767
7768     int HiIdx = (Offset + 1) * EltBits;
7769     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7770                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7771                                          DAG.getConstant(EltBits, DL, MVT::i8),
7772                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7773     return DAG.getNode(ISD::BITCAST, DL, VT,
7774                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7775   }
7776
7777   // If this would require more than 2 unpack instructions to expand, use
7778   // pshufb when available. We can only use more than 2 unpack instructions
7779   // when zero extending i8 elements which also makes it easier to use pshufb.
7780   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7781     assert(NumElements == 16 && "Unexpected byte vector width!");
7782     SDValue PSHUFBMask[16];
7783     for (int i = 0; i < 16; ++i) {
7784       int Idx = Offset + (i / Scale);
7785       PSHUFBMask[i] = DAG.getConstant(
7786           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7787     }
7788     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7789     return DAG.getBitcast(VT,
7790                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7791                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7792                                                   MVT::v16i8, PSHUFBMask)));
7793   }
7794
7795   // If we are extending from an offset, ensure we start on a boundary that
7796   // we can unpack from.
7797   int AlignToUnpack = Offset % (NumElements / Scale);
7798   if (AlignToUnpack) {
7799     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7800     for (int i = AlignToUnpack; i < NumElements; ++i)
7801       ShMask[i - AlignToUnpack] = i;
7802     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7803     Offset -= AlignToUnpack;
7804   }
7805
7806   // Otherwise emit a sequence of unpacks.
7807   do {
7808     unsigned UnpackLoHi = X86ISD::UNPCKL;
7809     if (Offset >= (NumElements / 2)) {
7810       UnpackLoHi = X86ISD::UNPCKH;
7811       Offset -= (NumElements / 2);
7812     }
7813
7814     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7815     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7816                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7817     InputV = DAG.getBitcast(InputVT, InputV);
7818     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7819     Scale /= 2;
7820     EltBits *= 2;
7821     NumElements /= 2;
7822   } while (Scale > 1);
7823   return DAG.getBitcast(VT, InputV);
7824 }
7825
7826 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7827 ///
7828 /// This routine will try to do everything in its power to cleverly lower
7829 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7830 /// check for the profitability of this lowering,  it tries to aggressively
7831 /// match this pattern. It will use all of the micro-architectural details it
7832 /// can to emit an efficient lowering. It handles both blends with all-zero
7833 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7834 /// masking out later).
7835 ///
7836 /// The reason we have dedicated lowering for zext-style shuffles is that they
7837 /// are both incredibly common and often quite performance sensitive.
7838 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7839     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7840     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7841   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7842
7843   int Bits = VT.getSizeInBits();
7844   int NumLanes = Bits / 128;
7845   int NumElements = VT.getVectorNumElements();
7846   int NumEltsPerLane = NumElements / NumLanes;
7847   assert(VT.getScalarSizeInBits() <= 32 &&
7848          "Exceeds 32-bit integer zero extension limit");
7849   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7850
7851   // Define a helper function to check a particular ext-scale and lower to it if
7852   // valid.
7853   auto Lower = [&](int Scale) -> SDValue {
7854     SDValue InputV;
7855     bool AnyExt = true;
7856     int Offset = 0;
7857     int Matches = 0;
7858     for (int i = 0; i < NumElements; ++i) {
7859       int M = Mask[i];
7860       if (M == -1)
7861         continue; // Valid anywhere but doesn't tell us anything.
7862       if (i % Scale != 0) {
7863         // Each of the extended elements need to be zeroable.
7864         if (!Zeroable[i])
7865           return SDValue();
7866
7867         // We no longer are in the anyext case.
7868         AnyExt = false;
7869         continue;
7870       }
7871
7872       // Each of the base elements needs to be consecutive indices into the
7873       // same input vector.
7874       SDValue V = M < NumElements ? V1 : V2;
7875       M = M % NumElements;
7876       if (!InputV) {
7877         InputV = V;
7878         Offset = M - (i / Scale);
7879       } else if (InputV != V)
7880         return SDValue(); // Flip-flopping inputs.
7881
7882       // Offset must start in the lowest 128-bit lane or at the start of an
7883       // upper lane.
7884       // FIXME: Is it ever worth allowing a negative base offset?
7885       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7886             (Offset % NumEltsPerLane) == 0))
7887         return SDValue();
7888
7889       // If we are offsetting, all referenced entries must come from the same
7890       // lane.
7891       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7892         return SDValue();
7893
7894       if ((M % NumElements) != (Offset + (i / Scale)))
7895         return SDValue(); // Non-consecutive strided elements.
7896       Matches++;
7897     }
7898
7899     // If we fail to find an input, we have a zero-shuffle which should always
7900     // have already been handled.
7901     // FIXME: Maybe handle this here in case during blending we end up with one?
7902     if (!InputV)
7903       return SDValue();
7904
7905     // If we are offsetting, don't extend if we only match a single input, we
7906     // can always do better by using a basic PSHUF or PUNPCK.
7907     if (Offset != 0 && Matches < 2)
7908       return SDValue();
7909
7910     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7911         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7912   };
7913
7914   // The widest scale possible for extending is to a 64-bit integer.
7915   assert(Bits % 64 == 0 &&
7916          "The number of bits in a vector must be divisible by 64 on x86!");
7917   int NumExtElements = Bits / 64;
7918
7919   // Each iteration, try extending the elements half as much, but into twice as
7920   // many elements.
7921   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7922     assert(NumElements % NumExtElements == 0 &&
7923            "The input vector size must be divisible by the extended size.");
7924     if (SDValue V = Lower(NumElements / NumExtElements))
7925       return V;
7926   }
7927
7928   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7929   if (Bits != 128)
7930     return SDValue();
7931
7932   // Returns one of the source operands if the shuffle can be reduced to a
7933   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7934   auto CanZExtLowHalf = [&]() {
7935     for (int i = NumElements / 2; i != NumElements; ++i)
7936       if (!Zeroable[i])
7937         return SDValue();
7938     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7939       return V1;
7940     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7941       return V2;
7942     return SDValue();
7943   };
7944
7945   if (SDValue V = CanZExtLowHalf()) {
7946     V = DAG.getBitcast(MVT::v2i64, V);
7947     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7948     return DAG.getBitcast(VT, V);
7949   }
7950
7951   // No viable ext lowering found.
7952   return SDValue();
7953 }
7954
7955 /// \brief Try to get a scalar value for a specific element of a vector.
7956 ///
7957 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7958 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7959                                               SelectionDAG &DAG) {
7960   MVT VT = V.getSimpleValueType();
7961   MVT EltVT = VT.getVectorElementType();
7962   while (V.getOpcode() == ISD::BITCAST)
7963     V = V.getOperand(0);
7964   // If the bitcasts shift the element size, we can't extract an equivalent
7965   // element from it.
7966   MVT NewVT = V.getSimpleValueType();
7967   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7968     return SDValue();
7969
7970   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7971       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7972     // Ensure the scalar operand is the same size as the destination.
7973     // FIXME: Add support for scalar truncation where possible.
7974     SDValue S = V.getOperand(Idx);
7975     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7976       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7977   }
7978
7979   return SDValue();
7980 }
7981
7982 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7983 ///
7984 /// This is particularly important because the set of instructions varies
7985 /// significantly based on whether the operand is a load or not.
7986 static bool isShuffleFoldableLoad(SDValue V) {
7987   while (V.getOpcode() == ISD::BITCAST)
7988     V = V.getOperand(0);
7989
7990   return ISD::isNON_EXTLoad(V.getNode());
7991 }
7992
7993 /// \brief Try to lower insertion of a single element into a zero vector.
7994 ///
7995 /// This is a common pattern that we have especially efficient patterns to lower
7996 /// across all subtarget feature sets.
7997 static SDValue lowerVectorShuffleAsElementInsertion(
7998     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7999     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8000   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8001   MVT ExtVT = VT;
8002   MVT EltVT = VT.getVectorElementType();
8003
8004   int V2Index = std::find_if(Mask.begin(), Mask.end(),
8005                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
8006                 Mask.begin();
8007   bool IsV1Zeroable = true;
8008   for (int i = 0, Size = Mask.size(); i < Size; ++i)
8009     if (i != V2Index && !Zeroable[i]) {
8010       IsV1Zeroable = false;
8011       break;
8012     }
8013
8014   // Check for a single input from a SCALAR_TO_VECTOR node.
8015   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
8016   // all the smarts here sunk into that routine. However, the current
8017   // lowering of BUILD_VECTOR makes that nearly impossible until the old
8018   // vector shuffle lowering is dead.
8019   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
8020                                                DAG);
8021   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
8022     // We need to zext the scalar if it is smaller than an i32.
8023     V2S = DAG.getBitcast(EltVT, V2S);
8024     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
8025       // Using zext to expand a narrow element won't work for non-zero
8026       // insertions.
8027       if (!IsV1Zeroable)
8028         return SDValue();
8029
8030       // Zero-extend directly to i32.
8031       ExtVT = MVT::v4i32;
8032       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
8033     }
8034     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
8035   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
8036              EltVT == MVT::i16) {
8037     // Either not inserting from the low element of the input or the input
8038     // element size is too small to use VZEXT_MOVL to clear the high bits.
8039     return SDValue();
8040   }
8041
8042   if (!IsV1Zeroable) {
8043     // If V1 can't be treated as a zero vector we have fewer options to lower
8044     // this. We can't support integer vectors or non-zero targets cheaply, and
8045     // the V1 elements can't be permuted in any way.
8046     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8047     if (!VT.isFloatingPoint() || V2Index != 0)
8048       return SDValue();
8049     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8050     V1Mask[V2Index] = -1;
8051     if (!isNoopShuffleMask(V1Mask))
8052       return SDValue();
8053     // This is essentially a special case blend operation, but if we have
8054     // general purpose blend operations, they are always faster. Bail and let
8055     // the rest of the lowering handle these as blends.
8056     if (Subtarget->hasSSE41())
8057       return SDValue();
8058
8059     // Otherwise, use MOVSD or MOVSS.
8060     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8061            "Only two types of floating point element types to handle!");
8062     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8063                        ExtVT, V1, V2);
8064   }
8065
8066   // This lowering only works for the low element with floating point vectors.
8067   if (VT.isFloatingPoint() && V2Index != 0)
8068     return SDValue();
8069
8070   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8071   if (ExtVT != VT)
8072     V2 = DAG.getBitcast(VT, V2);
8073
8074   if (V2Index != 0) {
8075     // If we have 4 or fewer lanes we can cheaply shuffle the element into
8076     // the desired position. Otherwise it is more efficient to do a vector
8077     // shift left. We know that we can do a vector shift left because all
8078     // the inputs are zero.
8079     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8080       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8081       V2Shuffle[V2Index] = 0;
8082       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8083     } else {
8084       V2 = DAG.getBitcast(MVT::v2i64, V2);
8085       V2 = DAG.getNode(
8086           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8087           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8088                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8089                               DAG.getDataLayout(), VT)));
8090       V2 = DAG.getBitcast(VT, V2);
8091     }
8092   }
8093   return V2;
8094 }
8095
8096 /// \brief Try to lower broadcast of a single - truncated - integer element,
8097 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8098 ///
8099 /// This assumes we have AVX2.
8100 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
8101                                                   int BroadcastIdx,
8102                                                   const X86Subtarget *Subtarget,
8103                                                   SelectionDAG &DAG) {
8104   assert(Subtarget->hasAVX2() &&
8105          "We can only lower integer broadcasts with AVX2!");
8106
8107   EVT EltVT = VT.getVectorElementType();
8108   EVT V0VT = V0.getValueType();
8109
8110   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8111   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8112
8113   EVT V0EltVT = V0VT.getVectorElementType();
8114   if (!V0EltVT.isInteger())
8115     return SDValue();
8116
8117   const unsigned EltSize = EltVT.getSizeInBits();
8118   const unsigned V0EltSize = V0EltVT.getSizeInBits();
8119
8120   // This is only a truncation if the original element type is larger.
8121   if (V0EltSize <= EltSize)
8122     return SDValue();
8123
8124   assert(((V0EltSize % EltSize) == 0) &&
8125          "Scalar type sizes must all be powers of 2 on x86!");
8126
8127   const unsigned V0Opc = V0.getOpcode();
8128   const unsigned Scale = V0EltSize / EltSize;
8129   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8130
8131   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8132       V0Opc != ISD::BUILD_VECTOR)
8133     return SDValue();
8134
8135   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8136
8137   // If we're extracting non-least-significant bits, shift so we can truncate.
8138   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8139   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8140   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8141   if (const int OffsetIdx = BroadcastIdx % Scale)
8142     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8143             DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8144
8145   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8146                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8147 }
8148
8149 /// \brief Try to lower broadcast of a single element.
8150 ///
8151 /// For convenience, this code also bundles all of the subtarget feature set
8152 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8153 /// a convenient way to factor it out.
8154 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8155 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8156                                              ArrayRef<int> Mask,
8157                                              const X86Subtarget *Subtarget,
8158                                              SelectionDAG &DAG) {
8159   if (!Subtarget->hasAVX())
8160     return SDValue();
8161   if (VT.isInteger() && !Subtarget->hasAVX2())
8162     return SDValue();
8163
8164   // Check that the mask is a broadcast.
8165   int BroadcastIdx = -1;
8166   for (int M : Mask)
8167     if (M >= 0 && BroadcastIdx == -1)
8168       BroadcastIdx = M;
8169     else if (M >= 0 && M != BroadcastIdx)
8170       return SDValue();
8171
8172   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8173                                             "a sorted mask where the broadcast "
8174                                             "comes from V1.");
8175
8176   // Go up the chain of (vector) values to find a scalar load that we can
8177   // combine with the broadcast.
8178   for (;;) {
8179     switch (V.getOpcode()) {
8180     case ISD::CONCAT_VECTORS: {
8181       int OperandSize = Mask.size() / V.getNumOperands();
8182       V = V.getOperand(BroadcastIdx / OperandSize);
8183       BroadcastIdx %= OperandSize;
8184       continue;
8185     }
8186
8187     case ISD::INSERT_SUBVECTOR: {
8188       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8189       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8190       if (!ConstantIdx)
8191         break;
8192
8193       int BeginIdx = (int)ConstantIdx->getZExtValue();
8194       int EndIdx =
8195           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8196       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8197         BroadcastIdx -= BeginIdx;
8198         V = VInner;
8199       } else {
8200         V = VOuter;
8201       }
8202       continue;
8203     }
8204     }
8205     break;
8206   }
8207
8208   // Check if this is a broadcast of a scalar. We special case lowering
8209   // for scalars so that we can more effectively fold with loads.
8210   // First, look through bitcast: if the original value has a larger element
8211   // type than the shuffle, the broadcast element is in essence truncated.
8212   // Make that explicit to ease folding.
8213   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8214     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8215             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8216       return TruncBroadcast;
8217
8218   MVT BroadcastVT = VT;
8219
8220   // Peek through any bitcast (only useful for loads).
8221   SDValue BC = V;
8222   while (BC.getOpcode() == ISD::BITCAST)
8223     BC = BC.getOperand(0);
8224
8225   // Also check the simpler case, where we can directly reuse the scalar.
8226   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8227       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8228     V = V.getOperand(BroadcastIdx);
8229
8230     // If the scalar isn't a load, we can't broadcast from it in AVX1.
8231     // Only AVX2 has register broadcasts.
8232     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8233       return SDValue();
8234   } else if (MayFoldLoad(BC) && !cast<LoadSDNode>(BC)->isVolatile()) {
8235     // 32-bit targets need to load i64 as a f64 and then bitcast the result.
8236     if (!Subtarget->is64Bit() && VT.getScalarType() == MVT::i64)
8237       BroadcastVT = MVT::getVectorVT(MVT::f64, VT.getVectorNumElements());
8238
8239     // If we are broadcasting a load that is only used by the shuffle
8240     // then we can reduce the vector load to the broadcasted scalar load.
8241     LoadSDNode *Ld = cast<LoadSDNode>(BC);
8242     SDValue BaseAddr = Ld->getOperand(1);
8243     EVT AddrVT = BaseAddr.getValueType();
8244     EVT SVT = BroadcastVT.getScalarType();
8245     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8246     SDValue NewAddr = DAG.getNode(
8247         ISD::ADD, DL, AddrVT, BaseAddr,
8248         DAG.getConstant(Offset, DL, AddrVT));
8249     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8250                     DAG.getMachineFunction().getMachineMemOperand(
8251                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8252   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8253     // We can't broadcast from a vector register without AVX2, and we can only
8254     // broadcast from the zero-element of a vector register.
8255     return SDValue();
8256   }
8257
8258   V = DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, V);
8259   return DAG.getBitcast(VT, V);
8260 }
8261
8262 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8263 // INSERTPS when the V1 elements are already in the correct locations
8264 // because otherwise we can just always use two SHUFPS instructions which
8265 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8266 // perform INSERTPS if a single V1 element is out of place and all V2
8267 // elements are zeroable.
8268 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8269                                             ArrayRef<int> Mask,
8270                                             SelectionDAG &DAG) {
8271   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8272   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8273   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8274   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8275
8276   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8277
8278   unsigned ZMask = 0;
8279   int V1DstIndex = -1;
8280   int V2DstIndex = -1;
8281   bool V1UsedInPlace = false;
8282
8283   for (int i = 0; i < 4; ++i) {
8284     // Synthesize a zero mask from the zeroable elements (includes undefs).
8285     if (Zeroable[i]) {
8286       ZMask |= 1 << i;
8287       continue;
8288     }
8289
8290     // Flag if we use any V1 inputs in place.
8291     if (i == Mask[i]) {
8292       V1UsedInPlace = true;
8293       continue;
8294     }
8295
8296     // We can only insert a single non-zeroable element.
8297     if (V1DstIndex != -1 || V2DstIndex != -1)
8298       return SDValue();
8299
8300     if (Mask[i] < 4) {
8301       // V1 input out of place for insertion.
8302       V1DstIndex = i;
8303     } else {
8304       // V2 input for insertion.
8305       V2DstIndex = i;
8306     }
8307   }
8308
8309   // Don't bother if we have no (non-zeroable) element for insertion.
8310   if (V1DstIndex == -1 && V2DstIndex == -1)
8311     return SDValue();
8312
8313   // Determine element insertion src/dst indices. The src index is from the
8314   // start of the inserted vector, not the start of the concatenated vector.
8315   unsigned V2SrcIndex = 0;
8316   if (V1DstIndex != -1) {
8317     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8318     // and don't use the original V2 at all.
8319     V2SrcIndex = Mask[V1DstIndex];
8320     V2DstIndex = V1DstIndex;
8321     V2 = V1;
8322   } else {
8323     V2SrcIndex = Mask[V2DstIndex] - 4;
8324   }
8325
8326   // If no V1 inputs are used in place, then the result is created only from
8327   // the zero mask and the V2 insertion - so remove V1 dependency.
8328   if (!V1UsedInPlace)
8329     V1 = DAG.getUNDEF(MVT::v4f32);
8330
8331   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8332   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8333
8334   // Insert the V2 element into the desired position.
8335   SDLoc DL(Op);
8336   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8337                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8338 }
8339
8340 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8341 /// UNPCK instruction.
8342 ///
8343 /// This specifically targets cases where we end up with alternating between
8344 /// the two inputs, and so can permute them into something that feeds a single
8345 /// UNPCK instruction. Note that this routine only targets integer vectors
8346 /// because for floating point vectors we have a generalized SHUFPS lowering
8347 /// strategy that handles everything that doesn't *exactly* match an unpack,
8348 /// making this clever lowering unnecessary.
8349 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8350                                                     SDValue V1, SDValue V2,
8351                                                     ArrayRef<int> Mask,
8352                                                     SelectionDAG &DAG) {
8353   assert(!VT.isFloatingPoint() &&
8354          "This routine only supports integer vectors.");
8355   assert(!isSingleInputShuffleMask(Mask) &&
8356          "This routine should only be used when blending two inputs.");
8357   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8358
8359   int Size = Mask.size();
8360
8361   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8362     return M >= 0 && M % Size < Size / 2;
8363   });
8364   int NumHiInputs = std::count_if(
8365       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8366
8367   bool UnpackLo = NumLoInputs >= NumHiInputs;
8368
8369   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8370     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8371     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8372
8373     for (int i = 0; i < Size; ++i) {
8374       if (Mask[i] < 0)
8375         continue;
8376
8377       // Each element of the unpack contains Scale elements from this mask.
8378       int UnpackIdx = i / Scale;
8379
8380       // We only handle the case where V1 feeds the first slots of the unpack.
8381       // We rely on canonicalization to ensure this is the case.
8382       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8383         return SDValue();
8384
8385       // Setup the mask for this input. The indexing is tricky as we have to
8386       // handle the unpack stride.
8387       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8388       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8389           Mask[i] % Size;
8390     }
8391
8392     // If we will have to shuffle both inputs to use the unpack, check whether
8393     // we can just unpack first and shuffle the result. If so, skip this unpack.
8394     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8395         !isNoopShuffleMask(V2Mask))
8396       return SDValue();
8397
8398     // Shuffle the inputs into place.
8399     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8400     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8401
8402     // Cast the inputs to the type we will use to unpack them.
8403     V1 = DAG.getBitcast(UnpackVT, V1);
8404     V2 = DAG.getBitcast(UnpackVT, V2);
8405
8406     // Unpack the inputs and cast the result back to the desired type.
8407     return DAG.getBitcast(
8408         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8409                         UnpackVT, V1, V2));
8410   };
8411
8412   // We try each unpack from the largest to the smallest to try and find one
8413   // that fits this mask.
8414   int OrigNumElements = VT.getVectorNumElements();
8415   int OrigScalarSize = VT.getScalarSizeInBits();
8416   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8417     int Scale = ScalarSize / OrigScalarSize;
8418     int NumElements = OrigNumElements / Scale;
8419     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8420     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8421       return Unpack;
8422   }
8423
8424   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8425   // initial unpack.
8426   if (NumLoInputs == 0 || NumHiInputs == 0) {
8427     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8428            "We have to have *some* inputs!");
8429     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8430
8431     // FIXME: We could consider the total complexity of the permute of each
8432     // possible unpacking. Or at the least we should consider how many
8433     // half-crossings are created.
8434     // FIXME: We could consider commuting the unpacks.
8435
8436     SmallVector<int, 32> PermMask;
8437     PermMask.assign(Size, -1);
8438     for (int i = 0; i < Size; ++i) {
8439       if (Mask[i] < 0)
8440         continue;
8441
8442       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8443
8444       PermMask[i] =
8445           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8446     }
8447     return DAG.getVectorShuffle(
8448         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8449                             DL, VT, V1, V2),
8450         DAG.getUNDEF(VT), PermMask);
8451   }
8452
8453   return SDValue();
8454 }
8455
8456 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8457 ///
8458 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8459 /// support for floating point shuffles but not integer shuffles. These
8460 /// instructions will incur a domain crossing penalty on some chips though so
8461 /// it is better to avoid lowering through this for integer vectors where
8462 /// possible.
8463 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8464                                        const X86Subtarget *Subtarget,
8465                                        SelectionDAG &DAG) {
8466   SDLoc DL(Op);
8467   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8468   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8469   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8470   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8471   ArrayRef<int> Mask = SVOp->getMask();
8472   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8473
8474   if (isSingleInputShuffleMask(Mask)) {
8475     // Use low duplicate instructions for masks that match their pattern.
8476     if (Subtarget->hasSSE3())
8477       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8478         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8479
8480     // Straight shuffle of a single input vector. Simulate this by using the
8481     // single input as both of the "inputs" to this instruction..
8482     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8483
8484     if (Subtarget->hasAVX()) {
8485       // If we have AVX, we can use VPERMILPS which will allow folding a load
8486       // into the shuffle.
8487       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8488                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8489     }
8490
8491     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8492                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8493   }
8494   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8495   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8496
8497   // If we have a single input, insert that into V1 if we can do so cheaply.
8498   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8499     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8500             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8501       return Insertion;
8502     // Try inverting the insertion since for v2 masks it is easy to do and we
8503     // can't reliably sort the mask one way or the other.
8504     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8505                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8506     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8507             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8508       return Insertion;
8509   }
8510
8511   // Try to use one of the special instruction patterns to handle two common
8512   // blend patterns if a zero-blend above didn't work.
8513   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8514       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8515     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8516       // We can either use a special instruction to load over the low double or
8517       // to move just the low double.
8518       return DAG.getNode(
8519           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8520           DL, MVT::v2f64, V2,
8521           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8522
8523   if (Subtarget->hasSSE41())
8524     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8525                                                   Subtarget, DAG))
8526       return Blend;
8527
8528   // Use dedicated unpack instructions for masks that match their pattern.
8529   if (SDValue V =
8530           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8531     return V;
8532
8533   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8534   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8535                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8536 }
8537
8538 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8539 ///
8540 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8541 /// the integer unit to minimize domain crossing penalties. However, for blends
8542 /// it falls back to the floating point shuffle operation with appropriate bit
8543 /// casting.
8544 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8545                                        const X86Subtarget *Subtarget,
8546                                        SelectionDAG &DAG) {
8547   SDLoc DL(Op);
8548   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8549   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8550   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8551   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8552   ArrayRef<int> Mask = SVOp->getMask();
8553   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8554
8555   if (isSingleInputShuffleMask(Mask)) {
8556     // Check for being able to broadcast a single element.
8557     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8558                                                           Mask, Subtarget, DAG))
8559       return Broadcast;
8560
8561     // Straight shuffle of a single input vector. For everything from SSE2
8562     // onward this has a single fast instruction with no scary immediates.
8563     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8564     V1 = DAG.getBitcast(MVT::v4i32, V1);
8565     int WidenedMask[4] = {
8566         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8567         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8568     return DAG.getBitcast(
8569         MVT::v2i64,
8570         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8571                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8572   }
8573   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8574   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8575   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8576   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8577
8578   // If we have a blend of two PACKUS operations an the blend aligns with the
8579   // low and half halves, we can just merge the PACKUS operations. This is
8580   // particularly important as it lets us merge shuffles that this routine itself
8581   // creates.
8582   auto GetPackNode = [](SDValue V) {
8583     while (V.getOpcode() == ISD::BITCAST)
8584       V = V.getOperand(0);
8585
8586     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8587   };
8588   if (SDValue V1Pack = GetPackNode(V1))
8589     if (SDValue V2Pack = GetPackNode(V2))
8590       return DAG.getBitcast(MVT::v2i64,
8591                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8592                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8593                                                      : V1Pack.getOperand(1),
8594                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8595                                                      : V2Pack.getOperand(1)));
8596
8597   // Try to use shift instructions.
8598   if (SDValue Shift =
8599           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8600     return Shift;
8601
8602   // When loading a scalar and then shuffling it into a vector we can often do
8603   // the insertion cheaply.
8604   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8605           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8606     return Insertion;
8607   // Try inverting the insertion since for v2 masks it is easy to do and we
8608   // can't reliably sort the mask one way or the other.
8609   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8610   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8611           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8612     return Insertion;
8613
8614   // We have different paths for blend lowering, but they all must use the
8615   // *exact* same predicate.
8616   bool IsBlendSupported = Subtarget->hasSSE41();
8617   if (IsBlendSupported)
8618     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8619                                                   Subtarget, DAG))
8620       return Blend;
8621
8622   // Use dedicated unpack instructions for masks that match their pattern.
8623   if (SDValue V =
8624           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8625     return V;
8626
8627   // Try to use byte rotation instructions.
8628   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8629   if (Subtarget->hasSSSE3())
8630     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8631             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8632       return Rotate;
8633
8634   // If we have direct support for blends, we should lower by decomposing into
8635   // a permute. That will be faster than the domain cross.
8636   if (IsBlendSupported)
8637     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8638                                                       Mask, DAG);
8639
8640   // We implement this with SHUFPD which is pretty lame because it will likely
8641   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8642   // However, all the alternatives are still more cycles and newer chips don't
8643   // have this problem. It would be really nice if x86 had better shuffles here.
8644   V1 = DAG.getBitcast(MVT::v2f64, V1);
8645   V2 = DAG.getBitcast(MVT::v2f64, V2);
8646   return DAG.getBitcast(MVT::v2i64,
8647                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8648 }
8649
8650 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8651 ///
8652 /// This is used to disable more specialized lowerings when the shufps lowering
8653 /// will happen to be efficient.
8654 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8655   // This routine only handles 128-bit shufps.
8656   assert(Mask.size() == 4 && "Unsupported mask size!");
8657
8658   // To lower with a single SHUFPS we need to have the low half and high half
8659   // each requiring a single input.
8660   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8661     return false;
8662   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8663     return false;
8664
8665   return true;
8666 }
8667
8668 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8669 ///
8670 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8671 /// It makes no assumptions about whether this is the *best* lowering, it simply
8672 /// uses it.
8673 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8674                                             ArrayRef<int> Mask, SDValue V1,
8675                                             SDValue V2, SelectionDAG &DAG) {
8676   SDValue LowV = V1, HighV = V2;
8677   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8678
8679   int NumV2Elements =
8680       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8681
8682   if (NumV2Elements == 1) {
8683     int V2Index =
8684         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8685         Mask.begin();
8686
8687     // Compute the index adjacent to V2Index and in the same half by toggling
8688     // the low bit.
8689     int V2AdjIndex = V2Index ^ 1;
8690
8691     if (Mask[V2AdjIndex] == -1) {
8692       // Handles all the cases where we have a single V2 element and an undef.
8693       // This will only ever happen in the high lanes because we commute the
8694       // vector otherwise.
8695       if (V2Index < 2)
8696         std::swap(LowV, HighV);
8697       NewMask[V2Index] -= 4;
8698     } else {
8699       // Handle the case where the V2 element ends up adjacent to a V1 element.
8700       // To make this work, blend them together as the first step.
8701       int V1Index = V2AdjIndex;
8702       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8703       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8704                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8705
8706       // Now proceed to reconstruct the final blend as we have the necessary
8707       // high or low half formed.
8708       if (V2Index < 2) {
8709         LowV = V2;
8710         HighV = V1;
8711       } else {
8712         HighV = V2;
8713       }
8714       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8715       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8716     }
8717   } else if (NumV2Elements == 2) {
8718     if (Mask[0] < 4 && Mask[1] < 4) {
8719       // Handle the easy case where we have V1 in the low lanes and V2 in the
8720       // high lanes.
8721       NewMask[2] -= 4;
8722       NewMask[3] -= 4;
8723     } else if (Mask[2] < 4 && Mask[3] < 4) {
8724       // We also handle the reversed case because this utility may get called
8725       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8726       // arrange things in the right direction.
8727       NewMask[0] -= 4;
8728       NewMask[1] -= 4;
8729       HighV = V1;
8730       LowV = V2;
8731     } else {
8732       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8733       // trying to place elements directly, just blend them and set up the final
8734       // shuffle to place them.
8735
8736       // The first two blend mask elements are for V1, the second two are for
8737       // V2.
8738       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8739                           Mask[2] < 4 ? Mask[2] : Mask[3],
8740                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8741                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8742       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8743                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8744
8745       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8746       // a blend.
8747       LowV = HighV = V1;
8748       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8749       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8750       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8751       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8752     }
8753   }
8754   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8755                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8756 }
8757
8758 /// \brief Lower 4-lane 32-bit floating point shuffles.
8759 ///
8760 /// Uses instructions exclusively from the floating point unit to minimize
8761 /// domain crossing penalties, as these are sufficient to implement all v4f32
8762 /// shuffles.
8763 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8764                                        const X86Subtarget *Subtarget,
8765                                        SelectionDAG &DAG) {
8766   SDLoc DL(Op);
8767   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8768   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8769   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8770   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8771   ArrayRef<int> Mask = SVOp->getMask();
8772   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8773
8774   int NumV2Elements =
8775       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8776
8777   if (NumV2Elements == 0) {
8778     // Check for being able to broadcast a single element.
8779     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8780                                                           Mask, Subtarget, DAG))
8781       return Broadcast;
8782
8783     // Use even/odd duplicate instructions for masks that match their pattern.
8784     if (Subtarget->hasSSE3()) {
8785       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8786         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8787       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8788         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8789     }
8790
8791     if (Subtarget->hasAVX()) {
8792       // If we have AVX, we can use VPERMILPS which will allow folding a load
8793       // into the shuffle.
8794       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8795                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8796     }
8797
8798     // Otherwise, use a straight shuffle of a single input vector. We pass the
8799     // input vector to both operands to simulate this with a SHUFPS.
8800     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8801                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8802   }
8803
8804   // There are special ways we can lower some single-element blends. However, we
8805   // have custom ways we can lower more complex single-element blends below that
8806   // we defer to if both this and BLENDPS fail to match, so restrict this to
8807   // when the V2 input is targeting element 0 of the mask -- that is the fast
8808   // case here.
8809   if (NumV2Elements == 1 && Mask[0] >= 4)
8810     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8811                                                          Mask, Subtarget, DAG))
8812       return V;
8813
8814   if (Subtarget->hasSSE41()) {
8815     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8816                                                   Subtarget, DAG))
8817       return Blend;
8818
8819     // Use INSERTPS if we can complete the shuffle efficiently.
8820     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8821       return V;
8822
8823     if (!isSingleSHUFPSMask(Mask))
8824       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8825               DL, MVT::v4f32, V1, V2, Mask, DAG))
8826         return BlendPerm;
8827   }
8828
8829   // Use dedicated unpack instructions for masks that match their pattern.
8830   if (SDValue V =
8831           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8832     return V;
8833
8834   // Otherwise fall back to a SHUFPS lowering strategy.
8835   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8836 }
8837
8838 /// \brief Lower 4-lane i32 vector shuffles.
8839 ///
8840 /// We try to handle these with integer-domain shuffles where we can, but for
8841 /// blends we use the floating point domain blend instructions.
8842 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8843                                        const X86Subtarget *Subtarget,
8844                                        SelectionDAG &DAG) {
8845   SDLoc DL(Op);
8846   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8847   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8848   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8849   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8850   ArrayRef<int> Mask = SVOp->getMask();
8851   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8852
8853   // Whenever we can lower this as a zext, that instruction is strictly faster
8854   // than any alternative. It also allows us to fold memory operands into the
8855   // shuffle in many cases.
8856   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8857                                                          Mask, Subtarget, DAG))
8858     return ZExt;
8859
8860   int NumV2Elements =
8861       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8862
8863   if (NumV2Elements == 0) {
8864     // Check for being able to broadcast a single element.
8865     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8866                                                           Mask, Subtarget, DAG))
8867       return Broadcast;
8868
8869     // Straight shuffle of a single input vector. For everything from SSE2
8870     // onward this has a single fast instruction with no scary immediates.
8871     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8872     // but we aren't actually going to use the UNPCK instruction because doing
8873     // so prevents folding a load into this instruction or making a copy.
8874     const int UnpackLoMask[] = {0, 0, 1, 1};
8875     const int UnpackHiMask[] = {2, 2, 3, 3};
8876     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8877       Mask = UnpackLoMask;
8878     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8879       Mask = UnpackHiMask;
8880
8881     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8882                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8883   }
8884
8885   // Try to use shift instructions.
8886   if (SDValue Shift =
8887           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8888     return Shift;
8889
8890   // There are special ways we can lower some single-element blends.
8891   if (NumV2Elements == 1)
8892     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8893                                                          Mask, Subtarget, DAG))
8894       return V;
8895
8896   // We have different paths for blend lowering, but they all must use the
8897   // *exact* same predicate.
8898   bool IsBlendSupported = Subtarget->hasSSE41();
8899   if (IsBlendSupported)
8900     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8901                                                   Subtarget, DAG))
8902       return Blend;
8903
8904   if (SDValue Masked =
8905           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8906     return Masked;
8907
8908   // Use dedicated unpack instructions for masks that match their pattern.
8909   if (SDValue V =
8910           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8911     return V;
8912
8913   // Try to use byte rotation instructions.
8914   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8915   if (Subtarget->hasSSSE3())
8916     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8917             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8918       return Rotate;
8919
8920   // If we have direct support for blends, we should lower by decomposing into
8921   // a permute. That will be faster than the domain cross.
8922   if (IsBlendSupported)
8923     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8924                                                       Mask, DAG);
8925
8926   // Try to lower by permuting the inputs into an unpack instruction.
8927   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8928                                                             V2, Mask, DAG))
8929     return Unpack;
8930
8931   // We implement this with SHUFPS because it can blend from two vectors.
8932   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8933   // up the inputs, bypassing domain shift penalties that we would encur if we
8934   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8935   // relevant.
8936   return DAG.getBitcast(
8937       MVT::v4i32,
8938       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8939                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8940 }
8941
8942 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8943 /// shuffle lowering, and the most complex part.
8944 ///
8945 /// The lowering strategy is to try to form pairs of input lanes which are
8946 /// targeted at the same half of the final vector, and then use a dword shuffle
8947 /// to place them onto the right half, and finally unpack the paired lanes into
8948 /// their final position.
8949 ///
8950 /// The exact breakdown of how to form these dword pairs and align them on the
8951 /// correct sides is really tricky. See the comments within the function for
8952 /// more of the details.
8953 ///
8954 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8955 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8956 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8957 /// vector, form the analogous 128-bit 8-element Mask.
8958 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8959     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8960     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8961   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8962   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8963
8964   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8965   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8966   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8967
8968   SmallVector<int, 4> LoInputs;
8969   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8970                [](int M) { return M >= 0; });
8971   std::sort(LoInputs.begin(), LoInputs.end());
8972   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8973   SmallVector<int, 4> HiInputs;
8974   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8975                [](int M) { return M >= 0; });
8976   std::sort(HiInputs.begin(), HiInputs.end());
8977   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8978   int NumLToL =
8979       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8980   int NumHToL = LoInputs.size() - NumLToL;
8981   int NumLToH =
8982       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8983   int NumHToH = HiInputs.size() - NumLToH;
8984   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8985   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8986   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8987   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8988
8989   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8990   // such inputs we can swap two of the dwords across the half mark and end up
8991   // with <=2 inputs to each half in each half. Once there, we can fall through
8992   // to the generic code below. For example:
8993   //
8994   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8995   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8996   //
8997   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8998   // and an existing 2-into-2 on the other half. In this case we may have to
8999   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
9000   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
9001   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
9002   // because any other situation (including a 3-into-1 or 1-into-3 in the other
9003   // half than the one we target for fixing) will be fixed when we re-enter this
9004   // path. We will also combine away any sequence of PSHUFD instructions that
9005   // result into a single instruction. Here is an example of the tricky case:
9006   //
9007   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
9008   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
9009   //
9010   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
9011   //
9012   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
9013   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
9014   //
9015   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
9016   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
9017   //
9018   // The result is fine to be handled by the generic logic.
9019   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
9020                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
9021                           int AOffset, int BOffset) {
9022     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
9023            "Must call this with A having 3 or 1 inputs from the A half.");
9024     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
9025            "Must call this with B having 1 or 3 inputs from the B half.");
9026     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
9027            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
9028
9029     bool ThreeAInputs = AToAInputs.size() == 3;
9030
9031     // Compute the index of dword with only one word among the three inputs in
9032     // a half by taking the sum of the half with three inputs and subtracting
9033     // the sum of the actual three inputs. The difference is the remaining
9034     // slot.
9035     int ADWord, BDWord;
9036     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
9037     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
9038     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
9039     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
9040     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
9041     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
9042     int TripleNonInputIdx =
9043         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
9044     TripleDWord = TripleNonInputIdx / 2;
9045
9046     // We use xor with one to compute the adjacent DWord to whichever one the
9047     // OneInput is in.
9048     OneInputDWord = (OneInput / 2) ^ 1;
9049
9050     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
9051     // and BToA inputs. If there is also such a problem with the BToB and AToB
9052     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
9053     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
9054     // is essential that we don't *create* a 3<-1 as then we might oscillate.
9055     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
9056       // Compute how many inputs will be flipped by swapping these DWords. We
9057       // need
9058       // to balance this to ensure we don't form a 3-1 shuffle in the other
9059       // half.
9060       int NumFlippedAToBInputs =
9061           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9062           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9063       int NumFlippedBToBInputs =
9064           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9065           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9066       if ((NumFlippedAToBInputs == 1 &&
9067            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9068           (NumFlippedBToBInputs == 1 &&
9069            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9070         // We choose whether to fix the A half or B half based on whether that
9071         // half has zero flipped inputs. At zero, we may not be able to fix it
9072         // with that half. We also bias towards fixing the B half because that
9073         // will more commonly be the high half, and we have to bias one way.
9074         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9075                                                        ArrayRef<int> Inputs) {
9076           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9077           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9078                                          PinnedIdx ^ 1) != Inputs.end();
9079           // Determine whether the free index is in the flipped dword or the
9080           // unflipped dword based on where the pinned index is. We use this bit
9081           // in an xor to conditionally select the adjacent dword.
9082           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9083           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9084                                              FixFreeIdx) != Inputs.end();
9085           if (IsFixIdxInput == IsFixFreeIdxInput)
9086             FixFreeIdx += 1;
9087           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9088                                         FixFreeIdx) != Inputs.end();
9089           assert(IsFixIdxInput != IsFixFreeIdxInput &&
9090                  "We need to be changing the number of flipped inputs!");
9091           int PSHUFHalfMask[] = {0, 1, 2, 3};
9092           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9093           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9094                           MVT::v8i16, V,
9095                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9096
9097           for (int &M : Mask)
9098             if (M != -1 && M == FixIdx)
9099               M = FixFreeIdx;
9100             else if (M != -1 && M == FixFreeIdx)
9101               M = FixIdx;
9102         };
9103         if (NumFlippedBToBInputs != 0) {
9104           int BPinnedIdx =
9105               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9106           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9107         } else {
9108           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9109           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9110           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9111         }
9112       }
9113     }
9114
9115     int PSHUFDMask[] = {0, 1, 2, 3};
9116     PSHUFDMask[ADWord] = BDWord;
9117     PSHUFDMask[BDWord] = ADWord;
9118     V = DAG.getBitcast(
9119         VT,
9120         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9121                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9122
9123     // Adjust the mask to match the new locations of A and B.
9124     for (int &M : Mask)
9125       if (M != -1 && M/2 == ADWord)
9126         M = 2 * BDWord + M % 2;
9127       else if (M != -1 && M/2 == BDWord)
9128         M = 2 * ADWord + M % 2;
9129
9130     // Recurse back into this routine to re-compute state now that this isn't
9131     // a 3 and 1 problem.
9132     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9133                                                      DAG);
9134   };
9135   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9136     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9137   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9138     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9139
9140   // At this point there are at most two inputs to the low and high halves from
9141   // each half. That means the inputs can always be grouped into dwords and
9142   // those dwords can then be moved to the correct half with a dword shuffle.
9143   // We use at most one low and one high word shuffle to collect these paired
9144   // inputs into dwords, and finally a dword shuffle to place them.
9145   int PSHUFLMask[4] = {-1, -1, -1, -1};
9146   int PSHUFHMask[4] = {-1, -1, -1, -1};
9147   int PSHUFDMask[4] = {-1, -1, -1, -1};
9148
9149   // First fix the masks for all the inputs that are staying in their
9150   // original halves. This will then dictate the targets of the cross-half
9151   // shuffles.
9152   auto fixInPlaceInputs =
9153       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9154                     MutableArrayRef<int> SourceHalfMask,
9155                     MutableArrayRef<int> HalfMask, int HalfOffset) {
9156     if (InPlaceInputs.empty())
9157       return;
9158     if (InPlaceInputs.size() == 1) {
9159       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9160           InPlaceInputs[0] - HalfOffset;
9161       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9162       return;
9163     }
9164     if (IncomingInputs.empty()) {
9165       // Just fix all of the in place inputs.
9166       for (int Input : InPlaceInputs) {
9167         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9168         PSHUFDMask[Input / 2] = Input / 2;
9169       }
9170       return;
9171     }
9172
9173     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9174     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9175         InPlaceInputs[0] - HalfOffset;
9176     // Put the second input next to the first so that they are packed into
9177     // a dword. We find the adjacent index by toggling the low bit.
9178     int AdjIndex = InPlaceInputs[0] ^ 1;
9179     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9180     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9181     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9182   };
9183   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9184   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9185
9186   // Now gather the cross-half inputs and place them into a free dword of
9187   // their target half.
9188   // FIXME: This operation could almost certainly be simplified dramatically to
9189   // look more like the 3-1 fixing operation.
9190   auto moveInputsToRightHalf = [&PSHUFDMask](
9191       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9192       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9193       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9194       int DestOffset) {
9195     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9196       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9197     };
9198     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9199                                                int Word) {
9200       int LowWord = Word & ~1;
9201       int HighWord = Word | 1;
9202       return isWordClobbered(SourceHalfMask, LowWord) ||
9203              isWordClobbered(SourceHalfMask, HighWord);
9204     };
9205
9206     if (IncomingInputs.empty())
9207       return;
9208
9209     if (ExistingInputs.empty()) {
9210       // Map any dwords with inputs from them into the right half.
9211       for (int Input : IncomingInputs) {
9212         // If the source half mask maps over the inputs, turn those into
9213         // swaps and use the swapped lane.
9214         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9215           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9216             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9217                 Input - SourceOffset;
9218             // We have to swap the uses in our half mask in one sweep.
9219             for (int &M : HalfMask)
9220               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9221                 M = Input;
9222               else if (M == Input)
9223                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9224           } else {
9225             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9226                        Input - SourceOffset &&
9227                    "Previous placement doesn't match!");
9228           }
9229           // Note that this correctly re-maps both when we do a swap and when
9230           // we observe the other side of the swap above. We rely on that to
9231           // avoid swapping the members of the input list directly.
9232           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9233         }
9234
9235         // Map the input's dword into the correct half.
9236         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9237           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9238         else
9239           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9240                      Input / 2 &&
9241                  "Previous placement doesn't match!");
9242       }
9243
9244       // And just directly shift any other-half mask elements to be same-half
9245       // as we will have mirrored the dword containing the element into the
9246       // same position within that half.
9247       for (int &M : HalfMask)
9248         if (M >= SourceOffset && M < SourceOffset + 4) {
9249           M = M - SourceOffset + DestOffset;
9250           assert(M >= 0 && "This should never wrap below zero!");
9251         }
9252       return;
9253     }
9254
9255     // Ensure we have the input in a viable dword of its current half. This
9256     // is particularly tricky because the original position may be clobbered
9257     // by inputs being moved and *staying* in that half.
9258     if (IncomingInputs.size() == 1) {
9259       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9260         int InputFixed = std::find(std::begin(SourceHalfMask),
9261                                    std::end(SourceHalfMask), -1) -
9262                          std::begin(SourceHalfMask) + SourceOffset;
9263         SourceHalfMask[InputFixed - SourceOffset] =
9264             IncomingInputs[0] - SourceOffset;
9265         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9266                      InputFixed);
9267         IncomingInputs[0] = InputFixed;
9268       }
9269     } else if (IncomingInputs.size() == 2) {
9270       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9271           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9272         // We have two non-adjacent or clobbered inputs we need to extract from
9273         // the source half. To do this, we need to map them into some adjacent
9274         // dword slot in the source mask.
9275         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9276                               IncomingInputs[1] - SourceOffset};
9277
9278         // If there is a free slot in the source half mask adjacent to one of
9279         // the inputs, place the other input in it. We use (Index XOR 1) to
9280         // compute an adjacent index.
9281         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9282             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9283           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9284           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9285           InputsFixed[1] = InputsFixed[0] ^ 1;
9286         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9287                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9288           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9289           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9290           InputsFixed[0] = InputsFixed[1] ^ 1;
9291         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9292                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9293           // The two inputs are in the same DWord but it is clobbered and the
9294           // adjacent DWord isn't used at all. Move both inputs to the free
9295           // slot.
9296           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9297           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9298           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9299           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9300         } else {
9301           // The only way we hit this point is if there is no clobbering
9302           // (because there are no off-half inputs to this half) and there is no
9303           // free slot adjacent to one of the inputs. In this case, we have to
9304           // swap an input with a non-input.
9305           for (int i = 0; i < 4; ++i)
9306             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9307                    "We can't handle any clobbers here!");
9308           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9309                  "Cannot have adjacent inputs here!");
9310
9311           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9312           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9313
9314           // We also have to update the final source mask in this case because
9315           // it may need to undo the above swap.
9316           for (int &M : FinalSourceHalfMask)
9317             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9318               M = InputsFixed[1] + SourceOffset;
9319             else if (M == InputsFixed[1] + SourceOffset)
9320               M = (InputsFixed[0] ^ 1) + SourceOffset;
9321
9322           InputsFixed[1] = InputsFixed[0] ^ 1;
9323         }
9324
9325         // Point everything at the fixed inputs.
9326         for (int &M : HalfMask)
9327           if (M == IncomingInputs[0])
9328             M = InputsFixed[0] + SourceOffset;
9329           else if (M == IncomingInputs[1])
9330             M = InputsFixed[1] + SourceOffset;
9331
9332         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9333         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9334       }
9335     } else {
9336       llvm_unreachable("Unhandled input size!");
9337     }
9338
9339     // Now hoist the DWord down to the right half.
9340     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9341     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9342     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9343     for (int &M : HalfMask)
9344       for (int Input : IncomingInputs)
9345         if (M == Input)
9346           M = FreeDWord * 2 + Input % 2;
9347   };
9348   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9349                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9350   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9351                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9352
9353   // Now enact all the shuffles we've computed to move the inputs into their
9354   // target half.
9355   if (!isNoopShuffleMask(PSHUFLMask))
9356     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9357                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9358   if (!isNoopShuffleMask(PSHUFHMask))
9359     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9360                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9361   if (!isNoopShuffleMask(PSHUFDMask))
9362     V = DAG.getBitcast(
9363         VT,
9364         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9365                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9366
9367   // At this point, each half should contain all its inputs, and we can then
9368   // just shuffle them into their final position.
9369   assert(std::count_if(LoMask.begin(), LoMask.end(),
9370                        [](int M) { return M >= 4; }) == 0 &&
9371          "Failed to lift all the high half inputs to the low mask!");
9372   assert(std::count_if(HiMask.begin(), HiMask.end(),
9373                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9374          "Failed to lift all the low half inputs to the high mask!");
9375
9376   // Do a half shuffle for the low mask.
9377   if (!isNoopShuffleMask(LoMask))
9378     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9379                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9380
9381   // Do a half shuffle with the high mask after shifting its values down.
9382   for (int &M : HiMask)
9383     if (M >= 0)
9384       M -= 4;
9385   if (!isNoopShuffleMask(HiMask))
9386     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9387                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9388
9389   return V;
9390 }
9391
9392 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9393 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9394                                           SDValue V2, ArrayRef<int> Mask,
9395                                           SelectionDAG &DAG, bool &V1InUse,
9396                                           bool &V2InUse) {
9397   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9398   SDValue V1Mask[16];
9399   SDValue V2Mask[16];
9400   V1InUse = false;
9401   V2InUse = false;
9402
9403   int Size = Mask.size();
9404   int Scale = 16 / Size;
9405   for (int i = 0; i < 16; ++i) {
9406     if (Mask[i / Scale] == -1) {
9407       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9408     } else {
9409       const int ZeroMask = 0x80;
9410       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9411                                           : ZeroMask;
9412       int V2Idx = Mask[i / Scale] < Size
9413                       ? ZeroMask
9414                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9415       if (Zeroable[i / Scale])
9416         V1Idx = V2Idx = ZeroMask;
9417       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9418       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9419       V1InUse |= (ZeroMask != V1Idx);
9420       V2InUse |= (ZeroMask != V2Idx);
9421     }
9422   }
9423
9424   if (V1InUse)
9425     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9426                      DAG.getBitcast(MVT::v16i8, V1),
9427                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9428   if (V2InUse)
9429     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9430                      DAG.getBitcast(MVT::v16i8, V2),
9431                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9432
9433   // If we need shuffled inputs from both, blend the two.
9434   SDValue V;
9435   if (V1InUse && V2InUse)
9436     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9437   else
9438     V = V1InUse ? V1 : V2;
9439
9440   // Cast the result back to the correct type.
9441   return DAG.getBitcast(VT, V);
9442 }
9443
9444 /// \brief Generic lowering of 8-lane i16 shuffles.
9445 ///
9446 /// This handles both single-input shuffles and combined shuffle/blends with
9447 /// two inputs. The single input shuffles are immediately delegated to
9448 /// a dedicated lowering routine.
9449 ///
9450 /// The blends are lowered in one of three fundamental ways. If there are few
9451 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9452 /// of the input is significantly cheaper when lowered as an interleaving of
9453 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9454 /// halves of the inputs separately (making them have relatively few inputs)
9455 /// and then concatenate them.
9456 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9457                                        const X86Subtarget *Subtarget,
9458                                        SelectionDAG &DAG) {
9459   SDLoc DL(Op);
9460   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9461   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9462   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9463   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9464   ArrayRef<int> OrigMask = SVOp->getMask();
9465   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9466                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9467   MutableArrayRef<int> Mask(MaskStorage);
9468
9469   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9470
9471   // Whenever we can lower this as a zext, that instruction is strictly faster
9472   // than any alternative.
9473   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9474           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9475     return ZExt;
9476
9477   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9478   (void)isV1;
9479   auto isV2 = [](int M) { return M >= 8; };
9480
9481   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9482
9483   if (NumV2Inputs == 0) {
9484     // Check for being able to broadcast a single element.
9485     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9486                                                           Mask, Subtarget, DAG))
9487       return Broadcast;
9488
9489     // Try to use shift instructions.
9490     if (SDValue Shift =
9491             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9492       return Shift;
9493
9494     // Use dedicated unpack instructions for masks that match their pattern.
9495     if (SDValue V =
9496             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9497       return V;
9498
9499     // Try to use byte rotation instructions.
9500     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9501                                                         Mask, Subtarget, DAG))
9502       return Rotate;
9503
9504     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9505                                                      Subtarget, DAG);
9506   }
9507
9508   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9509          "All single-input shuffles should be canonicalized to be V1-input "
9510          "shuffles.");
9511
9512   // Try to use shift instructions.
9513   if (SDValue Shift =
9514           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9515     return Shift;
9516
9517   // See if we can use SSE4A Extraction / Insertion.
9518   if (Subtarget->hasSSE4A())
9519     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9520       return V;
9521
9522   // There are special ways we can lower some single-element blends.
9523   if (NumV2Inputs == 1)
9524     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9525                                                          Mask, Subtarget, DAG))
9526       return V;
9527
9528   // We have different paths for blend lowering, but they all must use the
9529   // *exact* same predicate.
9530   bool IsBlendSupported = Subtarget->hasSSE41();
9531   if (IsBlendSupported)
9532     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9533                                                   Subtarget, DAG))
9534       return Blend;
9535
9536   if (SDValue Masked =
9537           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9538     return Masked;
9539
9540   // Use dedicated unpack instructions for masks that match their pattern.
9541   if (SDValue V =
9542           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9543     return V;
9544
9545   // Try to use byte rotation instructions.
9546   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9547           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9548     return Rotate;
9549
9550   if (SDValue BitBlend =
9551           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9552     return BitBlend;
9553
9554   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9555                                                             V2, Mask, DAG))
9556     return Unpack;
9557
9558   // If we can't directly blend but can use PSHUFB, that will be better as it
9559   // can both shuffle and set up the inefficient blend.
9560   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9561     bool V1InUse, V2InUse;
9562     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9563                                       V1InUse, V2InUse);
9564   }
9565
9566   // We can always bit-blend if we have to so the fallback strategy is to
9567   // decompose into single-input permutes and blends.
9568   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9569                                                       Mask, DAG);
9570 }
9571
9572 /// \brief Check whether a compaction lowering can be done by dropping even
9573 /// elements and compute how many times even elements must be dropped.
9574 ///
9575 /// This handles shuffles which take every Nth element where N is a power of
9576 /// two. Example shuffle masks:
9577 ///
9578 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9579 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9580 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9581 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9582 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9583 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9584 ///
9585 /// Any of these lanes can of course be undef.
9586 ///
9587 /// This routine only supports N <= 3.
9588 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9589 /// for larger N.
9590 ///
9591 /// \returns N above, or the number of times even elements must be dropped if
9592 /// there is such a number. Otherwise returns zero.
9593 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9594   // Figure out whether we're looping over two inputs or just one.
9595   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9596
9597   // The modulus for the shuffle vector entries is based on whether this is
9598   // a single input or not.
9599   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9600   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9601          "We should only be called with masks with a power-of-2 size!");
9602
9603   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9604
9605   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9606   // and 2^3 simultaneously. This is because we may have ambiguity with
9607   // partially undef inputs.
9608   bool ViableForN[3] = {true, true, true};
9609
9610   for (int i = 0, e = Mask.size(); i < e; ++i) {
9611     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9612     // want.
9613     if (Mask[i] == -1)
9614       continue;
9615
9616     bool IsAnyViable = false;
9617     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9618       if (ViableForN[j]) {
9619         uint64_t N = j + 1;
9620
9621         // The shuffle mask must be equal to (i * 2^N) % M.
9622         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9623           IsAnyViable = true;
9624         else
9625           ViableForN[j] = false;
9626       }
9627     // Early exit if we exhaust the possible powers of two.
9628     if (!IsAnyViable)
9629       break;
9630   }
9631
9632   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9633     if (ViableForN[j])
9634       return j + 1;
9635
9636   // Return 0 as there is no viable power of two.
9637   return 0;
9638 }
9639
9640 /// \brief Generic lowering of v16i8 shuffles.
9641 ///
9642 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9643 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9644 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9645 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9646 /// back together.
9647 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9648                                        const X86Subtarget *Subtarget,
9649                                        SelectionDAG &DAG) {
9650   SDLoc DL(Op);
9651   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9652   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9653   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9654   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9655   ArrayRef<int> Mask = SVOp->getMask();
9656   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9657
9658   // Try to use shift instructions.
9659   if (SDValue Shift =
9660           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9661     return Shift;
9662
9663   // Try to use byte rotation instructions.
9664   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9665           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9666     return Rotate;
9667
9668   // Try to use a zext lowering.
9669   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9670           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9671     return ZExt;
9672
9673   // See if we can use SSE4A Extraction / Insertion.
9674   if (Subtarget->hasSSE4A())
9675     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9676       return V;
9677
9678   int NumV2Elements =
9679       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9680
9681   // For single-input shuffles, there are some nicer lowering tricks we can use.
9682   if (NumV2Elements == 0) {
9683     // Check for being able to broadcast a single element.
9684     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9685                                                           Mask, Subtarget, DAG))
9686       return Broadcast;
9687
9688     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9689     // Notably, this handles splat and partial-splat shuffles more efficiently.
9690     // However, it only makes sense if the pre-duplication shuffle simplifies
9691     // things significantly. Currently, this means we need to be able to
9692     // express the pre-duplication shuffle as an i16 shuffle.
9693     //
9694     // FIXME: We should check for other patterns which can be widened into an
9695     // i16 shuffle as well.
9696     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9697       for (int i = 0; i < 16; i += 2)
9698         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9699           return false;
9700
9701       return true;
9702     };
9703     auto tryToWidenViaDuplication = [&]() -> SDValue {
9704       if (!canWidenViaDuplication(Mask))
9705         return SDValue();
9706       SmallVector<int, 4> LoInputs;
9707       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9708                    [](int M) { return M >= 0 && M < 8; });
9709       std::sort(LoInputs.begin(), LoInputs.end());
9710       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9711                      LoInputs.end());
9712       SmallVector<int, 4> HiInputs;
9713       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9714                    [](int M) { return M >= 8; });
9715       std::sort(HiInputs.begin(), HiInputs.end());
9716       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9717                      HiInputs.end());
9718
9719       bool TargetLo = LoInputs.size() >= HiInputs.size();
9720       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9721       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9722
9723       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9724       SmallDenseMap<int, int, 8> LaneMap;
9725       for (int I : InPlaceInputs) {
9726         PreDupI16Shuffle[I/2] = I/2;
9727         LaneMap[I] = I;
9728       }
9729       int j = TargetLo ? 0 : 4, je = j + 4;
9730       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9731         // Check if j is already a shuffle of this input. This happens when
9732         // there are two adjacent bytes after we move the low one.
9733         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9734           // If we haven't yet mapped the input, search for a slot into which
9735           // we can map it.
9736           while (j < je && PreDupI16Shuffle[j] != -1)
9737             ++j;
9738
9739           if (j == je)
9740             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9741             return SDValue();
9742
9743           // Map this input with the i16 shuffle.
9744           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9745         }
9746
9747         // Update the lane map based on the mapping we ended up with.
9748         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9749       }
9750       V1 = DAG.getBitcast(
9751           MVT::v16i8,
9752           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9753                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9754
9755       // Unpack the bytes to form the i16s that will be shuffled into place.
9756       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9757                        MVT::v16i8, V1, V1);
9758
9759       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9760       for (int i = 0; i < 16; ++i)
9761         if (Mask[i] != -1) {
9762           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9763           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9764           if (PostDupI16Shuffle[i / 2] == -1)
9765             PostDupI16Shuffle[i / 2] = MappedMask;
9766           else
9767             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9768                    "Conflicting entrties in the original shuffle!");
9769         }
9770       return DAG.getBitcast(
9771           MVT::v16i8,
9772           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9773                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9774     };
9775     if (SDValue V = tryToWidenViaDuplication())
9776       return V;
9777   }
9778
9779   if (SDValue Masked =
9780           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9781     return Masked;
9782
9783   // Use dedicated unpack instructions for masks that match their pattern.
9784   if (SDValue V =
9785           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9786     return V;
9787
9788   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9789   // with PSHUFB. It is important to do this before we attempt to generate any
9790   // blends but after all of the single-input lowerings. If the single input
9791   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9792   // want to preserve that and we can DAG combine any longer sequences into
9793   // a PSHUFB in the end. But once we start blending from multiple inputs,
9794   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9795   // and there are *very* few patterns that would actually be faster than the
9796   // PSHUFB approach because of its ability to zero lanes.
9797   //
9798   // FIXME: The only exceptions to the above are blends which are exact
9799   // interleavings with direct instructions supporting them. We currently don't
9800   // handle those well here.
9801   if (Subtarget->hasSSSE3()) {
9802     bool V1InUse = false;
9803     bool V2InUse = false;
9804
9805     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9806                                                 DAG, V1InUse, V2InUse);
9807
9808     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9809     // do so. This avoids using them to handle blends-with-zero which is
9810     // important as a single pshufb is significantly faster for that.
9811     if (V1InUse && V2InUse) {
9812       if (Subtarget->hasSSE41())
9813         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9814                                                       Mask, Subtarget, DAG))
9815           return Blend;
9816
9817       // We can use an unpack to do the blending rather than an or in some
9818       // cases. Even though the or may be (very minorly) more efficient, we
9819       // preference this lowering because there are common cases where part of
9820       // the complexity of the shuffles goes away when we do the final blend as
9821       // an unpack.
9822       // FIXME: It might be worth trying to detect if the unpack-feeding
9823       // shuffles will both be pshufb, in which case we shouldn't bother with
9824       // this.
9825       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9826               DL, MVT::v16i8, V1, V2, Mask, DAG))
9827         return Unpack;
9828     }
9829
9830     return PSHUFB;
9831   }
9832
9833   // There are special ways we can lower some single-element blends.
9834   if (NumV2Elements == 1)
9835     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9836                                                          Mask, Subtarget, DAG))
9837       return V;
9838
9839   if (SDValue BitBlend =
9840           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9841     return BitBlend;
9842
9843   // Check whether a compaction lowering can be done. This handles shuffles
9844   // which take every Nth element for some even N. See the helper function for
9845   // details.
9846   //
9847   // We special case these as they can be particularly efficiently handled with
9848   // the PACKUSB instruction on x86 and they show up in common patterns of
9849   // rearranging bytes to truncate wide elements.
9850   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9851     // NumEvenDrops is the power of two stride of the elements. Another way of
9852     // thinking about it is that we need to drop the even elements this many
9853     // times to get the original input.
9854     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9855
9856     // First we need to zero all the dropped bytes.
9857     assert(NumEvenDrops <= 3 &&
9858            "No support for dropping even elements more than 3 times.");
9859     // We use the mask type to pick which bytes are preserved based on how many
9860     // elements are dropped.
9861     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9862     SDValue ByteClearMask = DAG.getBitcast(
9863         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9864     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9865     if (!IsSingleInput)
9866       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9867
9868     // Now pack things back together.
9869     V1 = DAG.getBitcast(MVT::v8i16, V1);
9870     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9871     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9872     for (int i = 1; i < NumEvenDrops; ++i) {
9873       Result = DAG.getBitcast(MVT::v8i16, Result);
9874       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9875     }
9876
9877     return Result;
9878   }
9879
9880   // Handle multi-input cases by blending single-input shuffles.
9881   if (NumV2Elements > 0)
9882     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9883                                                       Mask, DAG);
9884
9885   // The fallback path for single-input shuffles widens this into two v8i16
9886   // vectors with unpacks, shuffles those, and then pulls them back together
9887   // with a pack.
9888   SDValue V = V1;
9889
9890   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9891   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9892   for (int i = 0; i < 16; ++i)
9893     if (Mask[i] >= 0)
9894       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9895
9896   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9897
9898   SDValue VLoHalf, VHiHalf;
9899   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9900   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9901   // i16s.
9902   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9903                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9904       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9905                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9906     // Use a mask to drop the high bytes.
9907     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9908     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9909                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9910
9911     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9912     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9913
9914     // Squash the masks to point directly into VLoHalf.
9915     for (int &M : LoBlendMask)
9916       if (M >= 0)
9917         M /= 2;
9918     for (int &M : HiBlendMask)
9919       if (M >= 0)
9920         M /= 2;
9921   } else {
9922     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9923     // VHiHalf so that we can blend them as i16s.
9924     VLoHalf = DAG.getBitcast(
9925         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9926     VHiHalf = DAG.getBitcast(
9927         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9928   }
9929
9930   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9931   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9932
9933   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9934 }
9935
9936 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9937 ///
9938 /// This routine breaks down the specific type of 128-bit shuffle and
9939 /// dispatches to the lowering routines accordingly.
9940 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9941                                         MVT VT, const X86Subtarget *Subtarget,
9942                                         SelectionDAG &DAG) {
9943   switch (VT.SimpleTy) {
9944   case MVT::v2i64:
9945     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9946   case MVT::v2f64:
9947     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9948   case MVT::v4i32:
9949     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9950   case MVT::v4f32:
9951     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9952   case MVT::v8i16:
9953     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9954   case MVT::v16i8:
9955     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9956
9957   default:
9958     llvm_unreachable("Unimplemented!");
9959   }
9960 }
9961
9962 /// \brief Helper function to test whether a shuffle mask could be
9963 /// simplified by widening the elements being shuffled.
9964 ///
9965 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9966 /// leaves it in an unspecified state.
9967 ///
9968 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9969 /// shuffle masks. The latter have the special property of a '-2' representing
9970 /// a zero-ed lane of a vector.
9971 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9972                                     SmallVectorImpl<int> &WidenedMask) {
9973   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9974     // If both elements are undef, its trivial.
9975     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9976       WidenedMask.push_back(SM_SentinelUndef);
9977       continue;
9978     }
9979
9980     // Check for an undef mask and a mask value properly aligned to fit with
9981     // a pair of values. If we find such a case, use the non-undef mask's value.
9982     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9983       WidenedMask.push_back(Mask[i + 1] / 2);
9984       continue;
9985     }
9986     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9987       WidenedMask.push_back(Mask[i] / 2);
9988       continue;
9989     }
9990
9991     // When zeroing, we need to spread the zeroing across both lanes to widen.
9992     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9993       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9994           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9995         WidenedMask.push_back(SM_SentinelZero);
9996         continue;
9997       }
9998       return false;
9999     }
10000
10001     // Finally check if the two mask values are adjacent and aligned with
10002     // a pair.
10003     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
10004       WidenedMask.push_back(Mask[i] / 2);
10005       continue;
10006     }
10007
10008     // Otherwise we can't safely widen the elements used in this shuffle.
10009     return false;
10010   }
10011   assert(WidenedMask.size() == Mask.size() / 2 &&
10012          "Incorrect size of mask after widening the elements!");
10013
10014   return true;
10015 }
10016
10017 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
10018 ///
10019 /// This routine just extracts two subvectors, shuffles them independently, and
10020 /// then concatenates them back together. This should work effectively with all
10021 /// AVX vector shuffle types.
10022 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10023                                           SDValue V2, ArrayRef<int> Mask,
10024                                           SelectionDAG &DAG) {
10025   assert(VT.getSizeInBits() >= 256 &&
10026          "Only for 256-bit or wider vector shuffles!");
10027   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
10028   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
10029
10030   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
10031   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
10032
10033   int NumElements = VT.getVectorNumElements();
10034   int SplitNumElements = NumElements / 2;
10035   MVT ScalarVT = VT.getVectorElementType();
10036   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
10037
10038   // Rather than splitting build-vectors, just build two narrower build
10039   // vectors. This helps shuffling with splats and zeros.
10040   auto SplitVector = [&](SDValue V) {
10041     while (V.getOpcode() == ISD::BITCAST)
10042       V = V->getOperand(0);
10043
10044     MVT OrigVT = V.getSimpleValueType();
10045     int OrigNumElements = OrigVT.getVectorNumElements();
10046     int OrigSplitNumElements = OrigNumElements / 2;
10047     MVT OrigScalarVT = OrigVT.getVectorElementType();
10048     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
10049
10050     SDValue LoV, HiV;
10051
10052     auto *BV = dyn_cast<BuildVectorSDNode>(V);
10053     if (!BV) {
10054       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10055                         DAG.getIntPtrConstant(0, DL));
10056       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10057                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
10058     } else {
10059
10060       SmallVector<SDValue, 16> LoOps, HiOps;
10061       for (int i = 0; i < OrigSplitNumElements; ++i) {
10062         LoOps.push_back(BV->getOperand(i));
10063         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10064       }
10065       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10066       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10067     }
10068     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10069                           DAG.getBitcast(SplitVT, HiV));
10070   };
10071
10072   SDValue LoV1, HiV1, LoV2, HiV2;
10073   std::tie(LoV1, HiV1) = SplitVector(V1);
10074   std::tie(LoV2, HiV2) = SplitVector(V2);
10075
10076   // Now create two 4-way blends of these half-width vectors.
10077   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10078     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10079     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10080     for (int i = 0; i < SplitNumElements; ++i) {
10081       int M = HalfMask[i];
10082       if (M >= NumElements) {
10083         if (M >= NumElements + SplitNumElements)
10084           UseHiV2 = true;
10085         else
10086           UseLoV2 = true;
10087         V2BlendMask.push_back(M - NumElements);
10088         V1BlendMask.push_back(-1);
10089         BlendMask.push_back(SplitNumElements + i);
10090       } else if (M >= 0) {
10091         if (M >= SplitNumElements)
10092           UseHiV1 = true;
10093         else
10094           UseLoV1 = true;
10095         V2BlendMask.push_back(-1);
10096         V1BlendMask.push_back(M);
10097         BlendMask.push_back(i);
10098       } else {
10099         V2BlendMask.push_back(-1);
10100         V1BlendMask.push_back(-1);
10101         BlendMask.push_back(-1);
10102       }
10103     }
10104
10105     // Because the lowering happens after all combining takes place, we need to
10106     // manually combine these blend masks as much as possible so that we create
10107     // a minimal number of high-level vector shuffle nodes.
10108
10109     // First try just blending the halves of V1 or V2.
10110     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10111       return DAG.getUNDEF(SplitVT);
10112     if (!UseLoV2 && !UseHiV2)
10113       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10114     if (!UseLoV1 && !UseHiV1)
10115       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10116
10117     SDValue V1Blend, V2Blend;
10118     if (UseLoV1 && UseHiV1) {
10119       V1Blend =
10120         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10121     } else {
10122       // We only use half of V1 so map the usage down into the final blend mask.
10123       V1Blend = UseLoV1 ? LoV1 : HiV1;
10124       for (int i = 0; i < SplitNumElements; ++i)
10125         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10126           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10127     }
10128     if (UseLoV2 && UseHiV2) {
10129       V2Blend =
10130         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10131     } else {
10132       // We only use half of V2 so map the usage down into the final blend mask.
10133       V2Blend = UseLoV2 ? LoV2 : HiV2;
10134       for (int i = 0; i < SplitNumElements; ++i)
10135         if (BlendMask[i] >= SplitNumElements)
10136           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10137     }
10138     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10139   };
10140   SDValue Lo = HalfBlend(LoMask);
10141   SDValue Hi = HalfBlend(HiMask);
10142   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10143 }
10144
10145 /// \brief Either split a vector in halves or decompose the shuffles and the
10146 /// blend.
10147 ///
10148 /// This is provided as a good fallback for many lowerings of non-single-input
10149 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10150 /// between splitting the shuffle into 128-bit components and stitching those
10151 /// back together vs. extracting the single-input shuffles and blending those
10152 /// results.
10153 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10154                                                 SDValue V2, ArrayRef<int> Mask,
10155                                                 SelectionDAG &DAG) {
10156   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10157                                             "lower single-input shuffles as it "
10158                                             "could then recurse on itself.");
10159   int Size = Mask.size();
10160
10161   // If this can be modeled as a broadcast of two elements followed by a blend,
10162   // prefer that lowering. This is especially important because broadcasts can
10163   // often fold with memory operands.
10164   auto DoBothBroadcast = [&] {
10165     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10166     for (int M : Mask)
10167       if (M >= Size) {
10168         if (V2BroadcastIdx == -1)
10169           V2BroadcastIdx = M - Size;
10170         else if (M - Size != V2BroadcastIdx)
10171           return false;
10172       } else if (M >= 0) {
10173         if (V1BroadcastIdx == -1)
10174           V1BroadcastIdx = M;
10175         else if (M != V1BroadcastIdx)
10176           return false;
10177       }
10178     return true;
10179   };
10180   if (DoBothBroadcast())
10181     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10182                                                       DAG);
10183
10184   // If the inputs all stem from a single 128-bit lane of each input, then we
10185   // split them rather than blending because the split will decompose to
10186   // unusually few instructions.
10187   int LaneCount = VT.getSizeInBits() / 128;
10188   int LaneSize = Size / LaneCount;
10189   SmallBitVector LaneInputs[2];
10190   LaneInputs[0].resize(LaneCount, false);
10191   LaneInputs[1].resize(LaneCount, false);
10192   for (int i = 0; i < Size; ++i)
10193     if (Mask[i] >= 0)
10194       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10195   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10196     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10197
10198   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10199   // that the decomposed single-input shuffles don't end up here.
10200   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10201 }
10202
10203 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10204 /// a permutation and blend of those lanes.
10205 ///
10206 /// This essentially blends the out-of-lane inputs to each lane into the lane
10207 /// from a permuted copy of the vector. This lowering strategy results in four
10208 /// instructions in the worst case for a single-input cross lane shuffle which
10209 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10210 /// of. Special cases for each particular shuffle pattern should be handled
10211 /// prior to trying this lowering.
10212 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10213                                                        SDValue V1, SDValue V2,
10214                                                        ArrayRef<int> Mask,
10215                                                        SelectionDAG &DAG) {
10216   // FIXME: This should probably be generalized for 512-bit vectors as well.
10217   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10218   int LaneSize = Mask.size() / 2;
10219
10220   // If there are only inputs from one 128-bit lane, splitting will in fact be
10221   // less expensive. The flags track whether the given lane contains an element
10222   // that crosses to another lane.
10223   bool LaneCrossing[2] = {false, false};
10224   for (int i = 0, Size = Mask.size(); i < Size; ++i)
10225     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10226       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10227   if (!LaneCrossing[0] || !LaneCrossing[1])
10228     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10229
10230   if (isSingleInputShuffleMask(Mask)) {
10231     SmallVector<int, 32> FlippedBlendMask;
10232     for (int i = 0, Size = Mask.size(); i < Size; ++i)
10233       FlippedBlendMask.push_back(
10234           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10235                                   ? Mask[i]
10236                                   : Mask[i] % LaneSize +
10237                                         (i / LaneSize) * LaneSize + Size));
10238
10239     // Flip the vector, and blend the results which should now be in-lane. The
10240     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10241     // 5 for the high source. The value 3 selects the high half of source 2 and
10242     // the value 2 selects the low half of source 2. We only use source 2 to
10243     // allow folding it into a memory operand.
10244     unsigned PERMMask = 3 | 2 << 4;
10245     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10246                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10247     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10248   }
10249
10250   // This now reduces to two single-input shuffles of V1 and V2 which at worst
10251   // will be handled by the above logic and a blend of the results, much like
10252   // other patterns in AVX.
10253   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10254 }
10255
10256 /// \brief Handle lowering 2-lane 128-bit shuffles.
10257 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10258                                         SDValue V2, ArrayRef<int> Mask,
10259                                         const X86Subtarget *Subtarget,
10260                                         SelectionDAG &DAG) {
10261   // TODO: If minimizing size and one of the inputs is a zero vector and the
10262   // the zero vector has only one use, we could use a VPERM2X128 to save the
10263   // instruction bytes needed to explicitly generate the zero vector.
10264
10265   // Blends are faster and handle all the non-lane-crossing cases.
10266   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10267                                                 Subtarget, DAG))
10268     return Blend;
10269
10270   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10271   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10272
10273   // If either input operand is a zero vector, use VPERM2X128 because its mask
10274   // allows us to replace the zero input with an implicit zero.
10275   if (!IsV1Zero && !IsV2Zero) {
10276     // Check for patterns which can be matched with a single insert of a 128-bit
10277     // subvector.
10278     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10279     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10280       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10281                                    VT.getVectorNumElements() / 2);
10282       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10283                                 DAG.getIntPtrConstant(0, DL));
10284       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10285                                 OnlyUsesV1 ? V1 : V2,
10286                                 DAG.getIntPtrConstant(0, DL));
10287       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10288     }
10289   }
10290
10291   // Otherwise form a 128-bit permutation. After accounting for undefs,
10292   // convert the 64-bit shuffle mask selection values into 128-bit
10293   // selection bits by dividing the indexes by 2 and shifting into positions
10294   // defined by a vperm2*128 instruction's immediate control byte.
10295
10296   // The immediate permute control byte looks like this:
10297   //    [1:0] - select 128 bits from sources for low half of destination
10298   //    [2]   - ignore
10299   //    [3]   - zero low half of destination
10300   //    [5:4] - select 128 bits from sources for high half of destination
10301   //    [6]   - ignore
10302   //    [7]   - zero high half of destination
10303
10304   int MaskLO = Mask[0];
10305   if (MaskLO == SM_SentinelUndef)
10306     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10307
10308   int MaskHI = Mask[2];
10309   if (MaskHI == SM_SentinelUndef)
10310     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10311
10312   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10313
10314   // If either input is a zero vector, replace it with an undef input.
10315   // Shuffle mask values <  4 are selecting elements of V1.
10316   // Shuffle mask values >= 4 are selecting elements of V2.
10317   // Adjust each half of the permute mask by clearing the half that was
10318   // selecting the zero vector and setting the zero mask bit.
10319   if (IsV1Zero) {
10320     V1 = DAG.getUNDEF(VT);
10321     if (MaskLO < 4)
10322       PermMask = (PermMask & 0xf0) | 0x08;
10323     if (MaskHI < 4)
10324       PermMask = (PermMask & 0x0f) | 0x80;
10325   }
10326   if (IsV2Zero) {
10327     V2 = DAG.getUNDEF(VT);
10328     if (MaskLO >= 4)
10329       PermMask = (PermMask & 0xf0) | 0x08;
10330     if (MaskHI >= 4)
10331       PermMask = (PermMask & 0x0f) | 0x80;
10332   }
10333
10334   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10335                      DAG.getConstant(PermMask, DL, MVT::i8));
10336 }
10337
10338 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10339 /// shuffling each lane.
10340 ///
10341 /// This will only succeed when the result of fixing the 128-bit lanes results
10342 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10343 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10344 /// the lane crosses early and then use simpler shuffles within each lane.
10345 ///
10346 /// FIXME: It might be worthwhile at some point to support this without
10347 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10348 /// in x86 only floating point has interesting non-repeating shuffles, and even
10349 /// those are still *marginally* more expensive.
10350 static SDValue lowerVectorShuffleByMerging128BitLanes(
10351     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10352     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10353   assert(!isSingleInputShuffleMask(Mask) &&
10354          "This is only useful with multiple inputs.");
10355
10356   int Size = Mask.size();
10357   int LaneSize = 128 / VT.getScalarSizeInBits();
10358   int NumLanes = Size / LaneSize;
10359   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10360
10361   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10362   // check whether the in-128-bit lane shuffles share a repeating pattern.
10363   SmallVector<int, 4> Lanes;
10364   Lanes.resize(NumLanes, -1);
10365   SmallVector<int, 4> InLaneMask;
10366   InLaneMask.resize(LaneSize, -1);
10367   for (int i = 0; i < Size; ++i) {
10368     if (Mask[i] < 0)
10369       continue;
10370
10371     int j = i / LaneSize;
10372
10373     if (Lanes[j] < 0) {
10374       // First entry we've seen for this lane.
10375       Lanes[j] = Mask[i] / LaneSize;
10376     } else if (Lanes[j] != Mask[i] / LaneSize) {
10377       // This doesn't match the lane selected previously!
10378       return SDValue();
10379     }
10380
10381     // Check that within each lane we have a consistent shuffle mask.
10382     int k = i % LaneSize;
10383     if (InLaneMask[k] < 0) {
10384       InLaneMask[k] = Mask[i] % LaneSize;
10385     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10386       // This doesn't fit a repeating in-lane mask.
10387       return SDValue();
10388     }
10389   }
10390
10391   // First shuffle the lanes into place.
10392   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10393                                 VT.getSizeInBits() / 64);
10394   SmallVector<int, 8> LaneMask;
10395   LaneMask.resize(NumLanes * 2, -1);
10396   for (int i = 0; i < NumLanes; ++i)
10397     if (Lanes[i] >= 0) {
10398       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10399       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10400     }
10401
10402   V1 = DAG.getBitcast(LaneVT, V1);
10403   V2 = DAG.getBitcast(LaneVT, V2);
10404   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10405
10406   // Cast it back to the type we actually want.
10407   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10408
10409   // Now do a simple shuffle that isn't lane crossing.
10410   SmallVector<int, 8> NewMask;
10411   NewMask.resize(Size, -1);
10412   for (int i = 0; i < Size; ++i)
10413     if (Mask[i] >= 0)
10414       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10415   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10416          "Must not introduce lane crosses at this point!");
10417
10418   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10419 }
10420
10421 /// Lower shuffles where an entire half of a 256-bit vector is UNDEF.
10422 /// This allows for fast cases such as subvector extraction/insertion
10423 /// or shuffling smaller vector types which can lower more efficiently.
10424 static SDValue lowerVectorShuffleWithUndefHalf(SDLoc DL, MVT VT, SDValue V1,
10425                                                SDValue V2, ArrayRef<int> Mask,
10426                                                const X86Subtarget *Subtarget,
10427                                                SelectionDAG &DAG) {
10428   assert(VT.getSizeInBits() == 256 && "Expected 256-bit vector");
10429
10430   unsigned NumElts = VT.getVectorNumElements();
10431   unsigned HalfNumElts = NumElts / 2;
10432   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
10433
10434   bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
10435   bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
10436   if (!UndefLower && !UndefUpper)
10437     return SDValue();
10438
10439   // Upper half is undef and lower half is whole upper subvector.
10440   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
10441   if (UndefUpper &&
10442       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
10443     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10444                              DAG.getIntPtrConstant(HalfNumElts, DL));
10445     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10446                        DAG.getIntPtrConstant(0, DL));
10447   }
10448
10449   // Lower half is undef and upper half is whole lower subvector.
10450   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
10451   if (UndefLower &&
10452       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
10453     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10454                              DAG.getIntPtrConstant(0, DL));
10455     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10456                        DAG.getIntPtrConstant(HalfNumElts, DL));
10457   }
10458
10459   // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
10460   if (UndefLower && Subtarget->hasAVX2() &&
10461       (VT == MVT::v4f64 || VT == MVT::v4i64))
10462     return SDValue();
10463
10464   // If the shuffle only uses the lower halves of the input operands,
10465   // then extract them and perform the 'half' shuffle at half width.
10466   // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
10467   int HalfIdx1 = -1, HalfIdx2 = -1;
10468   SmallVector<int, 8> HalfMask;
10469   unsigned Offset = UndefLower ? HalfNumElts : 0;
10470   for (unsigned i = 0; i != HalfNumElts; ++i) {
10471     int M = Mask[i + Offset];
10472     if (M < 0) {
10473       HalfMask.push_back(M);
10474       continue;
10475     }
10476
10477     // Determine which of the 4 half vectors this element is from.
10478     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
10479     int HalfIdx = M / HalfNumElts;
10480
10481     // Only shuffle using the lower halves of the inputs.
10482     // TODO: Investigate usefulness of shuffling with upper halves.
10483     if (HalfIdx != 0 && HalfIdx != 2)
10484       return SDValue();
10485
10486     // Determine the element index into its half vector source.
10487     int HalfElt = M % HalfNumElts;
10488
10489     // We can shuffle with up to 2 half vectors, set the new 'half'
10490     // shuffle mask accordingly.
10491     if (-1 == HalfIdx1 || HalfIdx1 == HalfIdx) {
10492       HalfMask.push_back(HalfElt);
10493       HalfIdx1 = HalfIdx;
10494       continue;
10495     }
10496     if (-1 == HalfIdx2 || HalfIdx2 == HalfIdx) {
10497       HalfMask.push_back(HalfElt + HalfNumElts);
10498       HalfIdx2 = HalfIdx;
10499       continue;
10500     }
10501
10502     // Too many half vectors referenced.
10503     return SDValue();
10504   }
10505   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
10506
10507   auto GetHalfVector = [&](int HalfIdx) {
10508     if (HalfIdx < 0)
10509       return DAG.getUNDEF(HalfVT);
10510     SDValue V = (HalfIdx < 2 ? V1 : V2);
10511     HalfIdx = (HalfIdx % 2) * HalfNumElts;
10512     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
10513                        DAG.getIntPtrConstant(HalfIdx, DL));
10514   };
10515
10516   SDValue Half1 = GetHalfVector(HalfIdx1);
10517   SDValue Half2 = GetHalfVector(HalfIdx2);
10518   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
10519   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
10520                      DAG.getIntPtrConstant(Offset, DL));
10521 }
10522
10523 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10524 /// given mask.
10525 ///
10526 /// This returns true if the elements from a particular input are already in the
10527 /// slot required by the given mask and require no permutation.
10528 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10529   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10530   int Size = Mask.size();
10531   for (int i = 0; i < Size; ++i)
10532     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10533       return false;
10534
10535   return true;
10536 }
10537
10538 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10539                                             ArrayRef<int> Mask, SDValue V1,
10540                                             SDValue V2, SelectionDAG &DAG) {
10541
10542   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10543   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10544   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10545   int NumElts = VT.getVectorNumElements();
10546   bool ShufpdMask = true;
10547   bool CommutableMask = true;
10548   unsigned Immediate = 0;
10549   for (int i = 0; i < NumElts; ++i) {
10550     if (Mask[i] < 0)
10551       continue;
10552     int Val = (i & 6) + NumElts * (i & 1);
10553     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10554     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10555       ShufpdMask = false;
10556     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10557       CommutableMask = false;
10558     Immediate |= (Mask[i] % 2) << i;
10559   }
10560   if (ShufpdMask)
10561     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10562                        DAG.getConstant(Immediate, DL, MVT::i8));
10563   if (CommutableMask)
10564     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10565                        DAG.getConstant(Immediate, DL, MVT::i8));
10566   return SDValue();
10567 }
10568
10569 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10570 ///
10571 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10572 /// isn't available.
10573 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10574                                        const X86Subtarget *Subtarget,
10575                                        SelectionDAG &DAG) {
10576   SDLoc DL(Op);
10577   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10578   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10579   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10580   ArrayRef<int> Mask = SVOp->getMask();
10581   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10582
10583   SmallVector<int, 4> WidenedMask;
10584   if (canWidenShuffleElements(Mask, WidenedMask))
10585     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10586                                     DAG);
10587
10588   if (isSingleInputShuffleMask(Mask)) {
10589     // Check for being able to broadcast a single element.
10590     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10591                                                           Mask, Subtarget, DAG))
10592       return Broadcast;
10593
10594     // Use low duplicate instructions for masks that match their pattern.
10595     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10596       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10597
10598     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10599       // Non-half-crossing single input shuffles can be lowerid with an
10600       // interleaved permutation.
10601       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10602                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10603       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10604                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10605     }
10606
10607     // With AVX2 we have direct support for this permutation.
10608     if (Subtarget->hasAVX2())
10609       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10610                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10611
10612     // Otherwise, fall back.
10613     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10614                                                    DAG);
10615   }
10616
10617   // Use dedicated unpack instructions for masks that match their pattern.
10618   if (SDValue V =
10619           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10620     return V;
10621
10622   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10623                                                 Subtarget, DAG))
10624     return Blend;
10625
10626   // Check if the blend happens to exactly fit that of SHUFPD.
10627   if (SDValue Op =
10628       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10629     return Op;
10630
10631   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10632   // shuffle. However, if we have AVX2 and either inputs are already in place,
10633   // we will be able to shuffle even across lanes the other input in a single
10634   // instruction so skip this pattern.
10635   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10636                                  isShuffleMaskInputInPlace(1, Mask))))
10637     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10638             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10639       return Result;
10640
10641   // If we have AVX2 then we always want to lower with a blend because an v4 we
10642   // can fully permute the elements.
10643   if (Subtarget->hasAVX2())
10644     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10645                                                       Mask, DAG);
10646
10647   // Otherwise fall back on generic lowering.
10648   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10649 }
10650
10651 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10652 ///
10653 /// This routine is only called when we have AVX2 and thus a reasonable
10654 /// instruction set for v4i64 shuffling..
10655 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10656                                        const X86Subtarget *Subtarget,
10657                                        SelectionDAG &DAG) {
10658   SDLoc DL(Op);
10659   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10660   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10661   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10662   ArrayRef<int> Mask = SVOp->getMask();
10663   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10664   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10665
10666   SmallVector<int, 4> WidenedMask;
10667   if (canWidenShuffleElements(Mask, WidenedMask))
10668     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10669                                     DAG);
10670
10671   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10672                                                 Subtarget, DAG))
10673     return Blend;
10674
10675   // Check for being able to broadcast a single element.
10676   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10677                                                         Mask, Subtarget, DAG))
10678     return Broadcast;
10679
10680   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10681   // use lower latency instructions that will operate on both 128-bit lanes.
10682   SmallVector<int, 2> RepeatedMask;
10683   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10684     if (isSingleInputShuffleMask(Mask)) {
10685       int PSHUFDMask[] = {-1, -1, -1, -1};
10686       for (int i = 0; i < 2; ++i)
10687         if (RepeatedMask[i] >= 0) {
10688           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10689           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10690         }
10691       return DAG.getBitcast(
10692           MVT::v4i64,
10693           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10694                       DAG.getBitcast(MVT::v8i32, V1),
10695                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10696     }
10697   }
10698
10699   // AVX2 provides a direct instruction for permuting a single input across
10700   // lanes.
10701   if (isSingleInputShuffleMask(Mask))
10702     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10703                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10704
10705   // Try to use shift instructions.
10706   if (SDValue Shift =
10707           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10708     return Shift;
10709
10710   // Use dedicated unpack instructions for masks that match their pattern.
10711   if (SDValue V =
10712           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10713     return V;
10714
10715   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10716   // shuffle. However, if we have AVX2 and either inputs are already in place,
10717   // we will be able to shuffle even across lanes the other input in a single
10718   // instruction so skip this pattern.
10719   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10720                                  isShuffleMaskInputInPlace(1, Mask))))
10721     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10722             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10723       return Result;
10724
10725   // Otherwise fall back on generic blend lowering.
10726   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10727                                                     Mask, DAG);
10728 }
10729
10730 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10731 ///
10732 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10733 /// isn't available.
10734 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10735                                        const X86Subtarget *Subtarget,
10736                                        SelectionDAG &DAG) {
10737   SDLoc DL(Op);
10738   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10739   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10740   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10741   ArrayRef<int> Mask = SVOp->getMask();
10742   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10743
10744   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10745                                                 Subtarget, DAG))
10746     return Blend;
10747
10748   // Check for being able to broadcast a single element.
10749   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10750                                                         Mask, Subtarget, DAG))
10751     return Broadcast;
10752
10753   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10754   // options to efficiently lower the shuffle.
10755   SmallVector<int, 4> RepeatedMask;
10756   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10757     assert(RepeatedMask.size() == 4 &&
10758            "Repeated masks must be half the mask width!");
10759
10760     // Use even/odd duplicate instructions for masks that match their pattern.
10761     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10762       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10763     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10764       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10765
10766     if (isSingleInputShuffleMask(Mask))
10767       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10768                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10769
10770     // Use dedicated unpack instructions for masks that match their pattern.
10771     if (SDValue V =
10772             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10773       return V;
10774
10775     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10776     // have already handled any direct blends. We also need to squash the
10777     // repeated mask into a simulated v4f32 mask.
10778     for (int i = 0; i < 4; ++i)
10779       if (RepeatedMask[i] >= 8)
10780         RepeatedMask[i] -= 4;
10781     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10782   }
10783
10784   // If we have a single input shuffle with different shuffle patterns in the
10785   // two 128-bit lanes use the variable mask to VPERMILPS.
10786   if (isSingleInputShuffleMask(Mask)) {
10787     SDValue VPermMask[8];
10788     for (int i = 0; i < 8; ++i)
10789       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10790                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10791     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10792       return DAG.getNode(
10793           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10794           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10795
10796     if (Subtarget->hasAVX2())
10797       return DAG.getNode(
10798           X86ISD::VPERMV, DL, MVT::v8f32,
10799           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10800
10801     // Otherwise, fall back.
10802     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10803                                                    DAG);
10804   }
10805
10806   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10807   // shuffle.
10808   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10809           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10810     return Result;
10811
10812   // If we have AVX2 then we always want to lower with a blend because at v8 we
10813   // can fully permute the elements.
10814   if (Subtarget->hasAVX2())
10815     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10816                                                       Mask, DAG);
10817
10818   // Otherwise fall back on generic lowering.
10819   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10820 }
10821
10822 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10823 ///
10824 /// This routine is only called when we have AVX2 and thus a reasonable
10825 /// instruction set for v8i32 shuffling..
10826 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10827                                        const X86Subtarget *Subtarget,
10828                                        SelectionDAG &DAG) {
10829   SDLoc DL(Op);
10830   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10831   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10832   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10833   ArrayRef<int> Mask = SVOp->getMask();
10834   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10835   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10836
10837   // Whenever we can lower this as a zext, that instruction is strictly faster
10838   // than any alternative. It also allows us to fold memory operands into the
10839   // shuffle in many cases.
10840   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10841                                                          Mask, Subtarget, DAG))
10842     return ZExt;
10843
10844   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10845                                                 Subtarget, DAG))
10846     return Blend;
10847
10848   // Check for being able to broadcast a single element.
10849   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10850                                                         Mask, Subtarget, DAG))
10851     return Broadcast;
10852
10853   // If the shuffle mask is repeated in each 128-bit lane we can use more
10854   // efficient instructions that mirror the shuffles across the two 128-bit
10855   // lanes.
10856   SmallVector<int, 4> RepeatedMask;
10857   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10858     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10859     if (isSingleInputShuffleMask(Mask))
10860       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10861                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10862
10863     // Use dedicated unpack instructions for masks that match their pattern.
10864     if (SDValue V =
10865             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10866       return V;
10867   }
10868
10869   // Try to use shift instructions.
10870   if (SDValue Shift =
10871           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10872     return Shift;
10873
10874   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10875           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10876     return Rotate;
10877
10878   // If the shuffle patterns aren't repeated but it is a single input, directly
10879   // generate a cross-lane VPERMD instruction.
10880   if (isSingleInputShuffleMask(Mask)) {
10881     SDValue VPermMask[8];
10882     for (int i = 0; i < 8; ++i)
10883       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10884                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10885     return DAG.getNode(
10886         X86ISD::VPERMV, DL, MVT::v8i32,
10887         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10888   }
10889
10890   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10891   // shuffle.
10892   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10893           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10894     return Result;
10895
10896   // Otherwise fall back on generic blend lowering.
10897   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10898                                                     Mask, DAG);
10899 }
10900
10901 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10902 ///
10903 /// This routine is only called when we have AVX2 and thus a reasonable
10904 /// instruction set for v16i16 shuffling..
10905 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10906                                         const X86Subtarget *Subtarget,
10907                                         SelectionDAG &DAG) {
10908   SDLoc DL(Op);
10909   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10910   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10911   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10912   ArrayRef<int> Mask = SVOp->getMask();
10913   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10914   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10915
10916   // Whenever we can lower this as a zext, that instruction is strictly faster
10917   // than any alternative. It also allows us to fold memory operands into the
10918   // shuffle in many cases.
10919   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10920                                                          Mask, Subtarget, DAG))
10921     return ZExt;
10922
10923   // Check for being able to broadcast a single element.
10924   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10925                                                         Mask, Subtarget, DAG))
10926     return Broadcast;
10927
10928   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10929                                                 Subtarget, DAG))
10930     return Blend;
10931
10932   // Use dedicated unpack instructions for masks that match their pattern.
10933   if (SDValue V =
10934           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10935     return V;
10936
10937   // Try to use shift instructions.
10938   if (SDValue Shift =
10939           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10940     return Shift;
10941
10942   // Try to use byte rotation instructions.
10943   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10944           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10945     return Rotate;
10946
10947   if (isSingleInputShuffleMask(Mask)) {
10948     // There are no generalized cross-lane shuffle operations available on i16
10949     // element types.
10950     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10951       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10952                                                      Mask, DAG);
10953
10954     SmallVector<int, 8> RepeatedMask;
10955     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10956       // As this is a single-input shuffle, the repeated mask should be
10957       // a strictly valid v8i16 mask that we can pass through to the v8i16
10958       // lowering to handle even the v16 case.
10959       return lowerV8I16GeneralSingleInputVectorShuffle(
10960           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10961     }
10962
10963     SDValue PSHUFBMask[32];
10964     for (int i = 0; i < 16; ++i) {
10965       if (Mask[i] == -1) {
10966         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10967         continue;
10968       }
10969
10970       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10971       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10972       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10973       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10974     }
10975     return DAG.getBitcast(MVT::v16i16,
10976                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10977                                       DAG.getBitcast(MVT::v32i8, V1),
10978                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10979                                                   MVT::v32i8, PSHUFBMask)));
10980   }
10981
10982   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10983   // shuffle.
10984   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10985           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10986     return Result;
10987
10988   // Otherwise fall back on generic lowering.
10989   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10990 }
10991
10992 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10993 ///
10994 /// This routine is only called when we have AVX2 and thus a reasonable
10995 /// instruction set for v32i8 shuffling..
10996 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10997                                        const X86Subtarget *Subtarget,
10998                                        SelectionDAG &DAG) {
10999   SDLoc DL(Op);
11000   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
11001   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
11002   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11003   ArrayRef<int> Mask = SVOp->getMask();
11004   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11005   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
11006
11007   // Whenever we can lower this as a zext, that instruction is strictly faster
11008   // than any alternative. It also allows us to fold memory operands into the
11009   // shuffle in many cases.
11010   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
11011                                                          Mask, Subtarget, DAG))
11012     return ZExt;
11013
11014   // Check for being able to broadcast a single element.
11015   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
11016                                                         Mask, Subtarget, DAG))
11017     return Broadcast;
11018
11019   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
11020                                                 Subtarget, DAG))
11021     return Blend;
11022
11023   // Use dedicated unpack instructions for masks that match their pattern.
11024   if (SDValue V =
11025           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
11026     return V;
11027
11028   // Try to use shift instructions.
11029   if (SDValue Shift =
11030           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
11031     return Shift;
11032
11033   // Try to use byte rotation instructions.
11034   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
11035           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11036     return Rotate;
11037
11038   if (isSingleInputShuffleMask(Mask)) {
11039     // There are no generalized cross-lane shuffle operations available on i8
11040     // element types.
11041     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
11042       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
11043                                                      Mask, DAG);
11044
11045     SDValue PSHUFBMask[32];
11046     for (int i = 0; i < 32; ++i)
11047       PSHUFBMask[i] =
11048           Mask[i] < 0
11049               ? DAG.getUNDEF(MVT::i8)
11050               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
11051                                 MVT::i8);
11052
11053     return DAG.getNode(
11054         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
11055         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
11056   }
11057
11058   // Try to simplify this by merging 128-bit lanes to enable a lane-based
11059   // shuffle.
11060   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11061           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11062     return Result;
11063
11064   // Otherwise fall back on generic lowering.
11065   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11066 }
11067
11068 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11069 ///
11070 /// This routine either breaks down the specific type of a 256-bit x86 vector
11071 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11072 /// together based on the available instructions.
11073 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11074                                         MVT VT, const X86Subtarget *Subtarget,
11075                                         SelectionDAG &DAG) {
11076   SDLoc DL(Op);
11077   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11078   ArrayRef<int> Mask = SVOp->getMask();
11079
11080   // If we have a single input to the zero element, insert that into V1 if we
11081   // can do so cheaply.
11082   int NumElts = VT.getVectorNumElements();
11083   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
11084     return M >= NumElts;
11085   });
11086
11087   if (NumV2Elements == 1 && Mask[0] >= NumElts)
11088     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
11089                               DL, VT, V1, V2, Mask, Subtarget, DAG))
11090       return Insertion;
11091
11092   // Handle special cases where the lower or upper half is UNDEF.
11093   if (SDValue V =
11094           lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
11095     return V;
11096
11097   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
11098   // can check for those subtargets here and avoid much of the subtarget
11099   // querying in the per-vector-type lowering routines. With AVX1 we have
11100   // essentially *zero* ability to manipulate a 256-bit vector with integer
11101   // types. Since we'll use floating point types there eventually, just
11102   // immediately cast everything to a float and operate entirely in that domain.
11103   if (VT.isInteger() && !Subtarget->hasAVX2()) {
11104     int ElementBits = VT.getScalarSizeInBits();
11105     if (ElementBits < 32)
11106       // No floating point type available, decompose into 128-bit vectors.
11107       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11108
11109     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11110                                 VT.getVectorNumElements());
11111     V1 = DAG.getBitcast(FpVT, V1);
11112     V2 = DAG.getBitcast(FpVT, V2);
11113     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11114   }
11115
11116   switch (VT.SimpleTy) {
11117   case MVT::v4f64:
11118     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11119   case MVT::v4i64:
11120     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11121   case MVT::v8f32:
11122     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11123   case MVT::v8i32:
11124     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11125   case MVT::v16i16:
11126     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11127   case MVT::v32i8:
11128     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11129
11130   default:
11131     llvm_unreachable("Not a valid 256-bit x86 vector type!");
11132   }
11133 }
11134
11135 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
11136 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
11137                                         ArrayRef<int> Mask,
11138                                         SDValue V1, SDValue V2,
11139                                         SelectionDAG &DAG) {
11140   assert(VT.getScalarSizeInBits() == 64 &&
11141          "Unexpected element type size for 128bit shuffle.");
11142
11143   // To handle 256 bit vector requires VLX and most probably
11144   // function lowerV2X128VectorShuffle() is better solution.
11145   assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
11146
11147   SmallVector<int, 4> WidenedMask;
11148   if (!canWidenShuffleElements(Mask, WidenedMask))
11149     return SDValue();
11150
11151   // Form a 128-bit permutation.
11152   // Convert the 64-bit shuffle mask selection values into 128-bit selection
11153   // bits defined by a vshuf64x2 instruction's immediate control byte.
11154   unsigned PermMask = 0, Imm = 0;
11155   unsigned ControlBitsNum = WidenedMask.size() / 2;
11156
11157   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11158     if (WidenedMask[i] == SM_SentinelZero)
11159       return SDValue();
11160
11161     // Use first element in place of undef mask.
11162     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
11163     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
11164   }
11165
11166   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
11167                      DAG.getConstant(PermMask, DL, MVT::i8));
11168 }
11169
11170 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
11171                                            ArrayRef<int> Mask, SDValue V1,
11172                                            SDValue V2, SelectionDAG &DAG) {
11173
11174   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11175
11176   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11177   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11178
11179   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11180   if (isSingleInputShuffleMask(Mask))
11181     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11182
11183   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11184 }
11185
11186 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11187 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11188                                        const X86Subtarget *Subtarget,
11189                                        SelectionDAG &DAG) {
11190   SDLoc DL(Op);
11191   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11192   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11193   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11194   ArrayRef<int> Mask = SVOp->getMask();
11195   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11196
11197   if (SDValue Shuf128 =
11198           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11199     return Shuf128;
11200
11201   if (SDValue Unpck =
11202           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11203     return Unpck;
11204
11205   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11206 }
11207
11208 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11209 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11210                                         const X86Subtarget *Subtarget,
11211                                         SelectionDAG &DAG) {
11212   SDLoc DL(Op);
11213   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11214   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11215   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11216   ArrayRef<int> Mask = SVOp->getMask();
11217   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11218
11219   if (SDValue Unpck =
11220           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11221     return Unpck;
11222
11223   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11224 }
11225
11226 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11227 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11228                                        const X86Subtarget *Subtarget,
11229                                        SelectionDAG &DAG) {
11230   SDLoc DL(Op);
11231   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11232   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11233   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11234   ArrayRef<int> Mask = SVOp->getMask();
11235   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11236
11237   if (SDValue Shuf128 =
11238           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11239     return Shuf128;
11240
11241   if (SDValue Unpck =
11242           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11243     return Unpck;
11244
11245   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11246 }
11247
11248 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11249 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11250                                         const X86Subtarget *Subtarget,
11251                                         SelectionDAG &DAG) {
11252   SDLoc DL(Op);
11253   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11254   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11255   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11256   ArrayRef<int> Mask = SVOp->getMask();
11257   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11258
11259   if (SDValue Unpck =
11260           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11261     return Unpck;
11262
11263   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11264 }
11265
11266 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11267 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11268                                         const X86Subtarget *Subtarget,
11269                                         SelectionDAG &DAG) {
11270   SDLoc DL(Op);
11271   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11272   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11273   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11274   ArrayRef<int> Mask = SVOp->getMask();
11275   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11276   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11277
11278   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11279 }
11280
11281 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11282 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11283                                        const X86Subtarget *Subtarget,
11284                                        SelectionDAG &DAG) {
11285   SDLoc DL(Op);
11286   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11287   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11288   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11289   ArrayRef<int> Mask = SVOp->getMask();
11290   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11291   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11292
11293   // FIXME: Implement direct support for this type!
11294   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11295 }
11296
11297 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11298 ///
11299 /// This routine either breaks down the specific type of a 512-bit x86 vector
11300 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11301 /// together based on the available instructions.
11302 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11303                                         MVT VT, const X86Subtarget *Subtarget,
11304                                         SelectionDAG &DAG) {
11305   SDLoc DL(Op);
11306   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11307   ArrayRef<int> Mask = SVOp->getMask();
11308   assert(Subtarget->hasAVX512() &&
11309          "Cannot lower 512-bit vectors w/ basic ISA!");
11310
11311   // Check for being able to broadcast a single element.
11312   if (SDValue Broadcast =
11313           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11314     return Broadcast;
11315
11316   // Dispatch to each element type for lowering. If we don't have supprot for
11317   // specific element type shuffles at 512 bits, immediately split them and
11318   // lower them. Each lowering routine of a given type is allowed to assume that
11319   // the requisite ISA extensions for that element type are available.
11320   switch (VT.SimpleTy) {
11321   case MVT::v8f64:
11322     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11323   case MVT::v16f32:
11324     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11325   case MVT::v8i64:
11326     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11327   case MVT::v16i32:
11328     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11329   case MVT::v32i16:
11330     if (Subtarget->hasBWI())
11331       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11332     break;
11333   case MVT::v64i8:
11334     if (Subtarget->hasBWI())
11335       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11336     break;
11337
11338   default:
11339     llvm_unreachable("Not a valid 512-bit x86 vector type!");
11340   }
11341
11342   // Otherwise fall back on splitting.
11343   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11344 }
11345
11346 // Lower vXi1 vector shuffles.
11347 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11348 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11349 // vector, shuffle and then truncate it back.
11350 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11351                                       MVT VT, const X86Subtarget *Subtarget,
11352                                       SelectionDAG &DAG) {
11353   SDLoc DL(Op);
11354   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11355   ArrayRef<int> Mask = SVOp->getMask();
11356   assert(Subtarget->hasAVX512() &&
11357          "Cannot lower 512-bit vectors w/o basic ISA!");
11358   MVT ExtVT;
11359   switch (VT.SimpleTy) {
11360   default:
11361     llvm_unreachable("Expected a vector of i1 elements");
11362   case MVT::v2i1:
11363     ExtVT = MVT::v2i64;
11364     break;
11365   case MVT::v4i1:
11366     ExtVT = MVT::v4i32;
11367     break;
11368   case MVT::v8i1:
11369     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11370     break;
11371   case MVT::v16i1:
11372     ExtVT = MVT::v16i32;
11373     break;
11374   case MVT::v32i1:
11375     ExtVT = MVT::v32i16;
11376     break;
11377   case MVT::v64i1:
11378     ExtVT = MVT::v64i8;
11379     break;
11380   }
11381
11382   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11383     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11384   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11385     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11386   else
11387     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11388
11389   if (V2.isUndef())
11390     V2 = DAG.getUNDEF(ExtVT);
11391   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11392     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11393   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11394     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11395   else
11396     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11397   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11398                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11399 }
11400 /// \brief Top-level lowering for x86 vector shuffles.
11401 ///
11402 /// This handles decomposition, canonicalization, and lowering of all x86
11403 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11404 /// above in helper routines. The canonicalization attempts to widen shuffles
11405 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11406 /// s.t. only one of the two inputs needs to be tested, etc.
11407 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11408                                   SelectionDAG &DAG) {
11409   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11410   ArrayRef<int> Mask = SVOp->getMask();
11411   SDValue V1 = Op.getOperand(0);
11412   SDValue V2 = Op.getOperand(1);
11413   MVT VT = Op.getSimpleValueType();
11414   int NumElements = VT.getVectorNumElements();
11415   SDLoc dl(Op);
11416   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11417
11418   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11419          "Can't lower MMX shuffles");
11420
11421   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11422   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11423   if (V1IsUndef && V2IsUndef)
11424     return DAG.getUNDEF(VT);
11425
11426   // When we create a shuffle node we put the UNDEF node to second operand,
11427   // but in some cases the first operand may be transformed to UNDEF.
11428   // In this case we should just commute the node.
11429   if (V1IsUndef)
11430     return DAG.getCommutedVectorShuffle(*SVOp);
11431
11432   // Check for non-undef masks pointing at an undef vector and make the masks
11433   // undef as well. This makes it easier to match the shuffle based solely on
11434   // the mask.
11435   if (V2IsUndef)
11436     for (int M : Mask)
11437       if (M >= NumElements) {
11438         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11439         for (int &M : NewMask)
11440           if (M >= NumElements)
11441             M = -1;
11442         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11443       }
11444
11445   // We actually see shuffles that are entirely re-arrangements of a set of
11446   // zero inputs. This mostly happens while decomposing complex shuffles into
11447   // simple ones. Directly lower these as a buildvector of zeros.
11448   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11449   if (Zeroable.all())
11450     return getZeroVector(VT, Subtarget, DAG, dl);
11451
11452   // Try to collapse shuffles into using a vector type with fewer elements but
11453   // wider element types. We cap this to not form integers or floating point
11454   // elements wider than 64 bits, but it might be interesting to form i128
11455   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11456   SmallVector<int, 16> WidenedMask;
11457   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11458       canWidenShuffleElements(Mask, WidenedMask)) {
11459     MVT NewEltVT = VT.isFloatingPoint()
11460                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11461                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11462     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11463     // Make sure that the new vector type is legal. For example, v2f64 isn't
11464     // legal on SSE1.
11465     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11466       V1 = DAG.getBitcast(NewVT, V1);
11467       V2 = DAG.getBitcast(NewVT, V2);
11468       return DAG.getBitcast(
11469           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11470     }
11471   }
11472
11473   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11474   for (int M : SVOp->getMask())
11475     if (M < 0)
11476       ++NumUndefElements;
11477     else if (M < NumElements)
11478       ++NumV1Elements;
11479     else
11480       ++NumV2Elements;
11481
11482   // Commute the shuffle as needed such that more elements come from V1 than
11483   // V2. This allows us to match the shuffle pattern strictly on how many
11484   // elements come from V1 without handling the symmetric cases.
11485   if (NumV2Elements > NumV1Elements)
11486     return DAG.getCommutedVectorShuffle(*SVOp);
11487
11488   // When the number of V1 and V2 elements are the same, try to minimize the
11489   // number of uses of V2 in the low half of the vector. When that is tied,
11490   // ensure that the sum of indices for V1 is equal to or lower than the sum
11491   // indices for V2. When those are equal, try to ensure that the number of odd
11492   // indices for V1 is lower than the number of odd indices for V2.
11493   if (NumV1Elements == NumV2Elements) {
11494     int LowV1Elements = 0, LowV2Elements = 0;
11495     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11496       if (M >= NumElements)
11497         ++LowV2Elements;
11498       else if (M >= 0)
11499         ++LowV1Elements;
11500     if (LowV2Elements > LowV1Elements) {
11501       return DAG.getCommutedVectorShuffle(*SVOp);
11502     } else if (LowV2Elements == LowV1Elements) {
11503       int SumV1Indices = 0, SumV2Indices = 0;
11504       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11505         if (SVOp->getMask()[i] >= NumElements)
11506           SumV2Indices += i;
11507         else if (SVOp->getMask()[i] >= 0)
11508           SumV1Indices += i;
11509       if (SumV2Indices < SumV1Indices) {
11510         return DAG.getCommutedVectorShuffle(*SVOp);
11511       } else if (SumV2Indices == SumV1Indices) {
11512         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11513         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11514           if (SVOp->getMask()[i] >= NumElements)
11515             NumV2OddIndices += i % 2;
11516           else if (SVOp->getMask()[i] >= 0)
11517             NumV1OddIndices += i % 2;
11518         if (NumV2OddIndices < NumV1OddIndices)
11519           return DAG.getCommutedVectorShuffle(*SVOp);
11520       }
11521     }
11522   }
11523
11524   // For each vector width, delegate to a specialized lowering routine.
11525   if (VT.is128BitVector())
11526     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11527
11528   if (VT.is256BitVector())
11529     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11530
11531   if (VT.is512BitVector())
11532     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11533
11534   if (Is1BitVector)
11535     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11536   llvm_unreachable("Unimplemented!");
11537 }
11538
11539 // This function assumes its argument is a BUILD_VECTOR of constants or
11540 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11541 // true.
11542 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11543                                     unsigned &MaskValue) {
11544   MaskValue = 0;
11545   unsigned NumElems = BuildVector->getNumOperands();
11546
11547   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11548   // We don't handle the >2 lanes case right now.
11549   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11550   if (NumLanes > 2)
11551     return false;
11552
11553   unsigned NumElemsInLane = NumElems / NumLanes;
11554
11555   // Blend for v16i16 should be symmetric for the both lanes.
11556   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11557     SDValue EltCond = BuildVector->getOperand(i);
11558     SDValue SndLaneEltCond =
11559         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11560
11561     int Lane1Cond = -1, Lane2Cond = -1;
11562     if (isa<ConstantSDNode>(EltCond))
11563       Lane1Cond = !isNullConstant(EltCond);
11564     if (isa<ConstantSDNode>(SndLaneEltCond))
11565       Lane2Cond = !isNullConstant(SndLaneEltCond);
11566
11567     unsigned LaneMask = 0;
11568     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11569       // Lane1Cond != 0, means we want the first argument.
11570       // Lane1Cond == 0, means we want the second argument.
11571       // The encoding of this argument is 0 for the first argument, 1
11572       // for the second. Therefore, invert the condition.
11573       LaneMask = !Lane1Cond << i;
11574     else if (Lane1Cond < 0)
11575       LaneMask = !Lane2Cond << i;
11576     else
11577       return false;
11578
11579     MaskValue |= LaneMask;
11580     if (NumLanes == 2)
11581       MaskValue |= LaneMask << NumElemsInLane;
11582   }
11583   return true;
11584 }
11585
11586 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11587 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11588                                            const X86Subtarget *Subtarget,
11589                                            SelectionDAG &DAG) {
11590   SDValue Cond = Op.getOperand(0);
11591   SDValue LHS = Op.getOperand(1);
11592   SDValue RHS = Op.getOperand(2);
11593   SDLoc dl(Op);
11594   MVT VT = Op.getSimpleValueType();
11595
11596   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11597     return SDValue();
11598   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11599
11600   // Only non-legal VSELECTs reach this lowering, convert those into generic
11601   // shuffles and re-use the shuffle lowering path for blends.
11602   SmallVector<int, 32> Mask;
11603   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11604     SDValue CondElt = CondBV->getOperand(i);
11605     Mask.push_back(
11606         isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11607                                      : -1);
11608   }
11609   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11610 }
11611
11612 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11613   // A vselect where all conditions and data are constants can be optimized into
11614   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11615   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11616       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11617       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11618     return SDValue();
11619
11620   // Try to lower this to a blend-style vector shuffle. This can handle all
11621   // constant condition cases.
11622   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11623     return BlendOp;
11624
11625   // Variable blends are only legal from SSE4.1 onward.
11626   if (!Subtarget->hasSSE41())
11627     return SDValue();
11628
11629   // Only some types will be legal on some subtargets. If we can emit a legal
11630   // VSELECT-matching blend, return Op, and but if we need to expand, return
11631   // a null value.
11632   switch (Op.getSimpleValueType().SimpleTy) {
11633   default:
11634     // Most of the vector types have blends past SSE4.1.
11635     return Op;
11636
11637   case MVT::v32i8:
11638     // The byte blends for AVX vectors were introduced only in AVX2.
11639     if (Subtarget->hasAVX2())
11640       return Op;
11641
11642     return SDValue();
11643
11644   case MVT::v8i16:
11645   case MVT::v16i16:
11646     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11647     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11648       return Op;
11649
11650     // FIXME: We should custom lower this by fixing the condition and using i8
11651     // blends.
11652     return SDValue();
11653   }
11654 }
11655
11656 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11657   MVT VT = Op.getSimpleValueType();
11658   SDLoc dl(Op);
11659
11660   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11661     return SDValue();
11662
11663   if (VT.getSizeInBits() == 8) {
11664     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11665                                   Op.getOperand(0), Op.getOperand(1));
11666     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11667                                   DAG.getValueType(VT));
11668     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11669   }
11670
11671   if (VT.getSizeInBits() == 16) {
11672     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11673     if (isNullConstant(Op.getOperand(1)))
11674       return DAG.getNode(
11675           ISD::TRUNCATE, dl, MVT::i16,
11676           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11677                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11678                       Op.getOperand(1)));
11679     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11680                                   Op.getOperand(0), Op.getOperand(1));
11681     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11682                                   DAG.getValueType(VT));
11683     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11684   }
11685
11686   if (VT == MVT::f32) {
11687     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11688     // the result back to FR32 register. It's only worth matching if the
11689     // result has a single use which is a store or a bitcast to i32.  And in
11690     // the case of a store, it's not worth it if the index is a constant 0,
11691     // because a MOVSSmr can be used instead, which is smaller and faster.
11692     if (!Op.hasOneUse())
11693       return SDValue();
11694     SDNode *User = *Op.getNode()->use_begin();
11695     if ((User->getOpcode() != ISD::STORE ||
11696          isNullConstant(Op.getOperand(1))) &&
11697         (User->getOpcode() != ISD::BITCAST ||
11698          User->getValueType(0) != MVT::i32))
11699       return SDValue();
11700     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11701                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11702                                   Op.getOperand(1));
11703     return DAG.getBitcast(MVT::f32, Extract);
11704   }
11705
11706   if (VT == MVT::i32 || VT == MVT::i64) {
11707     // ExtractPS/pextrq works with constant index.
11708     if (isa<ConstantSDNode>(Op.getOperand(1)))
11709       return Op;
11710   }
11711   return SDValue();
11712 }
11713
11714 /// Extract one bit from mask vector, like v16i1 or v8i1.
11715 /// AVX-512 feature.
11716 SDValue
11717 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11718   SDValue Vec = Op.getOperand(0);
11719   SDLoc dl(Vec);
11720   MVT VecVT = Vec.getSimpleValueType();
11721   SDValue Idx = Op.getOperand(1);
11722   MVT EltVT = Op.getSimpleValueType();
11723
11724   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11725   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11726          "Unexpected vector type in ExtractBitFromMaskVector");
11727
11728   // variable index can't be handled in mask registers,
11729   // extend vector to VR512
11730   if (!isa<ConstantSDNode>(Idx)) {
11731     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11732     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11733     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11734                               ExtVT.getVectorElementType(), Ext, Idx);
11735     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11736   }
11737
11738   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11739   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11740   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11741     rc = getRegClassFor(MVT::v16i1);
11742   unsigned MaxSift = rc->getSize()*8 - 1;
11743   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11744                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11745   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11746                     DAG.getConstant(MaxSift, dl, MVT::i8));
11747   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11748                        DAG.getIntPtrConstant(0, dl));
11749 }
11750
11751 SDValue
11752 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11753                                            SelectionDAG &DAG) const {
11754   SDLoc dl(Op);
11755   SDValue Vec = Op.getOperand(0);
11756   MVT VecVT = Vec.getSimpleValueType();
11757   SDValue Idx = Op.getOperand(1);
11758
11759   if (Op.getSimpleValueType() == MVT::i1)
11760     return ExtractBitFromMaskVector(Op, DAG);
11761
11762   if (!isa<ConstantSDNode>(Idx)) {
11763     if (VecVT.is512BitVector() ||
11764         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11765          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11766
11767       MVT MaskEltVT =
11768         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11769       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11770                                     MaskEltVT.getSizeInBits());
11771
11772       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11773       auto PtrVT = getPointerTy(DAG.getDataLayout());
11774       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11775                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11776                                  DAG.getConstant(0, dl, PtrVT));
11777       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11778       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11779                          DAG.getConstant(0, dl, PtrVT));
11780     }
11781     return SDValue();
11782   }
11783
11784   // If this is a 256-bit vector result, first extract the 128-bit vector and
11785   // then extract the element from the 128-bit vector.
11786   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11787
11788     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11789     // Get the 128-bit vector.
11790     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11791     MVT EltVT = VecVT.getVectorElementType();
11792
11793     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11794     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11795
11796     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11797     // this can be done with a mask.
11798     IdxVal &= ElemsPerChunk - 1;
11799     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11800                        DAG.getConstant(IdxVal, dl, MVT::i32));
11801   }
11802
11803   assert(VecVT.is128BitVector() && "Unexpected vector length");
11804
11805   if (Subtarget->hasSSE41())
11806     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11807       return Res;
11808
11809   MVT VT = Op.getSimpleValueType();
11810   // TODO: handle v16i8.
11811   if (VT.getSizeInBits() == 16) {
11812     SDValue Vec = Op.getOperand(0);
11813     if (isNullConstant(Op.getOperand(1)))
11814       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11815                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11816                                      DAG.getBitcast(MVT::v4i32, Vec),
11817                                      Op.getOperand(1)));
11818     // Transform it so it match pextrw which produces a 32-bit result.
11819     MVT EltVT = MVT::i32;
11820     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11821                                   Op.getOperand(0), Op.getOperand(1));
11822     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11823                                   DAG.getValueType(VT));
11824     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11825   }
11826
11827   if (VT.getSizeInBits() == 32) {
11828     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11829     if (Idx == 0)
11830       return Op;
11831
11832     // SHUFPS the element to the lowest double word, then movss.
11833     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11834     MVT VVT = Op.getOperand(0).getSimpleValueType();
11835     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11836                                        DAG.getUNDEF(VVT), Mask);
11837     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11838                        DAG.getIntPtrConstant(0, dl));
11839   }
11840
11841   if (VT.getSizeInBits() == 64) {
11842     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11843     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11844     //        to match extract_elt for f64.
11845     if (isNullConstant(Op.getOperand(1)))
11846       return Op;
11847
11848     // UNPCKHPD the element to the lowest double word, then movsd.
11849     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11850     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11851     int Mask[2] = { 1, -1 };
11852     MVT VVT = Op.getOperand(0).getSimpleValueType();
11853     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11854                                        DAG.getUNDEF(VVT), Mask);
11855     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11856                        DAG.getIntPtrConstant(0, dl));
11857   }
11858
11859   return SDValue();
11860 }
11861
11862 /// Insert one bit to mask vector, like v16i1 or v8i1.
11863 /// AVX-512 feature.
11864 SDValue
11865 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11866   SDLoc dl(Op);
11867   SDValue Vec = Op.getOperand(0);
11868   SDValue Elt = Op.getOperand(1);
11869   SDValue Idx = Op.getOperand(2);
11870   MVT VecVT = Vec.getSimpleValueType();
11871
11872   if (!isa<ConstantSDNode>(Idx)) {
11873     // Non constant index. Extend source and destination,
11874     // insert element and then truncate the result.
11875     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11876     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11877     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11878       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11879       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11880     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11881   }
11882
11883   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11884   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11885   if (IdxVal)
11886     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11887                            DAG.getConstant(IdxVal, dl, MVT::i8));
11888   if (Vec.getOpcode() == ISD::UNDEF)
11889     return EltInVec;
11890   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11891 }
11892
11893 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11894                                                   SelectionDAG &DAG) const {
11895   MVT VT = Op.getSimpleValueType();
11896   MVT EltVT = VT.getVectorElementType();
11897
11898   if (EltVT == MVT::i1)
11899     return InsertBitToMaskVector(Op, DAG);
11900
11901   SDLoc dl(Op);
11902   SDValue N0 = Op.getOperand(0);
11903   SDValue N1 = Op.getOperand(1);
11904   SDValue N2 = Op.getOperand(2);
11905   if (!isa<ConstantSDNode>(N2))
11906     return SDValue();
11907   auto *N2C = cast<ConstantSDNode>(N2);
11908   unsigned IdxVal = N2C->getZExtValue();
11909
11910   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11911   // into that, and then insert the subvector back into the result.
11912   if (VT.is256BitVector() || VT.is512BitVector()) {
11913     // With a 256-bit vector, we can insert into the zero element efficiently
11914     // using a blend if we have AVX or AVX2 and the right data type.
11915     if (VT.is256BitVector() && IdxVal == 0) {
11916       // TODO: It is worthwhile to cast integer to floating point and back
11917       // and incur a domain crossing penalty if that's what we'll end up
11918       // doing anyway after extracting to a 128-bit vector.
11919       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11920           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11921         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11922         N2 = DAG.getIntPtrConstant(1, dl);
11923         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11924       }
11925     }
11926
11927     // Get the desired 128-bit vector chunk.
11928     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11929
11930     // Insert the element into the desired chunk.
11931     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11932     assert(isPowerOf2_32(NumEltsIn128));
11933     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11934     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11935
11936     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11937                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11938
11939     // Insert the changed part back into the bigger vector
11940     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11941   }
11942   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11943
11944   if (Subtarget->hasSSE41()) {
11945     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11946       unsigned Opc;
11947       if (VT == MVT::v8i16) {
11948         Opc = X86ISD::PINSRW;
11949       } else {
11950         assert(VT == MVT::v16i8);
11951         Opc = X86ISD::PINSRB;
11952       }
11953
11954       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11955       // argument.
11956       if (N1.getValueType() != MVT::i32)
11957         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11958       if (N2.getValueType() != MVT::i32)
11959         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11960       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11961     }
11962
11963     if (EltVT == MVT::f32) {
11964       // Bits [7:6] of the constant are the source select. This will always be
11965       //   zero here. The DAG Combiner may combine an extract_elt index into
11966       //   these bits. For example (insert (extract, 3), 2) could be matched by
11967       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11968       // Bits [5:4] of the constant are the destination select. This is the
11969       //   value of the incoming immediate.
11970       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11971       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11972
11973       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11974       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11975         // If this is an insertion of 32-bits into the low 32-bits of
11976         // a vector, we prefer to generate a blend with immediate rather
11977         // than an insertps. Blends are simpler operations in hardware and so
11978         // will always have equal or better performance than insertps.
11979         // But if optimizing for size and there's a load folding opportunity,
11980         // generate insertps because blendps does not have a 32-bit memory
11981         // operand form.
11982         N2 = DAG.getIntPtrConstant(1, dl);
11983         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11984         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11985       }
11986       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11987       // Create this as a scalar to vector..
11988       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11989       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11990     }
11991
11992     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11993       // PINSR* works with constant index.
11994       return Op;
11995     }
11996   }
11997
11998   if (EltVT == MVT::i8)
11999     return SDValue();
12000
12001   if (EltVT.getSizeInBits() == 16) {
12002     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
12003     // as its second argument.
12004     if (N1.getValueType() != MVT::i32)
12005       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12006     if (N2.getValueType() != MVT::i32)
12007       N2 = DAG.getIntPtrConstant(IdxVal, dl);
12008     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
12009   }
12010   return SDValue();
12011 }
12012
12013 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
12014   SDLoc dl(Op);
12015   MVT OpVT = Op.getSimpleValueType();
12016
12017   // If this is a 256-bit vector result, first insert into a 128-bit
12018   // vector and then insert into the 256-bit vector.
12019   if (!OpVT.is128BitVector()) {
12020     // Insert into a 128-bit vector.
12021     unsigned SizeFactor = OpVT.getSizeInBits()/128;
12022     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
12023                                  OpVT.getVectorNumElements() / SizeFactor);
12024
12025     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
12026
12027     // Insert the 128-bit vector.
12028     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12029   }
12030
12031   if (OpVT == MVT::v1i64 &&
12032       Op.getOperand(0).getValueType() == MVT::i64)
12033     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12034
12035   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12036   assert(OpVT.is128BitVector() && "Expected an SSE type!");
12037   return DAG.getBitcast(
12038       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
12039 }
12040
12041 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
12042 // a simple subregister reference or explicit instructions to grab
12043 // upper bits of a vector.
12044 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12045                                       SelectionDAG &DAG) {
12046   SDLoc dl(Op);
12047   SDValue In =  Op.getOperand(0);
12048   SDValue Idx = Op.getOperand(1);
12049   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12050   MVT ResVT   = Op.getSimpleValueType();
12051   MVT InVT    = In.getSimpleValueType();
12052
12053   if (Subtarget->hasFp256()) {
12054     if (ResVT.is128BitVector() &&
12055         (InVT.is256BitVector() || InVT.is512BitVector()) &&
12056         isa<ConstantSDNode>(Idx)) {
12057       return Extract128BitVector(In, IdxVal, DAG, dl);
12058     }
12059     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12060         isa<ConstantSDNode>(Idx)) {
12061       return Extract256BitVector(In, IdxVal, DAG, dl);
12062     }
12063   }
12064   return SDValue();
12065 }
12066
12067 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
12068 // simple superregister reference or explicit instructions to insert
12069 // the upper bits of a vector.
12070 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12071                                      SelectionDAG &DAG) {
12072   if (!Subtarget->hasAVX())
12073     return SDValue();
12074
12075   SDLoc dl(Op);
12076   SDValue Vec = Op.getOperand(0);
12077   SDValue SubVec = Op.getOperand(1);
12078   SDValue Idx = Op.getOperand(2);
12079
12080   if (!isa<ConstantSDNode>(Idx))
12081     return SDValue();
12082
12083   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12084   MVT OpVT = Op.getSimpleValueType();
12085   MVT SubVecVT = SubVec.getSimpleValueType();
12086
12087   // Fold two 16-byte subvector loads into one 32-byte load:
12088   // (insert_subvector (insert_subvector undef, (load addr), 0),
12089   //                   (load addr + 16), Elts/2)
12090   // --> load32 addr
12091   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
12092       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
12093       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
12094     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
12095     if (Idx2 && Idx2->getZExtValue() == 0) {
12096       SDValue SubVec2 = Vec.getOperand(1);
12097       // If needed, look through a bitcast to get to the load.
12098       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
12099         SubVec2 = SubVec2.getOperand(0);
12100
12101       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
12102         bool Fast;
12103         unsigned Alignment = FirstLd->getAlignment();
12104         unsigned AS = FirstLd->getAddressSpace();
12105         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
12106         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
12107                                     OpVT, AS, Alignment, &Fast) && Fast) {
12108           SDValue Ops[] = { SubVec2, SubVec };
12109           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
12110             return Ld;
12111         }
12112       }
12113     }
12114   }
12115
12116   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
12117       SubVecVT.is128BitVector())
12118     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12119
12120   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
12121     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12122
12123   if (OpVT.getVectorElementType() == MVT::i1)
12124     return Insert1BitVector(Op, DAG);
12125
12126   return SDValue();
12127 }
12128
12129 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12130 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12131 // one of the above mentioned nodes. It has to be wrapped because otherwise
12132 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12133 // be used to form addressing mode. These wrapped nodes will be selected
12134 // into MOV32ri.
12135 SDValue
12136 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12137   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12138
12139   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12140   // global base reg.
12141   unsigned char OpFlag = 0;
12142   unsigned WrapperKind = X86ISD::Wrapper;
12143   CodeModel::Model M = DAG.getTarget().getCodeModel();
12144
12145   if (Subtarget->isPICStyleRIPRel() &&
12146       (M == CodeModel::Small || M == CodeModel::Kernel))
12147     WrapperKind = X86ISD::WrapperRIP;
12148   else if (Subtarget->isPICStyleGOT())
12149     OpFlag = X86II::MO_GOTOFF;
12150   else if (Subtarget->isPICStyleStubPIC())
12151     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12152
12153   auto PtrVT = getPointerTy(DAG.getDataLayout());
12154   SDValue Result = DAG.getTargetConstantPool(
12155       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
12156   SDLoc DL(CP);
12157   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12158   // With PIC, the address is actually $g + Offset.
12159   if (OpFlag) {
12160     Result =
12161         DAG.getNode(ISD::ADD, DL, PtrVT,
12162                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12163   }
12164
12165   return Result;
12166 }
12167
12168 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12169   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12170
12171   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12172   // global base reg.
12173   unsigned char OpFlag = 0;
12174   unsigned WrapperKind = X86ISD::Wrapper;
12175   CodeModel::Model M = DAG.getTarget().getCodeModel();
12176
12177   if (Subtarget->isPICStyleRIPRel() &&
12178       (M == CodeModel::Small || M == CodeModel::Kernel))
12179     WrapperKind = X86ISD::WrapperRIP;
12180   else if (Subtarget->isPICStyleGOT())
12181     OpFlag = X86II::MO_GOTOFF;
12182   else if (Subtarget->isPICStyleStubPIC())
12183     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12184
12185   auto PtrVT = getPointerTy(DAG.getDataLayout());
12186   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12187   SDLoc DL(JT);
12188   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12189
12190   // With PIC, the address is actually $g + Offset.
12191   if (OpFlag)
12192     Result =
12193         DAG.getNode(ISD::ADD, DL, PtrVT,
12194                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12195
12196   return Result;
12197 }
12198
12199 SDValue
12200 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12201   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12202
12203   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12204   // global base reg.
12205   unsigned char OpFlag = 0;
12206   unsigned WrapperKind = X86ISD::Wrapper;
12207   CodeModel::Model M = DAG.getTarget().getCodeModel();
12208
12209   if (Subtarget->isPICStyleRIPRel() &&
12210       (M == CodeModel::Small || M == CodeModel::Kernel)) {
12211     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12212       OpFlag = X86II::MO_GOTPCREL;
12213     WrapperKind = X86ISD::WrapperRIP;
12214   } else if (Subtarget->isPICStyleGOT()) {
12215     OpFlag = X86II::MO_GOT;
12216   } else if (Subtarget->isPICStyleStubPIC()) {
12217     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12218   } else if (Subtarget->isPICStyleStubNoDynamic()) {
12219     OpFlag = X86II::MO_DARWIN_NONLAZY;
12220   }
12221
12222   auto PtrVT = getPointerTy(DAG.getDataLayout());
12223   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12224
12225   SDLoc DL(Op);
12226   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12227
12228   // With PIC, the address is actually $g + Offset.
12229   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12230       !Subtarget->is64Bit()) {
12231     Result =
12232         DAG.getNode(ISD::ADD, DL, PtrVT,
12233                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12234   }
12235
12236   // For symbols that require a load from a stub to get the address, emit the
12237   // load.
12238   if (isGlobalStubReference(OpFlag))
12239     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12240                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12241                          false, false, false, 0);
12242
12243   return Result;
12244 }
12245
12246 SDValue
12247 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12248   // Create the TargetBlockAddressAddress node.
12249   unsigned char OpFlags =
12250     Subtarget->ClassifyBlockAddressReference();
12251   CodeModel::Model M = DAG.getTarget().getCodeModel();
12252   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12253   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12254   SDLoc dl(Op);
12255   auto PtrVT = getPointerTy(DAG.getDataLayout());
12256   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12257
12258   if (Subtarget->isPICStyleRIPRel() &&
12259       (M == CodeModel::Small || M == CodeModel::Kernel))
12260     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12261   else
12262     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12263
12264   // With PIC, the address is actually $g + Offset.
12265   if (isGlobalRelativeToPICBase(OpFlags)) {
12266     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12267                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12268   }
12269
12270   return Result;
12271 }
12272
12273 SDValue
12274 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12275                                       int64_t Offset, SelectionDAG &DAG) const {
12276   // Create the TargetGlobalAddress node, folding in the constant
12277   // offset if it is legal.
12278   unsigned char OpFlags =
12279       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12280   CodeModel::Model M = DAG.getTarget().getCodeModel();
12281   auto PtrVT = getPointerTy(DAG.getDataLayout());
12282   SDValue Result;
12283   if (OpFlags == X86II::MO_NO_FLAG &&
12284       X86::isOffsetSuitableForCodeModel(Offset, M)) {
12285     // A direct static reference to a global.
12286     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12287     Offset = 0;
12288   } else {
12289     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12290   }
12291
12292   if (Subtarget->isPICStyleRIPRel() &&
12293       (M == CodeModel::Small || M == CodeModel::Kernel))
12294     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12295   else
12296     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12297
12298   // With PIC, the address is actually $g + Offset.
12299   if (isGlobalRelativeToPICBase(OpFlags)) {
12300     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12301                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12302   }
12303
12304   // For globals that require a load from a stub to get the address, emit the
12305   // load.
12306   if (isGlobalStubReference(OpFlags))
12307     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12308                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12309                          false, false, false, 0);
12310
12311   // If there was a non-zero offset that we didn't fold, create an explicit
12312   // addition for it.
12313   if (Offset != 0)
12314     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12315                          DAG.getConstant(Offset, dl, PtrVT));
12316
12317   return Result;
12318 }
12319
12320 SDValue
12321 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12322   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12323   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12324   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12325 }
12326
12327 static SDValue
12328 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12329            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12330            unsigned char OperandFlags, bool LocalDynamic = false) {
12331   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12332   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12333   SDLoc dl(GA);
12334   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12335                                            GA->getValueType(0),
12336                                            GA->getOffset(),
12337                                            OperandFlags);
12338
12339   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12340                                            : X86ISD::TLSADDR;
12341
12342   if (InFlag) {
12343     SDValue Ops[] = { Chain,  TGA, *InFlag };
12344     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12345   } else {
12346     SDValue Ops[]  = { Chain, TGA };
12347     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12348   }
12349
12350   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12351   MFI->setAdjustsStack(true);
12352   MFI->setHasCalls(true);
12353
12354   SDValue Flag = Chain.getValue(1);
12355   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12356 }
12357
12358 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12359 static SDValue
12360 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12361                                 const EVT PtrVT) {
12362   SDValue InFlag;
12363   SDLoc dl(GA);  // ? function entry point might be better
12364   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12365                                    DAG.getNode(X86ISD::GlobalBaseReg,
12366                                                SDLoc(), PtrVT), InFlag);
12367   InFlag = Chain.getValue(1);
12368
12369   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12370 }
12371
12372 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12373 static SDValue
12374 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12375                                 const EVT PtrVT) {
12376   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12377                     X86::RAX, X86II::MO_TLSGD);
12378 }
12379
12380 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12381                                            SelectionDAG &DAG,
12382                                            const EVT PtrVT,
12383                                            bool is64Bit) {
12384   SDLoc dl(GA);
12385
12386   // Get the start address of the TLS block for this module.
12387   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12388       .getInfo<X86MachineFunctionInfo>();
12389   MFI->incNumLocalDynamicTLSAccesses();
12390
12391   SDValue Base;
12392   if (is64Bit) {
12393     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12394                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12395   } else {
12396     SDValue InFlag;
12397     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12398         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12399     InFlag = Chain.getValue(1);
12400     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12401                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12402   }
12403
12404   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12405   // of Base.
12406
12407   // Build x@dtpoff.
12408   unsigned char OperandFlags = X86II::MO_DTPOFF;
12409   unsigned WrapperKind = X86ISD::Wrapper;
12410   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12411                                            GA->getValueType(0),
12412                                            GA->getOffset(), OperandFlags);
12413   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12414
12415   // Add x@dtpoff with the base.
12416   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12417 }
12418
12419 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12420 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12421                                    const EVT PtrVT, TLSModel::Model model,
12422                                    bool is64Bit, bool isPIC) {
12423   SDLoc dl(GA);
12424
12425   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12426   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12427                                                          is64Bit ? 257 : 256));
12428
12429   SDValue ThreadPointer =
12430       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12431                   MachinePointerInfo(Ptr), false, false, false, 0);
12432
12433   unsigned char OperandFlags = 0;
12434   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12435   // initialexec.
12436   unsigned WrapperKind = X86ISD::Wrapper;
12437   if (model == TLSModel::LocalExec) {
12438     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12439   } else if (model == TLSModel::InitialExec) {
12440     if (is64Bit) {
12441       OperandFlags = X86II::MO_GOTTPOFF;
12442       WrapperKind = X86ISD::WrapperRIP;
12443     } else {
12444       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12445     }
12446   } else {
12447     llvm_unreachable("Unexpected model");
12448   }
12449
12450   // emit "addl x@ntpoff,%eax" (local exec)
12451   // or "addl x@indntpoff,%eax" (initial exec)
12452   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12453   SDValue TGA =
12454       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12455                                  GA->getOffset(), OperandFlags);
12456   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12457
12458   if (model == TLSModel::InitialExec) {
12459     if (isPIC && !is64Bit) {
12460       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12461                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12462                            Offset);
12463     }
12464
12465     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12466                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12467                          false, false, false, 0);
12468   }
12469
12470   // The address of the thread local variable is the add of the thread
12471   // pointer with the offset of the variable.
12472   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12473 }
12474
12475 SDValue
12476 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12477
12478   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12479
12480   // Cygwin uses emutls.
12481   // FIXME: It may be EmulatedTLS-generic also for X86-Android.
12482   if (Subtarget->isTargetWindowsCygwin())
12483     return LowerToTLSEmulatedModel(GA, DAG);
12484
12485   const GlobalValue *GV = GA->getGlobal();
12486   auto PtrVT = getPointerTy(DAG.getDataLayout());
12487
12488   if (Subtarget->isTargetELF()) {
12489     if (DAG.getTarget().Options.EmulatedTLS)
12490       return LowerToTLSEmulatedModel(GA, DAG);
12491     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12492     switch (model) {
12493       case TLSModel::GeneralDynamic:
12494         if (Subtarget->is64Bit())
12495           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12496         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12497       case TLSModel::LocalDynamic:
12498         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12499                                            Subtarget->is64Bit());
12500       case TLSModel::InitialExec:
12501       case TLSModel::LocalExec:
12502         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12503                                    DAG.getTarget().getRelocationModel() ==
12504                                        Reloc::PIC_);
12505     }
12506     llvm_unreachable("Unknown TLS model.");
12507   }
12508
12509   if (Subtarget->isTargetDarwin()) {
12510     // Darwin only has one model of TLS.  Lower to that.
12511     unsigned char OpFlag = 0;
12512     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12513                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12514
12515     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12516     // global base reg.
12517     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12518                  !Subtarget->is64Bit();
12519     if (PIC32)
12520       OpFlag = X86II::MO_TLVP_PIC_BASE;
12521     else
12522       OpFlag = X86II::MO_TLVP;
12523     SDLoc DL(Op);
12524     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12525                                                 GA->getValueType(0),
12526                                                 GA->getOffset(), OpFlag);
12527     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12528
12529     // With PIC32, the address is actually $g + Offset.
12530     if (PIC32)
12531       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12532                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12533                            Offset);
12534
12535     // Lowering the machine isd will make sure everything is in the right
12536     // location.
12537     SDValue Chain = DAG.getEntryNode();
12538     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12539     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, DL, true), DL);
12540     SDValue Args[] = { Chain, Offset };
12541     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12542     Chain =
12543         DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
12544                            DAG.getIntPtrConstant(0, DL, true), SDValue(), DL);
12545
12546     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12547     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12548     MFI->setAdjustsStack(true);
12549
12550     // And our return value (tls address) is in the standard call return value
12551     // location.
12552     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12553     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12554   }
12555
12556   if (Subtarget->isTargetKnownWindowsMSVC() ||
12557       Subtarget->isTargetWindowsGNU()) {
12558     // Just use the implicit TLS architecture
12559     // Need to generate someting similar to:
12560     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12561     //                                  ; from TEB
12562     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12563     //   mov     rcx, qword [rdx+rcx*8]
12564     //   mov     eax, .tls$:tlsvar
12565     //   [rax+rcx] contains the address
12566     // Windows 64bit: gs:0x58
12567     // Windows 32bit: fs:__tls_array
12568
12569     SDLoc dl(GA);
12570     SDValue Chain = DAG.getEntryNode();
12571
12572     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12573     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12574     // use its literal value of 0x2C.
12575     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12576                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12577                                                              256)
12578                                         : Type::getInt32PtrTy(*DAG.getContext(),
12579                                                               257));
12580
12581     SDValue TlsArray = Subtarget->is64Bit()
12582                            ? DAG.getIntPtrConstant(0x58, dl)
12583                            : (Subtarget->isTargetWindowsGNU()
12584                                   ? DAG.getIntPtrConstant(0x2C, dl)
12585                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12586
12587     SDValue ThreadPointer =
12588         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12589                     false, false, 0);
12590
12591     SDValue res;
12592     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12593       res = ThreadPointer;
12594     } else {
12595       // Load the _tls_index variable
12596       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12597       if (Subtarget->is64Bit())
12598         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12599                              MachinePointerInfo(), MVT::i32, false, false,
12600                              false, 0);
12601       else
12602         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12603                           false, false, 0);
12604
12605       auto &DL = DAG.getDataLayout();
12606       SDValue Scale =
12607           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12608       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12609
12610       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12611     }
12612
12613     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12614                       false, 0);
12615
12616     // Get the offset of start of .tls section
12617     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12618                                              GA->getValueType(0),
12619                                              GA->getOffset(), X86II::MO_SECREL);
12620     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12621
12622     // The address of the thread local variable is the add of the thread
12623     // pointer with the offset of the variable.
12624     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12625   }
12626
12627   llvm_unreachable("TLS not implemented for this target.");
12628 }
12629
12630 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12631 /// and take a 2 x i32 value to shift plus a shift amount.
12632 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12633   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12634   MVT VT = Op.getSimpleValueType();
12635   unsigned VTBits = VT.getSizeInBits();
12636   SDLoc dl(Op);
12637   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12638   SDValue ShOpLo = Op.getOperand(0);
12639   SDValue ShOpHi = Op.getOperand(1);
12640   SDValue ShAmt  = Op.getOperand(2);
12641   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12642   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12643   // during isel.
12644   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12645                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12646   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12647                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12648                        : DAG.getConstant(0, dl, VT);
12649
12650   SDValue Tmp2, Tmp3;
12651   if (Op.getOpcode() == ISD::SHL_PARTS) {
12652     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12653     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12654   } else {
12655     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12656     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12657   }
12658
12659   // If the shift amount is larger or equal than the width of a part we can't
12660   // rely on the results of shld/shrd. Insert a test and select the appropriate
12661   // values for large shift amounts.
12662   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12663                                 DAG.getConstant(VTBits, dl, MVT::i8));
12664   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12665                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12666
12667   SDValue Hi, Lo;
12668   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12669   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12670   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12671
12672   if (Op.getOpcode() == ISD::SHL_PARTS) {
12673     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12674     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12675   } else {
12676     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12677     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12678   }
12679
12680   SDValue Ops[2] = { Lo, Hi };
12681   return DAG.getMergeValues(Ops, dl);
12682 }
12683
12684 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12685                                            SelectionDAG &DAG) const {
12686   SDValue Src = Op.getOperand(0);
12687   MVT SrcVT = Src.getSimpleValueType();
12688   MVT VT = Op.getSimpleValueType();
12689   SDLoc dl(Op);
12690
12691   if (SrcVT.isVector()) {
12692     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12693       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12694                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12695                          DAG.getUNDEF(SrcVT)));
12696     }
12697     if (SrcVT.getVectorElementType() == MVT::i1) {
12698       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12699       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12700                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12701     }
12702     return SDValue();
12703   }
12704
12705   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12706          "Unknown SINT_TO_FP to lower!");
12707
12708   // These are really Legal; return the operand so the caller accepts it as
12709   // Legal.
12710   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12711     return Op;
12712   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12713       Subtarget->is64Bit()) {
12714     return Op;
12715   }
12716
12717   SDValue ValueToStore = Op.getOperand(0);
12718   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12719       !Subtarget->is64Bit())
12720     // Bitcasting to f64 here allows us to do a single 64-bit store from
12721     // an SSE register, avoiding the store forwarding penalty that would come
12722     // with two 32-bit stores.
12723     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
12724
12725   unsigned Size = SrcVT.getSizeInBits()/8;
12726   MachineFunction &MF = DAG.getMachineFunction();
12727   auto PtrVT = getPointerTy(MF.getDataLayout());
12728   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12729   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12730   SDValue Chain = DAG.getStore(
12731       DAG.getEntryNode(), dl, ValueToStore, StackSlot,
12732       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12733       false, 0);
12734   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12735 }
12736
12737 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12738                                      SDValue StackSlot,
12739                                      SelectionDAG &DAG) const {
12740   // Build the FILD
12741   SDLoc DL(Op);
12742   SDVTList Tys;
12743   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12744   if (useSSE)
12745     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12746   else
12747     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12748
12749   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12750
12751   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12752   MachineMemOperand *MMO;
12753   if (FI) {
12754     int SSFI = FI->getIndex();
12755     MMO = DAG.getMachineFunction().getMachineMemOperand(
12756         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12757         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12758   } else {
12759     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12760     StackSlot = StackSlot.getOperand(1);
12761   }
12762   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12763   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12764                                            X86ISD::FILD, DL,
12765                                            Tys, Ops, SrcVT, MMO);
12766
12767   if (useSSE) {
12768     Chain = Result.getValue(1);
12769     SDValue InFlag = Result.getValue(2);
12770
12771     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12772     // shouldn't be necessary except that RFP cannot be live across
12773     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12774     MachineFunction &MF = DAG.getMachineFunction();
12775     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12776     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12777     auto PtrVT = getPointerTy(MF.getDataLayout());
12778     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12779     Tys = DAG.getVTList(MVT::Other);
12780     SDValue Ops[] = {
12781       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12782     };
12783     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12784         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12785         MachineMemOperand::MOStore, SSFISize, SSFISize);
12786
12787     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12788                                     Ops, Op.getValueType(), MMO);
12789     Result = DAG.getLoad(
12790         Op.getValueType(), DL, Chain, StackSlot,
12791         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12792         false, false, false, 0);
12793   }
12794
12795   return Result;
12796 }
12797
12798 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12799 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12800                                                SelectionDAG &DAG) const {
12801   // This algorithm is not obvious. Here it is what we're trying to output:
12802   /*
12803      movq       %rax,  %xmm0
12804      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12805      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12806      #ifdef __SSE3__
12807        haddpd   %xmm0, %xmm0
12808      #else
12809        pshufd   $0x4e, %xmm0, %xmm1
12810        addpd    %xmm1, %xmm0
12811      #endif
12812   */
12813
12814   SDLoc dl(Op);
12815   LLVMContext *Context = DAG.getContext();
12816
12817   // Build some magic constants.
12818   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12819   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12820   auto PtrVT = getPointerTy(DAG.getDataLayout());
12821   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12822
12823   SmallVector<Constant*,2> CV1;
12824   CV1.push_back(
12825     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12826                                       APInt(64, 0x4330000000000000ULL))));
12827   CV1.push_back(
12828     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12829                                       APInt(64, 0x4530000000000000ULL))));
12830   Constant *C1 = ConstantVector::get(CV1);
12831   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12832
12833   // Load the 64-bit value into an XMM register.
12834   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12835                             Op.getOperand(0));
12836   SDValue CLod0 =
12837       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12838                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12839                   false, false, false, 16);
12840   SDValue Unpck1 =
12841       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12842
12843   SDValue CLod1 =
12844       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12845                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12846                   false, false, false, 16);
12847   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12848   // TODO: Are there any fast-math-flags to propagate here?
12849   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12850   SDValue Result;
12851
12852   if (Subtarget->hasSSE3()) {
12853     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12854     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12855   } else {
12856     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12857     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12858                                            S2F, 0x4E, DAG);
12859     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12860                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12861   }
12862
12863   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12864                      DAG.getIntPtrConstant(0, dl));
12865 }
12866
12867 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12868 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12869                                                SelectionDAG &DAG) const {
12870   SDLoc dl(Op);
12871   // FP constant to bias correct the final result.
12872   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12873                                    MVT::f64);
12874
12875   // Load the 32-bit value into an XMM register.
12876   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12877                              Op.getOperand(0));
12878
12879   // Zero out the upper parts of the register.
12880   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12881
12882   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12883                      DAG.getBitcast(MVT::v2f64, Load),
12884                      DAG.getIntPtrConstant(0, dl));
12885
12886   // Or the load with the bias.
12887   SDValue Or = DAG.getNode(
12888       ISD::OR, dl, MVT::v2i64,
12889       DAG.getBitcast(MVT::v2i64,
12890                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12891       DAG.getBitcast(MVT::v2i64,
12892                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12893   Or =
12894       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12895                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12896
12897   // Subtract the bias.
12898   // TODO: Are there any fast-math-flags to propagate here?
12899   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12900
12901   // Handle final rounding.
12902   MVT DestVT = Op.getSimpleValueType();
12903
12904   if (DestVT.bitsLT(MVT::f64))
12905     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12906                        DAG.getIntPtrConstant(0, dl));
12907   if (DestVT.bitsGT(MVT::f64))
12908     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12909
12910   // Handle final rounding.
12911   return Sub;
12912 }
12913
12914 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12915                                      const X86Subtarget &Subtarget) {
12916   // The algorithm is the following:
12917   // #ifdef __SSE4_1__
12918   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12919   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12920   //                                 (uint4) 0x53000000, 0xaa);
12921   // #else
12922   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12923   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12924   // #endif
12925   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12926   //     return (float4) lo + fhi;
12927
12928   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12929   // reassociate the two FADDs, and if we do that, the algorithm fails
12930   // spectacularly (PR24512).
12931   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12932   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12933   // there's also the MachineCombiner reassociations happening on Machine IR.
12934   if (DAG.getTarget().Options.UnsafeFPMath)
12935     return SDValue();
12936
12937   SDLoc DL(Op);
12938   SDValue V = Op->getOperand(0);
12939   MVT VecIntVT = V.getSimpleValueType();
12940   bool Is128 = VecIntVT == MVT::v4i32;
12941   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12942   // If we convert to something else than the supported type, e.g., to v4f64,
12943   // abort early.
12944   if (VecFloatVT != Op->getSimpleValueType(0))
12945     return SDValue();
12946
12947   unsigned NumElts = VecIntVT.getVectorNumElements();
12948   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12949          "Unsupported custom type");
12950   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12951
12952   // In the #idef/#else code, we have in common:
12953   // - The vector of constants:
12954   // -- 0x4b000000
12955   // -- 0x53000000
12956   // - A shift:
12957   // -- v >> 16
12958
12959   // Create the splat vector for 0x4b000000.
12960   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12961   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12962                            CstLow, CstLow, CstLow, CstLow};
12963   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12964                                   makeArrayRef(&CstLowArray[0], NumElts));
12965   // Create the splat vector for 0x53000000.
12966   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12967   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12968                             CstHigh, CstHigh, CstHigh, CstHigh};
12969   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12970                                    makeArrayRef(&CstHighArray[0], NumElts));
12971
12972   // Create the right shift.
12973   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12974   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12975                              CstShift, CstShift, CstShift, CstShift};
12976   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12977                                     makeArrayRef(&CstShiftArray[0], NumElts));
12978   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12979
12980   SDValue Low, High;
12981   if (Subtarget.hasSSE41()) {
12982     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12983     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12984     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12985     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12986     // Low will be bitcasted right away, so do not bother bitcasting back to its
12987     // original type.
12988     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12989                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12990     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12991     //                                 (uint4) 0x53000000, 0xaa);
12992     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12993     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12994     // High will be bitcasted right away, so do not bother bitcasting back to
12995     // its original type.
12996     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12997                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12998   } else {
12999     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
13000     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
13001                                      CstMask, CstMask, CstMask);
13002     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13003     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
13004     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
13005
13006     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13007     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
13008   }
13009
13010   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
13011   SDValue CstFAdd = DAG.getConstantFP(
13012       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
13013   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
13014                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
13015   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
13016                                    makeArrayRef(&CstFAddArray[0], NumElts));
13017
13018   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13019   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
13020   // TODO: Are there any fast-math-flags to propagate here?
13021   SDValue FHigh =
13022       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
13023   //     return (float4) lo + fhi;
13024   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
13025   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
13026 }
13027
13028 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13029                                                SelectionDAG &DAG) const {
13030   SDValue N0 = Op.getOperand(0);
13031   MVT SVT = N0.getSimpleValueType();
13032   SDLoc dl(Op);
13033
13034   switch (SVT.SimpleTy) {
13035   default:
13036     llvm_unreachable("Custom UINT_TO_FP is not supported!");
13037   case MVT::v4i8:
13038   case MVT::v4i16:
13039   case MVT::v8i8:
13040   case MVT::v8i16: {
13041     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13042     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13043                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13044   }
13045   case MVT::v4i32:
13046   case MVT::v8i32:
13047     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13048   case MVT::v16i8:
13049   case MVT::v16i16:
13050     assert(Subtarget->hasAVX512());
13051     return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
13052                        DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
13053   }
13054 }
13055
13056 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13057                                            SelectionDAG &DAG) const {
13058   SDValue N0 = Op.getOperand(0);
13059   SDLoc dl(Op);
13060   auto PtrVT = getPointerTy(DAG.getDataLayout());
13061
13062   if (Op.getSimpleValueType().isVector())
13063     return lowerUINT_TO_FP_vec(Op, DAG);
13064
13065   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13066   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13067   // the optimization here.
13068   if (DAG.SignBitIsZero(N0))
13069     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13070
13071   MVT SrcVT = N0.getSimpleValueType();
13072   MVT DstVT = Op.getSimpleValueType();
13073
13074   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
13075       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
13076     // Conversions from unsigned i32 to f32/f64 are legal,
13077     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
13078     return Op;
13079   }
13080
13081   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13082     return LowerUINT_TO_FP_i64(Op, DAG);
13083   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13084     return LowerUINT_TO_FP_i32(Op, DAG);
13085   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13086     return SDValue();
13087
13088   // Make a 64-bit buffer, and use it to build an FILD.
13089   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13090   if (SrcVT == MVT::i32) {
13091     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
13092     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
13093     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13094                                   StackSlot, MachinePointerInfo(),
13095                                   false, false, 0);
13096     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
13097                                   OffsetSlot, MachinePointerInfo(),
13098                                   false, false, 0);
13099     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13100     return Fild;
13101   }
13102
13103   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13104   SDValue ValueToStore = Op.getOperand(0);
13105   if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget->is64Bit())
13106     // Bitcasting to f64 here allows us to do a single 64-bit store from
13107     // an SSE register, avoiding the store forwarding penalty that would come
13108     // with two 32-bit stores.
13109     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
13110   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, ValueToStore,
13111                                StackSlot, MachinePointerInfo(),
13112                                false, false, 0);
13113   // For i64 source, we need to add the appropriate power of 2 if the input
13114   // was negative.  This is the same as the optimization in
13115   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13116   // we must be careful to do the computation in x87 extended precision, not
13117   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13118   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13119   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13120       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13121       MachineMemOperand::MOLoad, 8, 8);
13122
13123   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13124   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13125   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13126                                          MVT::i64, MMO);
13127
13128   APInt FF(32, 0x5F800000ULL);
13129
13130   // Check whether the sign bit is set.
13131   SDValue SignSet = DAG.getSetCC(
13132       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
13133       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
13134
13135   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13136   SDValue FudgePtr = DAG.getConstantPool(
13137       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
13138
13139   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13140   SDValue Zero = DAG.getIntPtrConstant(0, dl);
13141   SDValue Four = DAG.getIntPtrConstant(4, dl);
13142   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13143                                Zero, Four);
13144   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
13145
13146   // Load the value out, extending it from f32 to f80.
13147   // FIXME: Avoid the extend by constructing the right constant pool?
13148   SDValue Fudge = DAG.getExtLoad(
13149       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
13150       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
13151       false, false, false, 4);
13152   // Extend everything to 80 bits to force it to be done on x87.
13153   // TODO: Are there any fast-math-flags to propagate here?
13154   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13155   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
13156                      DAG.getIntPtrConstant(0, dl));
13157 }
13158
13159 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
13160 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
13161 // just return an <SDValue(), SDValue()> pair.
13162 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
13163 // to i16, i32 or i64, and we lower it to a legal sequence.
13164 // If lowered to the final integer result we return a <result, SDValue()> pair.
13165 // Otherwise we lower it to a sequence ending with a FIST, return a
13166 // <FIST, StackSlot> pair, and the caller is responsible for loading
13167 // the final integer result from StackSlot.
13168 std::pair<SDValue,SDValue>
13169 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13170                                    bool IsSigned, bool IsReplace) const {
13171   SDLoc DL(Op);
13172
13173   EVT DstTy = Op.getValueType();
13174   EVT TheVT = Op.getOperand(0).getValueType();
13175   auto PtrVT = getPointerTy(DAG.getDataLayout());
13176
13177   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
13178     // f16 must be promoted before using the lowering in this routine.
13179     // fp128 does not use this lowering.
13180     return std::make_pair(SDValue(), SDValue());
13181   }
13182
13183   // If using FIST to compute an unsigned i64, we'll need some fixup
13184   // to handle values above the maximum signed i64.  A FIST is always
13185   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13186   bool UnsignedFixup = !IsSigned &&
13187                        DstTy == MVT::i64 &&
13188                        (!Subtarget->is64Bit() ||
13189                         !isScalarFPTypeInSSEReg(TheVT));
13190
13191   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
13192     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13193     // The low 32 bits of the fist result will have the correct uint32 result.
13194     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13195     DstTy = MVT::i64;
13196   }
13197
13198   assert(DstTy.getSimpleVT() <= MVT::i64 &&
13199          DstTy.getSimpleVT() >= MVT::i16 &&
13200          "Unknown FP_TO_INT to lower!");
13201
13202   // These are really Legal.
13203   if (DstTy == MVT::i32 &&
13204       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13205     return std::make_pair(SDValue(), SDValue());
13206   if (Subtarget->is64Bit() &&
13207       DstTy == MVT::i64 &&
13208       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13209     return std::make_pair(SDValue(), SDValue());
13210
13211   // We lower FP->int64 into FISTP64 followed by a load from a temporary
13212   // stack slot.
13213   MachineFunction &MF = DAG.getMachineFunction();
13214   unsigned MemSize = DstTy.getSizeInBits()/8;
13215   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13216   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13217
13218   unsigned Opc;
13219   switch (DstTy.getSimpleVT().SimpleTy) {
13220   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13221   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13222   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13223   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13224   }
13225
13226   SDValue Chain = DAG.getEntryNode();
13227   SDValue Value = Op.getOperand(0);
13228   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13229
13230   if (UnsignedFixup) {
13231     //
13232     // Conversion to unsigned i64 is implemented with a select,
13233     // depending on whether the source value fits in the range
13234     // of a signed i64.  Let Thresh be the FP equivalent of
13235     // 0x8000000000000000ULL.
13236     //
13237     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13238     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
13239     //  Fist-to-mem64 FistSrc
13240     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13241     //  to XOR'ing the high 32 bits with Adjust.
13242     //
13243     // Being a power of 2, Thresh is exactly representable in all FP formats.
13244     // For X87 we'd like to use the smallest FP type for this constant, but
13245     // for DAG type consistency we have to match the FP operand type.
13246
13247     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13248     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13249     bool LosesInfo = false;
13250     if (TheVT == MVT::f64)
13251       // The rounding mode is irrelevant as the conversion should be exact.
13252       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13253                               &LosesInfo);
13254     else if (TheVT == MVT::f80)
13255       Status = Thresh.convert(APFloat::x87DoubleExtended,
13256                               APFloat::rmNearestTiesToEven, &LosesInfo);
13257
13258     assert(Status == APFloat::opOK && !LosesInfo &&
13259            "FP conversion should have been exact");
13260
13261     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13262
13263     SDValue Cmp = DAG.getSetCC(DL,
13264                                getSetCCResultType(DAG.getDataLayout(),
13265                                                   *DAG.getContext(), TheVT),
13266                                Value, ThreshVal, ISD::SETLT);
13267     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13268                            DAG.getConstant(0, DL, MVT::i32),
13269                            DAG.getConstant(0x80000000, DL, MVT::i32));
13270     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13271     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13272                                               *DAG.getContext(), TheVT),
13273                        Value, ThreshVal, ISD::SETLT);
13274     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13275   }
13276
13277   // FIXME This causes a redundant load/store if the SSE-class value is already
13278   // in memory, such as if it is on the callstack.
13279   if (isScalarFPTypeInSSEReg(TheVT)) {
13280     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13281     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13282                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
13283                          false, 0);
13284     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13285     SDValue Ops[] = {
13286       Chain, StackSlot, DAG.getValueType(TheVT)
13287     };
13288
13289     MachineMemOperand *MMO =
13290         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13291                                 MachineMemOperand::MOLoad, MemSize, MemSize);
13292     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13293     Chain = Value.getValue(1);
13294     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13295     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13296   }
13297
13298   MachineMemOperand *MMO =
13299       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13300                               MachineMemOperand::MOStore, MemSize, MemSize);
13301
13302   if (UnsignedFixup) {
13303
13304     // Insert the FIST, load its result as two i32's,
13305     // and XOR the high i32 with Adjust.
13306
13307     SDValue FistOps[] = { Chain, Value, StackSlot };
13308     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13309                                            FistOps, DstTy, MMO);
13310
13311     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13312                                 MachinePointerInfo(),
13313                                 false, false, false, 0);
13314     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13315                                    DAG.getConstant(4, DL, PtrVT));
13316
13317     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13318                                  MachinePointerInfo(),
13319                                  false, false, false, 0);
13320     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13321
13322     if (Subtarget->is64Bit()) {
13323       // Join High32 and Low32 into a 64-bit result.
13324       // (High32 << 32) | Low32
13325       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13326       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13327       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13328                            DAG.getConstant(32, DL, MVT::i8));
13329       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13330       return std::make_pair(Result, SDValue());
13331     }
13332
13333     SDValue ResultOps[] = { Low32, High32 };
13334
13335     SDValue pair = IsReplace
13336       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13337       : DAG.getMergeValues(ResultOps, DL);
13338     return std::make_pair(pair, SDValue());
13339   } else {
13340     // Build the FP_TO_INT*_IN_MEM
13341     SDValue Ops[] = { Chain, Value, StackSlot };
13342     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13343                                            Ops, DstTy, MMO);
13344     return std::make_pair(FIST, StackSlot);
13345   }
13346 }
13347
13348 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13349                               const X86Subtarget *Subtarget) {
13350   MVT VT = Op->getSimpleValueType(0);
13351   SDValue In = Op->getOperand(0);
13352   MVT InVT = In.getSimpleValueType();
13353   SDLoc dl(Op);
13354
13355   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13356     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13357
13358   // Optimize vectors in AVX mode:
13359   //
13360   //   v8i16 -> v8i32
13361   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13362   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13363   //   Concat upper and lower parts.
13364   //
13365   //   v4i32 -> v4i64
13366   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13367   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13368   //   Concat upper and lower parts.
13369   //
13370
13371   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13372       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13373       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13374     return SDValue();
13375
13376   if (Subtarget->hasInt256())
13377     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13378
13379   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13380   SDValue Undef = DAG.getUNDEF(InVT);
13381   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13382   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13383   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13384
13385   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13386                              VT.getVectorNumElements()/2);
13387
13388   OpLo = DAG.getBitcast(HVT, OpLo);
13389   OpHi = DAG.getBitcast(HVT, OpHi);
13390
13391   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13392 }
13393
13394 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13395                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13396   MVT VT = Op->getSimpleValueType(0);
13397   SDValue In = Op->getOperand(0);
13398   MVT InVT = In.getSimpleValueType();
13399   SDLoc DL(Op);
13400   unsigned int NumElts = VT.getVectorNumElements();
13401   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13402     return SDValue();
13403
13404   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13405     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13406
13407   assert(InVT.getVectorElementType() == MVT::i1);
13408   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13409   SDValue One =
13410    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13411   SDValue Zero =
13412    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13413
13414   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13415   if (VT.is512BitVector())
13416     return V;
13417   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13418 }
13419
13420 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13421                                SelectionDAG &DAG) {
13422   if (Subtarget->hasFp256())
13423     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13424       return Res;
13425
13426   return SDValue();
13427 }
13428
13429 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13430                                 SelectionDAG &DAG) {
13431   SDLoc DL(Op);
13432   MVT VT = Op.getSimpleValueType();
13433   SDValue In = Op.getOperand(0);
13434   MVT SVT = In.getSimpleValueType();
13435
13436   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13437     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13438
13439   if (Subtarget->hasFp256())
13440     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13441       return Res;
13442
13443   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13444          VT.getVectorNumElements() != SVT.getVectorNumElements());
13445   return SDValue();
13446 }
13447
13448 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
13449                                   const X86Subtarget *Subtarget) {
13450
13451   SDLoc DL(Op);
13452   MVT VT = Op.getSimpleValueType();
13453   SDValue In = Op.getOperand(0);
13454   MVT InVT = In.getSimpleValueType();
13455
13456   assert(VT.getVectorElementType() == MVT::i1 && "Unexected vector type.");
13457
13458   // Shift LSB to MSB and use VPMOVB2M - SKX.
13459   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
13460   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13461          Subtarget->hasBWI()) ||     // legal, will go to VPMOVB2M, VPMOVW2M
13462       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13463              InVT.getScalarSizeInBits() <= 16 && Subtarget->hasBWI() &&
13464              Subtarget->hasVLX())) { // legal, will go to VPMOVB2M, VPMOVW2M
13465     // Shift packed bytes not supported natively, bitcast to dword
13466     MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
13467     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, ExtVT,
13468                                      DAG.getBitcast(ExtVT, In),
13469                                      DAG.getConstant(ShiftInx, DL, ExtVT));
13470     ShiftNode = DAG.getBitcast(InVT, ShiftNode);
13471     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13472   }
13473   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13474          Subtarget->hasDQI()) ||  // legal, will go to VPMOVD2M, VPMOVQ2M
13475       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13476          InVT.getScalarSizeInBits() >= 32 && Subtarget->hasDQI() &&
13477          Subtarget->hasVLX())) {  // legal, will go to VPMOVD2M, VPMOVQ2M
13478
13479     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13480                                      DAG.getConstant(ShiftInx, DL, InVT));
13481     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13482   }
13483
13484   // Shift LSB to MSB, extend if necessary and use TESTM.
13485   unsigned NumElts = InVT.getVectorNumElements();
13486   if (InVT.getSizeInBits() < 512 &&
13487       (InVT.getScalarType() == MVT::i8 || InVT.getScalarType() == MVT::i16 ||
13488        !Subtarget->hasVLX())) {
13489     assert((NumElts == 8 || NumElts == 16) && "Unexected vector type.");
13490
13491     // TESTD/Q should be used (if BW supported we use CVT2MASK above),
13492     // so vector should be extended to packed dword/qword.
13493     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(512/NumElts), NumElts);
13494     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13495     InVT = ExtVT;
13496     ShiftInx = InVT.getScalarSizeInBits() - 1;
13497   }
13498
13499   SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13500                                    DAG.getConstant(ShiftInx, DL, InVT));
13501   return DAG.getNode(X86ISD::TESTM, DL, VT, ShiftNode, ShiftNode);
13502 }
13503
13504 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13505   SDLoc DL(Op);
13506   MVT VT = Op.getSimpleValueType();
13507   SDValue In = Op.getOperand(0);
13508   MVT InVT = In.getSimpleValueType();
13509
13510   if (VT == MVT::i1) {
13511     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13512            "Invalid scalar TRUNCATE operation");
13513     if (InVT.getSizeInBits() >= 32)
13514       return SDValue();
13515     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13516     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13517   }
13518   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13519          "Invalid TRUNCATE operation");
13520
13521   if (VT.getVectorElementType() == MVT::i1)
13522     return LowerTruncateVecI1(Op, DAG, Subtarget);
13523
13524   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13525   if (Subtarget->hasAVX512()) {
13526     // word to byte only under BWI
13527     if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13528       return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13529                          DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13530     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13531   }
13532   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13533     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13534     if (Subtarget->hasInt256()) {
13535       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13536       In = DAG.getBitcast(MVT::v8i32, In);
13537       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13538                                 ShufMask);
13539       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13540                          DAG.getIntPtrConstant(0, DL));
13541     }
13542
13543     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13544                                DAG.getIntPtrConstant(0, DL));
13545     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13546                                DAG.getIntPtrConstant(2, DL));
13547     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13548     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13549     static const int ShufMask[] = {0, 2, 4, 6};
13550     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13551   }
13552
13553   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13554     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13555     if (Subtarget->hasInt256()) {
13556       In = DAG.getBitcast(MVT::v32i8, In);
13557
13558       SmallVector<SDValue,32> pshufbMask;
13559       for (unsigned i = 0; i < 2; ++i) {
13560         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13561         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13562         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13563         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13564         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13565         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13566         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13567         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13568         for (unsigned j = 0; j < 8; ++j)
13569           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13570       }
13571       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13572       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13573       In = DAG.getBitcast(MVT::v4i64, In);
13574
13575       static const int ShufMask[] = {0,  2,  -1,  -1};
13576       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13577                                 &ShufMask[0]);
13578       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13579                        DAG.getIntPtrConstant(0, DL));
13580       return DAG.getBitcast(VT, In);
13581     }
13582
13583     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13584                                DAG.getIntPtrConstant(0, DL));
13585
13586     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13587                                DAG.getIntPtrConstant(4, DL));
13588
13589     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13590     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13591
13592     // The PSHUFB mask:
13593     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13594                                    -1, -1, -1, -1, -1, -1, -1, -1};
13595
13596     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13597     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13598     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13599
13600     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13601     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13602
13603     // The MOVLHPS Mask:
13604     static const int ShufMask2[] = {0, 1, 4, 5};
13605     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13606     return DAG.getBitcast(MVT::v8i16, res);
13607   }
13608
13609   // Handle truncation of V256 to V128 using shuffles.
13610   if (!VT.is128BitVector() || !InVT.is256BitVector())
13611     return SDValue();
13612
13613   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13614
13615   unsigned NumElems = VT.getVectorNumElements();
13616   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13617
13618   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13619   // Prepare truncation shuffle mask
13620   for (unsigned i = 0; i != NumElems; ++i)
13621     MaskVec[i] = i * 2;
13622   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13623                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13624   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13625                      DAG.getIntPtrConstant(0, DL));
13626 }
13627
13628 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13629                                            SelectionDAG &DAG) const {
13630   assert(!Op.getSimpleValueType().isVector());
13631
13632   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13633     /*IsSigned=*/ true, /*IsReplace=*/ false);
13634   SDValue FIST = Vals.first, StackSlot = Vals.second;
13635   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13636   if (!FIST.getNode())
13637     return Op;
13638
13639   if (StackSlot.getNode())
13640     // Load the result.
13641     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13642                        FIST, StackSlot, MachinePointerInfo(),
13643                        false, false, false, 0);
13644
13645   // The node is the result.
13646   return FIST;
13647 }
13648
13649 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13650                                            SelectionDAG &DAG) const {
13651   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13652     /*IsSigned=*/ false, /*IsReplace=*/ false);
13653   SDValue FIST = Vals.first, StackSlot = Vals.second;
13654   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13655   if (!FIST.getNode())
13656     return Op;
13657
13658   if (StackSlot.getNode())
13659     // Load the result.
13660     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13661                        FIST, StackSlot, MachinePointerInfo(),
13662                        false, false, false, 0);
13663
13664   // The node is the result.
13665   return FIST;
13666 }
13667
13668 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13669   SDLoc DL(Op);
13670   MVT VT = Op.getSimpleValueType();
13671   SDValue In = Op.getOperand(0);
13672   MVT SVT = In.getSimpleValueType();
13673
13674   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13675
13676   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13677                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13678                                  In, DAG.getUNDEF(SVT)));
13679 }
13680
13681 /// The only differences between FABS and FNEG are the mask and the logic op.
13682 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13683 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13684   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13685          "Wrong opcode for lowering FABS or FNEG.");
13686
13687   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13688
13689   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13690   // into an FNABS. We'll lower the FABS after that if it is still in use.
13691   if (IsFABS)
13692     for (SDNode *User : Op->uses())
13693       if (User->getOpcode() == ISD::FNEG)
13694         return Op;
13695
13696   SDLoc dl(Op);
13697   MVT VT = Op.getSimpleValueType();
13698
13699   bool IsF128 = (VT == MVT::f128);
13700
13701   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13702   // decide if we should generate a 16-byte constant mask when we only need 4 or
13703   // 8 bytes for the scalar case.
13704
13705   MVT LogicVT;
13706   MVT EltVT;
13707   unsigned NumElts;
13708
13709   if (VT.isVector()) {
13710     LogicVT = VT;
13711     EltVT = VT.getVectorElementType();
13712     NumElts = VT.getVectorNumElements();
13713   } else if (IsF128) {
13714     // SSE instructions are used for optimized f128 logical operations.
13715     LogicVT = MVT::f128;
13716     EltVT = VT;
13717     NumElts = 1;
13718   } else {
13719     // There are no scalar bitwise logical SSE/AVX instructions, so we
13720     // generate a 16-byte vector constant and logic op even for the scalar case.
13721     // Using a 16-byte mask allows folding the load of the mask with
13722     // the logic op, so it can save (~4 bytes) on code size.
13723     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13724     EltVT = VT;
13725     NumElts = (VT == MVT::f64) ? 2 : 4;
13726   }
13727
13728   unsigned EltBits = EltVT.getSizeInBits();
13729   LLVMContext *Context = DAG.getContext();
13730   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13731   APInt MaskElt =
13732     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13733   Constant *C = ConstantInt::get(*Context, MaskElt);
13734   C = ConstantVector::getSplat(NumElts, C);
13735   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13736   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13737   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13738   SDValue Mask =
13739       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13740                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13741                   false, false, false, Alignment);
13742
13743   SDValue Op0 = Op.getOperand(0);
13744   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13745   unsigned LogicOp =
13746     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13747   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13748
13749   if (VT.isVector() || IsF128)
13750     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13751
13752   // For the scalar case extend to a 128-bit vector, perform the logic op,
13753   // and extract the scalar result back out.
13754   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13755   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13756   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13757                      DAG.getIntPtrConstant(0, dl));
13758 }
13759
13760 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13761   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13762   LLVMContext *Context = DAG.getContext();
13763   SDValue Op0 = Op.getOperand(0);
13764   SDValue Op1 = Op.getOperand(1);
13765   SDLoc dl(Op);
13766   MVT VT = Op.getSimpleValueType();
13767   MVT SrcVT = Op1.getSimpleValueType();
13768   bool IsF128 = (VT == MVT::f128);
13769
13770   // If second operand is smaller, extend it first.
13771   if (SrcVT.bitsLT(VT)) {
13772     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13773     SrcVT = VT;
13774   }
13775   // And if it is bigger, shrink it first.
13776   if (SrcVT.bitsGT(VT)) {
13777     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13778     SrcVT = VT;
13779   }
13780
13781   // At this point the operands and the result should have the same
13782   // type, and that won't be f80 since that is not custom lowered.
13783   assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13784          "Unexpected type in LowerFCOPYSIGN");
13785
13786   const fltSemantics &Sem =
13787       VT == MVT::f64 ? APFloat::IEEEdouble :
13788           (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13789   const unsigned SizeInBits = VT.getSizeInBits();
13790
13791   SmallVector<Constant *, 4> CV(
13792       VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13793       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13794
13795   // First, clear all bits but the sign bit from the second operand (sign).
13796   CV[0] = ConstantFP::get(*Context,
13797                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13798   Constant *C = ConstantVector::get(CV);
13799   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13800   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13801
13802   // Perform all logic operations as 16-byte vectors because there are no
13803   // scalar FP logic instructions in SSE. This allows load folding of the
13804   // constants into the logic instructions.
13805   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13806   SDValue Mask1 =
13807       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13808                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13809                   false, false, false, 16);
13810   if (!IsF128)
13811     Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13812   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13813
13814   // Next, clear the sign bit from the first operand (magnitude).
13815   // If it's a constant, we can clear it here.
13816   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13817     APFloat APF = Op0CN->getValueAPF();
13818     // If the magnitude is a positive zero, the sign bit alone is enough.
13819     if (APF.isPosZero())
13820       return IsF128 ? SignBit :
13821           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13822                       DAG.getIntPtrConstant(0, dl));
13823     APF.clearSign();
13824     CV[0] = ConstantFP::get(*Context, APF);
13825   } else {
13826     CV[0] = ConstantFP::get(
13827         *Context,
13828         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13829   }
13830   C = ConstantVector::get(CV);
13831   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13832   SDValue Val =
13833       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13834                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13835                   false, false, false, 16);
13836   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13837   if (!isa<ConstantFPSDNode>(Op0)) {
13838     if (!IsF128)
13839       Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13840     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13841   }
13842   // OR the magnitude value with the sign bit.
13843   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13844   return IsF128 ? Val :
13845       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13846                   DAG.getIntPtrConstant(0, dl));
13847 }
13848
13849 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13850   SDValue N0 = Op.getOperand(0);
13851   SDLoc dl(Op);
13852   MVT VT = Op.getSimpleValueType();
13853
13854   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13855   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13856                                   DAG.getConstant(1, dl, VT));
13857   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13858 }
13859
13860 // Check whether an OR'd tree is PTEST-able.
13861 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13862                                       SelectionDAG &DAG) {
13863   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13864
13865   if (!Subtarget->hasSSE41())
13866     return SDValue();
13867
13868   if (!Op->hasOneUse())
13869     return SDValue();
13870
13871   SDNode *N = Op.getNode();
13872   SDLoc DL(N);
13873
13874   SmallVector<SDValue, 8> Opnds;
13875   DenseMap<SDValue, unsigned> VecInMap;
13876   SmallVector<SDValue, 8> VecIns;
13877   EVT VT = MVT::Other;
13878
13879   // Recognize a special case where a vector is casted into wide integer to
13880   // test all 0s.
13881   Opnds.push_back(N->getOperand(0));
13882   Opnds.push_back(N->getOperand(1));
13883
13884   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13885     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13886     // BFS traverse all OR'd operands.
13887     if (I->getOpcode() == ISD::OR) {
13888       Opnds.push_back(I->getOperand(0));
13889       Opnds.push_back(I->getOperand(1));
13890       // Re-evaluate the number of nodes to be traversed.
13891       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13892       continue;
13893     }
13894
13895     // Quit if a non-EXTRACT_VECTOR_ELT
13896     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13897       return SDValue();
13898
13899     // Quit if without a constant index.
13900     SDValue Idx = I->getOperand(1);
13901     if (!isa<ConstantSDNode>(Idx))
13902       return SDValue();
13903
13904     SDValue ExtractedFromVec = I->getOperand(0);
13905     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13906     if (M == VecInMap.end()) {
13907       VT = ExtractedFromVec.getValueType();
13908       // Quit if not 128/256-bit vector.
13909       if (!VT.is128BitVector() && !VT.is256BitVector())
13910         return SDValue();
13911       // Quit if not the same type.
13912       if (VecInMap.begin() != VecInMap.end() &&
13913           VT != VecInMap.begin()->first.getValueType())
13914         return SDValue();
13915       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13916       VecIns.push_back(ExtractedFromVec);
13917     }
13918     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13919   }
13920
13921   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13922          "Not extracted from 128-/256-bit vector.");
13923
13924   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13925
13926   for (DenseMap<SDValue, unsigned>::const_iterator
13927         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13928     // Quit if not all elements are used.
13929     if (I->second != FullMask)
13930       return SDValue();
13931   }
13932
13933   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13934
13935   // Cast all vectors into TestVT for PTEST.
13936   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13937     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13938
13939   // If more than one full vectors are evaluated, OR them first before PTEST.
13940   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13941     // Each iteration will OR 2 nodes and append the result until there is only
13942     // 1 node left, i.e. the final OR'd value of all vectors.
13943     SDValue LHS = VecIns[Slot];
13944     SDValue RHS = VecIns[Slot + 1];
13945     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13946   }
13947
13948   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13949                      VecIns.back(), VecIns.back());
13950 }
13951
13952 /// \brief return true if \c Op has a use that doesn't just read flags.
13953 static bool hasNonFlagsUse(SDValue Op) {
13954   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13955        ++UI) {
13956     SDNode *User = *UI;
13957     unsigned UOpNo = UI.getOperandNo();
13958     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13959       // Look pass truncate.
13960       UOpNo = User->use_begin().getOperandNo();
13961       User = *User->use_begin();
13962     }
13963
13964     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13965         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13966       return true;
13967   }
13968   return false;
13969 }
13970
13971 /// Emit nodes that will be selected as "test Op0,Op0", or something
13972 /// equivalent.
13973 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13974                                     SelectionDAG &DAG) const {
13975   if (Op.getValueType() == MVT::i1) {
13976     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13977     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13978                        DAG.getConstant(0, dl, MVT::i8));
13979   }
13980   // CF and OF aren't always set the way we want. Determine which
13981   // of these we need.
13982   bool NeedCF = false;
13983   bool NeedOF = false;
13984   switch (X86CC) {
13985   default: break;
13986   case X86::COND_A: case X86::COND_AE:
13987   case X86::COND_B: case X86::COND_BE:
13988     NeedCF = true;
13989     break;
13990   case X86::COND_G: case X86::COND_GE:
13991   case X86::COND_L: case X86::COND_LE:
13992   case X86::COND_O: case X86::COND_NO: {
13993     // Check if we really need to set the
13994     // Overflow flag. If NoSignedWrap is present
13995     // that is not actually needed.
13996     switch (Op->getOpcode()) {
13997     case ISD::ADD:
13998     case ISD::SUB:
13999     case ISD::MUL:
14000     case ISD::SHL: {
14001       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
14002       if (BinNode->Flags.hasNoSignedWrap())
14003         break;
14004     }
14005     default:
14006       NeedOF = true;
14007       break;
14008     }
14009     break;
14010   }
14011   }
14012   // See if we can use the EFLAGS value from the operand instead of
14013   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
14014   // we prove that the arithmetic won't overflow, we can't use OF or CF.
14015   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
14016     // Emit a CMP with 0, which is the TEST pattern.
14017     //if (Op.getValueType() == MVT::i1)
14018     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
14019     //                     DAG.getConstant(0, MVT::i1));
14020     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14021                        DAG.getConstant(0, dl, Op.getValueType()));
14022   }
14023   unsigned Opcode = 0;
14024   unsigned NumOperands = 0;
14025
14026   // Truncate operations may prevent the merge of the SETCC instruction
14027   // and the arithmetic instruction before it. Attempt to truncate the operands
14028   // of the arithmetic instruction and use a reduced bit-width instruction.
14029   bool NeedTruncation = false;
14030   SDValue ArithOp = Op;
14031   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14032     SDValue Arith = Op->getOperand(0);
14033     // Both the trunc and the arithmetic op need to have one user each.
14034     if (Arith->hasOneUse())
14035       switch (Arith.getOpcode()) {
14036         default: break;
14037         case ISD::ADD:
14038         case ISD::SUB:
14039         case ISD::AND:
14040         case ISD::OR:
14041         case ISD::XOR: {
14042           NeedTruncation = true;
14043           ArithOp = Arith;
14044         }
14045       }
14046   }
14047
14048   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14049   // which may be the result of a CAST.  We use the variable 'Op', which is the
14050   // non-casted variable when we check for possible users.
14051   switch (ArithOp.getOpcode()) {
14052   case ISD::ADD:
14053     // Due to an isel shortcoming, be conservative if this add is likely to be
14054     // selected as part of a load-modify-store instruction. When the root node
14055     // in a match is a store, isel doesn't know how to remap non-chain non-flag
14056     // uses of other nodes in the match, such as the ADD in this case. This
14057     // leads to the ADD being left around and reselected, with the result being
14058     // two adds in the output.  Alas, even if none our users are stores, that
14059     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
14060     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
14061     // climbing the DAG back to the root, and it doesn't seem to be worth the
14062     // effort.
14063     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14064          UE = Op.getNode()->use_end(); UI != UE; ++UI)
14065       if (UI->getOpcode() != ISD::CopyToReg &&
14066           UI->getOpcode() != ISD::SETCC &&
14067           UI->getOpcode() != ISD::STORE)
14068         goto default_case;
14069
14070     if (ConstantSDNode *C =
14071         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14072       // An add of one will be selected as an INC.
14073       if (C->isOne() && !Subtarget->slowIncDec()) {
14074         Opcode = X86ISD::INC;
14075         NumOperands = 1;
14076         break;
14077       }
14078
14079       // An add of negative one (subtract of one) will be selected as a DEC.
14080       if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
14081         Opcode = X86ISD::DEC;
14082         NumOperands = 1;
14083         break;
14084       }
14085     }
14086
14087     // Otherwise use a regular EFLAGS-setting add.
14088     Opcode = X86ISD::ADD;
14089     NumOperands = 2;
14090     break;
14091   case ISD::SHL:
14092   case ISD::SRL:
14093     // If we have a constant logical shift that's only used in a comparison
14094     // against zero turn it into an equivalent AND. This allows turning it into
14095     // a TEST instruction later.
14096     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14097         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14098       EVT VT = Op.getValueType();
14099       unsigned BitWidth = VT.getSizeInBits();
14100       unsigned ShAmt = Op->getConstantOperandVal(1);
14101       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14102         break;
14103       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14104                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14105                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14106       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14107         break;
14108       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14109                                 DAG.getConstant(Mask, dl, VT));
14110       DAG.ReplaceAllUsesWith(Op, New);
14111       Op = New;
14112     }
14113     break;
14114
14115   case ISD::AND:
14116     // If the primary and result isn't used, don't bother using X86ISD::AND,
14117     // because a TEST instruction will be better.
14118     if (!hasNonFlagsUse(Op))
14119       break;
14120     // FALL THROUGH
14121   case ISD::SUB:
14122   case ISD::OR:
14123   case ISD::XOR:
14124     // Due to the ISEL shortcoming noted above, be conservative if this op is
14125     // likely to be selected as part of a load-modify-store instruction.
14126     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14127            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14128       if (UI->getOpcode() == ISD::STORE)
14129         goto default_case;
14130
14131     // Otherwise use a regular EFLAGS-setting instruction.
14132     switch (ArithOp.getOpcode()) {
14133     default: llvm_unreachable("unexpected operator!");
14134     case ISD::SUB: Opcode = X86ISD::SUB; break;
14135     case ISD::XOR: Opcode = X86ISD::XOR; break;
14136     case ISD::AND: Opcode = X86ISD::AND; break;
14137     case ISD::OR: {
14138       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14139         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14140         if (EFLAGS.getNode())
14141           return EFLAGS;
14142       }
14143       Opcode = X86ISD::OR;
14144       break;
14145     }
14146     }
14147
14148     NumOperands = 2;
14149     break;
14150   case X86ISD::ADD:
14151   case X86ISD::SUB:
14152   case X86ISD::INC:
14153   case X86ISD::DEC:
14154   case X86ISD::OR:
14155   case X86ISD::XOR:
14156   case X86ISD::AND:
14157     return SDValue(Op.getNode(), 1);
14158   default:
14159   default_case:
14160     break;
14161   }
14162
14163   // If we found that truncation is beneficial, perform the truncation and
14164   // update 'Op'.
14165   if (NeedTruncation) {
14166     EVT VT = Op.getValueType();
14167     SDValue WideVal = Op->getOperand(0);
14168     EVT WideVT = WideVal.getValueType();
14169     unsigned ConvertedOp = 0;
14170     // Use a target machine opcode to prevent further DAGCombine
14171     // optimizations that may separate the arithmetic operations
14172     // from the setcc node.
14173     switch (WideVal.getOpcode()) {
14174       default: break;
14175       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14176       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14177       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14178       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14179       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14180     }
14181
14182     if (ConvertedOp) {
14183       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14184       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14185         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14186         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14187         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14188       }
14189     }
14190   }
14191
14192   if (Opcode == 0)
14193     // Emit a CMP with 0, which is the TEST pattern.
14194     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14195                        DAG.getConstant(0, dl, Op.getValueType()));
14196
14197   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14198   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
14199
14200   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14201   DAG.ReplaceAllUsesWith(Op, New);
14202   return SDValue(New.getNode(), 1);
14203 }
14204
14205 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14206 /// equivalent.
14207 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14208                                    SDLoc dl, SelectionDAG &DAG) const {
14209   if (isNullConstant(Op1))
14210     return EmitTest(Op0, X86CC, dl, DAG);
14211
14212   assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14213          "Unexpected comparison operation for MVT::i1 operands");
14214
14215   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14216        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14217     // Do the comparison at i32 if it's smaller, besides the Atom case.
14218     // This avoids subregister aliasing issues. Keep the smaller reference
14219     // if we're optimizing for size, however, as that'll allow better folding
14220     // of memory operations.
14221     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14222         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14223         !Subtarget->isAtom()) {
14224       unsigned ExtendOp =
14225           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14226       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14227       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14228     }
14229     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14230     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14231     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14232                               Op0, Op1);
14233     return SDValue(Sub.getNode(), 1);
14234   }
14235   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14236 }
14237
14238 /// Convert a comparison if required by the subtarget.
14239 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14240                                                  SelectionDAG &DAG) const {
14241   // If the subtarget does not support the FUCOMI instruction, floating-point
14242   // comparisons have to be converted.
14243   if (Subtarget->hasCMov() ||
14244       Cmp.getOpcode() != X86ISD::CMP ||
14245       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14246       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14247     return Cmp;
14248
14249   // The instruction selector will select an FUCOM instruction instead of
14250   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14251   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14252   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14253   SDLoc dl(Cmp);
14254   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14255   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14256   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14257                             DAG.getConstant(8, dl, MVT::i8));
14258   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14259
14260   // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14261   assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14262   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14263 }
14264
14265 /// The minimum architected relative accuracy is 2^-12. We need one
14266 /// Newton-Raphson step to have a good float result (24 bits of precision).
14267 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14268                                             DAGCombinerInfo &DCI,
14269                                             unsigned &RefinementSteps,
14270                                             bool &UseOneConstNR) const {
14271   EVT VT = Op.getValueType();
14272   const char *RecipOp;
14273
14274   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14275   // TODO: Add support for AVX512 (v16f32).
14276   // It is likely not profitable to do this for f64 because a double-precision
14277   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14278   // instructions: convert to single, rsqrtss, convert back to double, refine
14279   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14280   // along with FMA, this could be a throughput win.
14281   if (VT == MVT::f32 && Subtarget->hasSSE1())
14282     RecipOp = "sqrtf";
14283   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14284            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14285     RecipOp = "vec-sqrtf";
14286   else
14287     return SDValue();
14288
14289   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14290   if (!Recips.isEnabled(RecipOp))
14291     return SDValue();
14292
14293   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14294   UseOneConstNR = false;
14295   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14296 }
14297
14298 /// The minimum architected relative accuracy is 2^-12. We need one
14299 /// Newton-Raphson step to have a good float result (24 bits of precision).
14300 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14301                                             DAGCombinerInfo &DCI,
14302                                             unsigned &RefinementSteps) const {
14303   EVT VT = Op.getValueType();
14304   const char *RecipOp;
14305
14306   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14307   // TODO: Add support for AVX512 (v16f32).
14308   // It is likely not profitable to do this for f64 because a double-precision
14309   // reciprocal estimate with refinement on x86 prior to FMA requires
14310   // 15 instructions: convert to single, rcpss, convert back to double, refine
14311   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14312   // along with FMA, this could be a throughput win.
14313   if (VT == MVT::f32 && Subtarget->hasSSE1())
14314     RecipOp = "divf";
14315   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14316            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14317     RecipOp = "vec-divf";
14318   else
14319     return SDValue();
14320
14321   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14322   if (!Recips.isEnabled(RecipOp))
14323     return SDValue();
14324
14325   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14326   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14327 }
14328
14329 /// If we have at least two divisions that use the same divisor, convert to
14330 /// multplication by a reciprocal. This may need to be adjusted for a given
14331 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14332 /// This is because we still need one division to calculate the reciprocal and
14333 /// then we need two multiplies by that reciprocal as replacements for the
14334 /// original divisions.
14335 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14336   return 2;
14337 }
14338
14339 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14340 /// if it's possible.
14341 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14342                                      SDLoc dl, SelectionDAG &DAG) const {
14343   SDValue Op0 = And.getOperand(0);
14344   SDValue Op1 = And.getOperand(1);
14345   if (Op0.getOpcode() == ISD::TRUNCATE)
14346     Op0 = Op0.getOperand(0);
14347   if (Op1.getOpcode() == ISD::TRUNCATE)
14348     Op1 = Op1.getOperand(0);
14349
14350   SDValue LHS, RHS;
14351   if (Op1.getOpcode() == ISD::SHL)
14352     std::swap(Op0, Op1);
14353   if (Op0.getOpcode() == ISD::SHL) {
14354     if (isOneConstant(Op0.getOperand(0))) {
14355         // If we looked past a truncate, check that it's only truncating away
14356         // known zeros.
14357         unsigned BitWidth = Op0.getValueSizeInBits();
14358         unsigned AndBitWidth = And.getValueSizeInBits();
14359         if (BitWidth > AndBitWidth) {
14360           APInt Zeros, Ones;
14361           DAG.computeKnownBits(Op0, Zeros, Ones);
14362           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14363             return SDValue();
14364         }
14365         LHS = Op1;
14366         RHS = Op0.getOperand(1);
14367       }
14368   } else if (Op1.getOpcode() == ISD::Constant) {
14369     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14370     uint64_t AndRHSVal = AndRHS->getZExtValue();
14371     SDValue AndLHS = Op0;
14372
14373     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14374       LHS = AndLHS.getOperand(0);
14375       RHS = AndLHS.getOperand(1);
14376     }
14377
14378     // Use BT if the immediate can't be encoded in a TEST instruction.
14379     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14380       LHS = AndLHS;
14381       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14382     }
14383   }
14384
14385   if (LHS.getNode()) {
14386     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
14387     // instruction.  Since the shift amount is in-range-or-undefined, we know
14388     // that doing a bittest on the i32 value is ok.  We extend to i32 because
14389     // the encoding for the i16 version is larger than the i32 version.
14390     // Also promote i16 to i32 for performance / code size reason.
14391     if (LHS.getValueType() == MVT::i8 ||
14392         LHS.getValueType() == MVT::i16)
14393       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14394
14395     // If the operand types disagree, extend the shift amount to match.  Since
14396     // BT ignores high bits (like shifts) we can use anyextend.
14397     if (LHS.getValueType() != RHS.getValueType())
14398       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14399
14400     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14401     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14402     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14403                        DAG.getConstant(Cond, dl, MVT::i8), BT);
14404   }
14405
14406   return SDValue();
14407 }
14408
14409 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14410 /// mask CMPs.
14411 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14412                               SDValue &Op1) {
14413   unsigned SSECC;
14414   bool Swap = false;
14415
14416   // SSE Condition code mapping:
14417   //  0 - EQ
14418   //  1 - LT
14419   //  2 - LE
14420   //  3 - UNORD
14421   //  4 - NEQ
14422   //  5 - NLT
14423   //  6 - NLE
14424   //  7 - ORD
14425   switch (SetCCOpcode) {
14426   default: llvm_unreachable("Unexpected SETCC condition");
14427   case ISD::SETOEQ:
14428   case ISD::SETEQ:  SSECC = 0; break;
14429   case ISD::SETOGT:
14430   case ISD::SETGT:  Swap = true; // Fallthrough
14431   case ISD::SETLT:
14432   case ISD::SETOLT: SSECC = 1; break;
14433   case ISD::SETOGE:
14434   case ISD::SETGE:  Swap = true; // Fallthrough
14435   case ISD::SETLE:
14436   case ISD::SETOLE: SSECC = 2; break;
14437   case ISD::SETUO:  SSECC = 3; break;
14438   case ISD::SETUNE:
14439   case ISD::SETNE:  SSECC = 4; break;
14440   case ISD::SETULE: Swap = true; // Fallthrough
14441   case ISD::SETUGE: SSECC = 5; break;
14442   case ISD::SETULT: Swap = true; // Fallthrough
14443   case ISD::SETUGT: SSECC = 6; break;
14444   case ISD::SETO:   SSECC = 7; break;
14445   case ISD::SETUEQ:
14446   case ISD::SETONE: SSECC = 8; break;
14447   }
14448   if (Swap)
14449     std::swap(Op0, Op1);
14450
14451   return SSECC;
14452 }
14453
14454 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14455 // ones, and then concatenate the result back.
14456 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14457   MVT VT = Op.getSimpleValueType();
14458
14459   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14460          "Unsupported value type for operation");
14461
14462   unsigned NumElems = VT.getVectorNumElements();
14463   SDLoc dl(Op);
14464   SDValue CC = Op.getOperand(2);
14465
14466   // Extract the LHS vectors
14467   SDValue LHS = Op.getOperand(0);
14468   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14469   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14470
14471   // Extract the RHS vectors
14472   SDValue RHS = Op.getOperand(1);
14473   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14474   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14475
14476   // Issue the operation on the smaller types and concatenate the result back
14477   MVT EltVT = VT.getVectorElementType();
14478   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14479   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14480                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14481                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14482 }
14483
14484 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14485   SDValue Op0 = Op.getOperand(0);
14486   SDValue Op1 = Op.getOperand(1);
14487   SDValue CC = Op.getOperand(2);
14488   MVT VT = Op.getSimpleValueType();
14489   SDLoc dl(Op);
14490
14491   assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14492          "Unexpected type for boolean compare operation");
14493   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14494   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14495                                DAG.getConstant(-1, dl, VT));
14496   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14497                                DAG.getConstant(-1, dl, VT));
14498   switch (SetCCOpcode) {
14499   default: llvm_unreachable("Unexpected SETCC condition");
14500   case ISD::SETEQ:
14501     // (x == y) -> ~(x ^ y)
14502     return DAG.getNode(ISD::XOR, dl, VT,
14503                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14504                        DAG.getConstant(-1, dl, VT));
14505   case ISD::SETNE:
14506     // (x != y) -> (x ^ y)
14507     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14508   case ISD::SETUGT:
14509   case ISD::SETGT:
14510     // (x > y) -> (x & ~y)
14511     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14512   case ISD::SETULT:
14513   case ISD::SETLT:
14514     // (x < y) -> (~x & y)
14515     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14516   case ISD::SETULE:
14517   case ISD::SETLE:
14518     // (x <= y) -> (~x | y)
14519     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14520   case ISD::SETUGE:
14521   case ISD::SETGE:
14522     // (x >=y) -> (x | ~y)
14523     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14524   }
14525 }
14526
14527 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14528                                      const X86Subtarget *Subtarget) {
14529   SDValue Op0 = Op.getOperand(0);
14530   SDValue Op1 = Op.getOperand(1);
14531   SDValue CC = Op.getOperand(2);
14532   MVT VT = Op.getSimpleValueType();
14533   SDLoc dl(Op);
14534
14535   assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14536          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14537          "Cannot set masked compare for this operation");
14538
14539   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14540   unsigned  Opc = 0;
14541   bool Unsigned = false;
14542   bool Swap = false;
14543   unsigned SSECC;
14544   switch (SetCCOpcode) {
14545   default: llvm_unreachable("Unexpected SETCC condition");
14546   case ISD::SETNE:  SSECC = 4; break;
14547   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14548   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14549   case ISD::SETLT:  Swap = true; //fall-through
14550   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14551   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14552   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14553   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14554   case ISD::SETULE: Unsigned = true; //fall-through
14555   case ISD::SETLE:  SSECC = 2; break;
14556   }
14557
14558   if (Swap)
14559     std::swap(Op0, Op1);
14560   if (Opc)
14561     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14562   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14563   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14564                      DAG.getConstant(SSECC, dl, MVT::i8));
14565 }
14566
14567 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14568 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14569 /// return an empty value.
14570 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14571 {
14572   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14573   if (!BV)
14574     return SDValue();
14575
14576   MVT VT = Op1.getSimpleValueType();
14577   MVT EVT = VT.getVectorElementType();
14578   unsigned n = VT.getVectorNumElements();
14579   SmallVector<SDValue, 8> ULTOp1;
14580
14581   for (unsigned i = 0; i < n; ++i) {
14582     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14583     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14584       return SDValue();
14585
14586     // Avoid underflow.
14587     APInt Val = Elt->getAPIntValue();
14588     if (Val == 0)
14589       return SDValue();
14590
14591     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14592   }
14593
14594   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14595 }
14596
14597 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14598                            SelectionDAG &DAG) {
14599   SDValue Op0 = Op.getOperand(0);
14600   SDValue Op1 = Op.getOperand(1);
14601   SDValue CC = Op.getOperand(2);
14602   MVT VT = Op.getSimpleValueType();
14603   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14604   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14605   SDLoc dl(Op);
14606
14607   if (isFP) {
14608 #ifndef NDEBUG
14609     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14610     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14611 #endif
14612
14613     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14614     unsigned Opc = X86ISD::CMPP;
14615     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14616       assert(VT.getVectorNumElements() <= 16);
14617       Opc = X86ISD::CMPM;
14618     }
14619     // In the two special cases we can't handle, emit two comparisons.
14620     if (SSECC == 8) {
14621       unsigned CC0, CC1;
14622       unsigned CombineOpc;
14623       if (SetCCOpcode == ISD::SETUEQ) {
14624         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14625       } else {
14626         assert(SetCCOpcode == ISD::SETONE);
14627         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14628       }
14629
14630       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14631                                  DAG.getConstant(CC0, dl, MVT::i8));
14632       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14633                                  DAG.getConstant(CC1, dl, MVT::i8));
14634       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14635     }
14636     // Handle all other FP comparisons here.
14637     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14638                        DAG.getConstant(SSECC, dl, MVT::i8));
14639   }
14640
14641   MVT VTOp0 = Op0.getSimpleValueType();
14642   assert(VTOp0 == Op1.getSimpleValueType() &&
14643          "Expected operands with same type!");
14644   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14645          "Invalid number of packed elements for source and destination!");
14646
14647   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14648     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14649     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14650     // legalizer firstly checks if the first operand in input to the setcc has
14651     // a legal type. If so, then it promotes the return type to that same type.
14652     // Otherwise, the return type is promoted to the 'next legal type' which,
14653     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14654     //
14655     // We reach this code only if the following two conditions are met:
14656     // 1. Both return type and operand type have been promoted to wider types
14657     //    by the type legalizer.
14658     // 2. The original operand type has been promoted to a 256-bit vector.
14659     //
14660     // Note that condition 2. only applies for AVX targets.
14661     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14662     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14663   }
14664
14665   // The non-AVX512 code below works under the assumption that source and
14666   // destination types are the same.
14667   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14668          "Value types for source and destination must be the same!");
14669
14670   // Break 256-bit integer vector compare into smaller ones.
14671   if (VT.is256BitVector() && !Subtarget->hasInt256())
14672     return Lower256IntVSETCC(Op, DAG);
14673
14674   MVT OpVT = Op1.getSimpleValueType();
14675   if (OpVT.getVectorElementType() == MVT::i1)
14676     return LowerBoolVSETCC_AVX512(Op, DAG);
14677
14678   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14679   if (Subtarget->hasAVX512()) {
14680     if (Op1.getSimpleValueType().is512BitVector() ||
14681         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14682         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14683       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14684
14685     // In AVX-512 architecture setcc returns mask with i1 elements,
14686     // But there is no compare instruction for i8 and i16 elements in KNL.
14687     // We are not talking about 512-bit operands in this case, these
14688     // types are illegal.
14689     if (MaskResult &&
14690         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14691          OpVT.getVectorElementType().getSizeInBits() >= 8))
14692       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14693                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14694   }
14695
14696   // Lower using XOP integer comparisons.
14697   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14698        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14699     // Translate compare code to XOP PCOM compare mode.
14700     unsigned CmpMode = 0;
14701     switch (SetCCOpcode) {
14702     default: llvm_unreachable("Unexpected SETCC condition");
14703     case ISD::SETULT:
14704     case ISD::SETLT: CmpMode = 0x00; break;
14705     case ISD::SETULE:
14706     case ISD::SETLE: CmpMode = 0x01; break;
14707     case ISD::SETUGT:
14708     case ISD::SETGT: CmpMode = 0x02; break;
14709     case ISD::SETUGE:
14710     case ISD::SETGE: CmpMode = 0x03; break;
14711     case ISD::SETEQ: CmpMode = 0x04; break;
14712     case ISD::SETNE: CmpMode = 0x05; break;
14713     }
14714
14715     // Are we comparing unsigned or signed integers?
14716     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14717       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14718
14719     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14720                        DAG.getConstant(CmpMode, dl, MVT::i8));
14721   }
14722
14723   // We are handling one of the integer comparisons here.  Since SSE only has
14724   // GT and EQ comparisons for integer, swapping operands and multiple
14725   // operations may be required for some comparisons.
14726   unsigned Opc;
14727   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14728   bool Subus = false;
14729
14730   switch (SetCCOpcode) {
14731   default: llvm_unreachable("Unexpected SETCC condition");
14732   case ISD::SETNE:  Invert = true;
14733   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14734   case ISD::SETLT:  Swap = true;
14735   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14736   case ISD::SETGE:  Swap = true;
14737   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14738                     Invert = true; break;
14739   case ISD::SETULT: Swap = true;
14740   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14741                     FlipSigns = true; break;
14742   case ISD::SETUGE: Swap = true;
14743   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14744                     FlipSigns = true; Invert = true; break;
14745   }
14746
14747   // Special case: Use min/max operations for SETULE/SETUGE
14748   MVT VET = VT.getVectorElementType();
14749   bool hasMinMax =
14750        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14751     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14752
14753   if (hasMinMax) {
14754     switch (SetCCOpcode) {
14755     default: break;
14756     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14757     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14758     }
14759
14760     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14761   }
14762
14763   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14764   if (!MinMax && hasSubus) {
14765     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14766     // Op0 u<= Op1:
14767     //   t = psubus Op0, Op1
14768     //   pcmpeq t, <0..0>
14769     switch (SetCCOpcode) {
14770     default: break;
14771     case ISD::SETULT: {
14772       // If the comparison is against a constant we can turn this into a
14773       // setule.  With psubus, setule does not require a swap.  This is
14774       // beneficial because the constant in the register is no longer
14775       // destructed as the destination so it can be hoisted out of a loop.
14776       // Only do this pre-AVX since vpcmp* is no longer destructive.
14777       if (Subtarget->hasAVX())
14778         break;
14779       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14780       if (ULEOp1.getNode()) {
14781         Op1 = ULEOp1;
14782         Subus = true; Invert = false; Swap = false;
14783       }
14784       break;
14785     }
14786     // Psubus is better than flip-sign because it requires no inversion.
14787     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14788     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14789     }
14790
14791     if (Subus) {
14792       Opc = X86ISD::SUBUS;
14793       FlipSigns = false;
14794     }
14795   }
14796
14797   if (Swap)
14798     std::swap(Op0, Op1);
14799
14800   // Check that the operation in question is available (most are plain SSE2,
14801   // but PCMPGTQ and PCMPEQQ have different requirements).
14802   if (VT == MVT::v2i64) {
14803     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14804       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14805
14806       // First cast everything to the right type.
14807       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14808       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14809
14810       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14811       // bits of the inputs before performing those operations. The lower
14812       // compare is always unsigned.
14813       SDValue SB;
14814       if (FlipSigns) {
14815         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14816       } else {
14817         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14818         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14819         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14820                          Sign, Zero, Sign, Zero);
14821       }
14822       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14823       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14824
14825       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14826       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14827       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14828
14829       // Create masks for only the low parts/high parts of the 64 bit integers.
14830       static const int MaskHi[] = { 1, 1, 3, 3 };
14831       static const int MaskLo[] = { 0, 0, 2, 2 };
14832       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14833       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14834       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14835
14836       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14837       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14838
14839       if (Invert)
14840         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14841
14842       return DAG.getBitcast(VT, Result);
14843     }
14844
14845     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14846       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14847       // pcmpeqd + pshufd + pand.
14848       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14849
14850       // First cast everything to the right type.
14851       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14852       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14853
14854       // Do the compare.
14855       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14856
14857       // Make sure the lower and upper halves are both all-ones.
14858       static const int Mask[] = { 1, 0, 3, 2 };
14859       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14860       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14861
14862       if (Invert)
14863         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14864
14865       return DAG.getBitcast(VT, Result);
14866     }
14867   }
14868
14869   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14870   // bits of the inputs before performing those operations.
14871   if (FlipSigns) {
14872     MVT EltVT = VT.getVectorElementType();
14873     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14874                                  VT);
14875     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14876     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14877   }
14878
14879   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14880
14881   // If the logical-not of the result is required, perform that now.
14882   if (Invert)
14883     Result = DAG.getNOT(dl, Result, VT);
14884
14885   if (MinMax)
14886     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14887
14888   if (Subus)
14889     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14890                          getZeroVector(VT, Subtarget, DAG, dl));
14891
14892   return Result;
14893 }
14894
14895 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14896
14897   MVT VT = Op.getSimpleValueType();
14898
14899   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14900
14901   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14902          && "SetCC type must be 8-bit or 1-bit integer");
14903   SDValue Op0 = Op.getOperand(0);
14904   SDValue Op1 = Op.getOperand(1);
14905   SDLoc dl(Op);
14906   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14907
14908   // Optimize to BT if possible.
14909   // Lower (X & (1 << N)) == 0 to BT(X, N).
14910   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14911   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14912   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14913       isNullConstant(Op1) &&
14914       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14915     if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14916       if (VT == MVT::i1)
14917         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14918       return NewSetCC;
14919     }
14920   }
14921
14922   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14923   // these.
14924   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14925       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14926
14927     // If the input is a setcc, then reuse the input setcc or use a new one with
14928     // the inverted condition.
14929     if (Op0.getOpcode() == X86ISD::SETCC) {
14930       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14931       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14932       if (!Invert)
14933         return Op0;
14934
14935       CCode = X86::GetOppositeBranchCondition(CCode);
14936       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14937                                   DAG.getConstant(CCode, dl, MVT::i8),
14938                                   Op0.getOperand(1));
14939       if (VT == MVT::i1)
14940         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14941       return SetCC;
14942     }
14943   }
14944   if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14945       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14946
14947     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14948     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14949   }
14950
14951   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14952   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14953   if (X86CC == X86::COND_INVALID)
14954     return SDValue();
14955
14956   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14957   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14958   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14959                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14960   if (VT == MVT::i1)
14961     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14962   return SetCC;
14963 }
14964
14965 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14966   SDValue LHS = Op.getOperand(0);
14967   SDValue RHS = Op.getOperand(1);
14968   SDValue Carry = Op.getOperand(2);
14969   SDValue Cond = Op.getOperand(3);
14970   SDLoc DL(Op);
14971
14972   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14973   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14974
14975   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14976   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14977   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14978   return DAG.getNode(X86ISD::SETCC, DL, Op.getValueType(),
14979                      DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14980 }
14981
14982 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14983 static bool isX86LogicalCmp(SDValue Op) {
14984   unsigned Opc = Op.getNode()->getOpcode();
14985   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14986       Opc == X86ISD::SAHF)
14987     return true;
14988   if (Op.getResNo() == 1 &&
14989       (Opc == X86ISD::ADD ||
14990        Opc == X86ISD::SUB ||
14991        Opc == X86ISD::ADC ||
14992        Opc == X86ISD::SBB ||
14993        Opc == X86ISD::SMUL ||
14994        Opc == X86ISD::UMUL ||
14995        Opc == X86ISD::INC ||
14996        Opc == X86ISD::DEC ||
14997        Opc == X86ISD::OR ||
14998        Opc == X86ISD::XOR ||
14999        Opc == X86ISD::AND))
15000     return true;
15001
15002   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
15003     return true;
15004
15005   return false;
15006 }
15007
15008 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
15009   if (V.getOpcode() != ISD::TRUNCATE)
15010     return false;
15011
15012   SDValue VOp0 = V.getOperand(0);
15013   unsigned InBits = VOp0.getValueSizeInBits();
15014   unsigned Bits = V.getValueSizeInBits();
15015   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
15016 }
15017
15018 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
15019   bool addTest = true;
15020   SDValue Cond  = Op.getOperand(0);
15021   SDValue Op1 = Op.getOperand(1);
15022   SDValue Op2 = Op.getOperand(2);
15023   SDLoc DL(Op);
15024   MVT VT = Op1.getSimpleValueType();
15025   SDValue CC;
15026
15027   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
15028   // are available or VBLENDV if AVX is available.
15029   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
15030   if (Cond.getOpcode() == ISD::SETCC &&
15031       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15032        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
15033       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
15034     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15035     int SSECC = translateX86FSETCC(
15036         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15037
15038     if (SSECC != 8) {
15039       if (Subtarget->hasAVX512()) {
15040         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15041                                   DAG.getConstant(SSECC, DL, MVT::i8));
15042         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15043       }
15044
15045       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15046                                 DAG.getConstant(SSECC, DL, MVT::i8));
15047
15048       // If we have AVX, we can use a variable vector select (VBLENDV) instead
15049       // of 3 logic instructions for size savings and potentially speed.
15050       // Unfortunately, there is no scalar form of VBLENDV.
15051
15052       // If either operand is a constant, don't try this. We can expect to
15053       // optimize away at least one of the logic instructions later in that
15054       // case, so that sequence would be faster than a variable blend.
15055
15056       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
15057       // uses XMM0 as the selection register. That may need just as many
15058       // instructions as the AND/ANDN/OR sequence due to register moves, so
15059       // don't bother.
15060
15061       if (Subtarget->hasAVX() &&
15062           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
15063
15064         // Convert to vectors, do a VSELECT, and convert back to scalar.
15065         // All of the conversions should be optimized away.
15066
15067         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
15068         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
15069         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
15070         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
15071
15072         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
15073         VCmp = DAG.getBitcast(VCmpVT, VCmp);
15074
15075         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
15076
15077         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
15078                            VSel, DAG.getIntPtrConstant(0, DL));
15079       }
15080       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15081       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15082       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15083     }
15084   }
15085
15086   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
15087     SDValue Op1Scalar;
15088     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
15089       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
15090     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
15091       Op1Scalar = Op1.getOperand(0);
15092     SDValue Op2Scalar;
15093     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
15094       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
15095     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
15096       Op2Scalar = Op2.getOperand(0);
15097     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
15098       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
15099                                       Op1Scalar.getValueType(),
15100                                       Cond, Op1Scalar, Op2Scalar);
15101       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
15102         return DAG.getBitcast(VT, newSelect);
15103       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
15104       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
15105                          DAG.getIntPtrConstant(0, DL));
15106     }
15107   }
15108
15109   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
15110     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
15111     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15112                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
15113     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15114                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
15115     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
15116                                     Cond, Op1, Op2);
15117     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
15118   }
15119
15120   if (Cond.getOpcode() == ISD::SETCC) {
15121     SDValue NewCond = LowerSETCC(Cond, DAG);
15122     if (NewCond.getNode())
15123       Cond = NewCond;
15124   }
15125
15126   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15127   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15128   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15129   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15130   if (Cond.getOpcode() == X86ISD::SETCC &&
15131       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15132       isNullConstant(Cond.getOperand(1).getOperand(1))) {
15133     SDValue Cmp = Cond.getOperand(1);
15134
15135     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15136
15137     if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15138         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15139       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
15140
15141       SDValue CmpOp0 = Cmp.getOperand(0);
15142       // Apply further optimizations for special cases
15143       // (select (x != 0), -1, 0) -> neg & sbb
15144       // (select (x == 0), 0, -1) -> neg & sbb
15145       if (isNullConstant(Y) &&
15146             (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
15147           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15148           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15149                                     DAG.getConstant(0, DL,
15150                                                     CmpOp0.getValueType()),
15151                                     CmpOp0);
15152           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15153                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
15154                                     SDValue(Neg.getNode(), 1));
15155           return Res;
15156         }
15157
15158       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15159                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
15160       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15161
15162       SDValue Res =   // Res = 0 or -1.
15163         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15164                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
15165
15166       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
15167         Res = DAG.getNOT(DL, Res, Res.getValueType());
15168
15169       if (!isNullConstant(Op2))
15170         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15171       return Res;
15172     }
15173   }
15174
15175   // Look past (and (setcc_carry (cmp ...)), 1).
15176   if (Cond.getOpcode() == ISD::AND &&
15177       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15178       isOneConstant(Cond.getOperand(1)))
15179     Cond = Cond.getOperand(0);
15180
15181   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15182   // setting operand in place of the X86ISD::SETCC.
15183   unsigned CondOpcode = Cond.getOpcode();
15184   if (CondOpcode == X86ISD::SETCC ||
15185       CondOpcode == X86ISD::SETCC_CARRY) {
15186     CC = Cond.getOperand(0);
15187
15188     SDValue Cmp = Cond.getOperand(1);
15189     unsigned Opc = Cmp.getOpcode();
15190     MVT VT = Op.getSimpleValueType();
15191
15192     bool IllegalFPCMov = false;
15193     if (VT.isFloatingPoint() && !VT.isVector() &&
15194         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15195       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15196
15197     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15198         Opc == X86ISD::BT) { // FIXME
15199       Cond = Cmp;
15200       addTest = false;
15201     }
15202   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15203              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15204              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15205               Cond.getOperand(0).getValueType() != MVT::i8)) {
15206     SDValue LHS = Cond.getOperand(0);
15207     SDValue RHS = Cond.getOperand(1);
15208     unsigned X86Opcode;
15209     unsigned X86Cond;
15210     SDVTList VTs;
15211     switch (CondOpcode) {
15212     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15213     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15214     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15215     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15216     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15217     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15218     default: llvm_unreachable("unexpected overflowing operator");
15219     }
15220     if (CondOpcode == ISD::UMULO)
15221       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15222                           MVT::i32);
15223     else
15224       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15225
15226     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15227
15228     if (CondOpcode == ISD::UMULO)
15229       Cond = X86Op.getValue(2);
15230     else
15231       Cond = X86Op.getValue(1);
15232
15233     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15234     addTest = false;
15235   }
15236
15237   if (addTest) {
15238     // Look past the truncate if the high bits are known zero.
15239     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15240       Cond = Cond.getOperand(0);
15241
15242     // We know the result of AND is compared against zero. Try to match
15243     // it to BT.
15244     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15245       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
15246         CC = NewSetCC.getOperand(0);
15247         Cond = NewSetCC.getOperand(1);
15248         addTest = false;
15249       }
15250     }
15251   }
15252
15253   if (addTest) {
15254     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
15255     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15256   }
15257
15258   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15259   // a <  b ?  0 : -1 -> RES = setcc_carry
15260   // a >= b ? -1 :  0 -> RES = setcc_carry
15261   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15262   if (Cond.getOpcode() == X86ISD::SUB) {
15263     Cond = ConvertCmpIfNecessary(Cond, DAG);
15264     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15265
15266     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15267         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15268         (isNullConstant(Op1) || isNullConstant(Op2))) {
15269       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15270                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15271                                 Cond);
15272       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15273         return DAG.getNOT(DL, Res, Res.getValueType());
15274       return Res;
15275     }
15276   }
15277
15278   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15279   // widen the cmov and push the truncate through. This avoids introducing a new
15280   // branch during isel and doesn't add any extensions.
15281   if (Op.getValueType() == MVT::i8 &&
15282       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15283     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15284     if (T1.getValueType() == T2.getValueType() &&
15285         // Blacklist CopyFromReg to avoid partial register stalls.
15286         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15287       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15288       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15289       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15290     }
15291   }
15292
15293   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15294   // condition is true.
15295   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15296   SDValue Ops[] = { Op2, Op1, CC, Cond };
15297   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15298 }
15299
15300 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15301                                        const X86Subtarget *Subtarget,
15302                                        SelectionDAG &DAG) {
15303   MVT VT = Op->getSimpleValueType(0);
15304   SDValue In = Op->getOperand(0);
15305   MVT InVT = In.getSimpleValueType();
15306   MVT VTElt = VT.getVectorElementType();
15307   MVT InVTElt = InVT.getVectorElementType();
15308   SDLoc dl(Op);
15309
15310   // SKX processor
15311   if ((InVTElt == MVT::i1) &&
15312       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15313         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15314
15315        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15316         VTElt.getSizeInBits() <= 16)) ||
15317
15318        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15319         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15320
15321        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15322         VTElt.getSizeInBits() >= 32))))
15323     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15324
15325   unsigned int NumElts = VT.getVectorNumElements();
15326
15327   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15328     return SDValue();
15329
15330   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15331     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15332       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15333     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15334   }
15335
15336   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15337   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15338   SDValue NegOne =
15339    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15340                    ExtVT);
15341   SDValue Zero =
15342    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15343
15344   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15345   if (VT.is512BitVector())
15346     return V;
15347   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15348 }
15349
15350 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15351                                              const X86Subtarget *Subtarget,
15352                                              SelectionDAG &DAG) {
15353   SDValue In = Op->getOperand(0);
15354   MVT VT = Op->getSimpleValueType(0);
15355   MVT InVT = In.getSimpleValueType();
15356   assert(VT.getSizeInBits() == InVT.getSizeInBits());
15357
15358   MVT InSVT = InVT.getVectorElementType();
15359   assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15360
15361   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15362     return SDValue();
15363   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15364     return SDValue();
15365
15366   SDLoc dl(Op);
15367
15368   // SSE41 targets can use the pmovsx* instructions directly.
15369   if (Subtarget->hasSSE41())
15370     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15371
15372   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15373   SDValue Curr = In;
15374   MVT CurrVT = InVT;
15375
15376   // As SRAI is only available on i16/i32 types, we expand only up to i32
15377   // and handle i64 separately.
15378   while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15379     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15380     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15381     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15382     Curr = DAG.getBitcast(CurrVT, Curr);
15383   }
15384
15385   SDValue SignExt = Curr;
15386   if (CurrVT != InVT) {
15387     unsigned SignExtShift =
15388         CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15389     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15390                           DAG.getConstant(SignExtShift, dl, MVT::i8));
15391   }
15392
15393   if (CurrVT == VT)
15394     return SignExt;
15395
15396   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15397     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15398                                DAG.getConstant(31, dl, MVT::i8));
15399     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15400     return DAG.getBitcast(VT, Ext);
15401   }
15402
15403   return SDValue();
15404 }
15405
15406 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15407                                 SelectionDAG &DAG) {
15408   MVT VT = Op->getSimpleValueType(0);
15409   SDValue In = Op->getOperand(0);
15410   MVT InVT = In.getSimpleValueType();
15411   SDLoc dl(Op);
15412
15413   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15414     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15415
15416   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15417       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15418       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15419     return SDValue();
15420
15421   if (Subtarget->hasInt256())
15422     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15423
15424   // Optimize vectors in AVX mode
15425   // Sign extend  v8i16 to v8i32 and
15426   //              v4i32 to v4i64
15427   //
15428   // Divide input vector into two parts
15429   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15430   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15431   // concat the vectors to original VT
15432
15433   unsigned NumElems = InVT.getVectorNumElements();
15434   SDValue Undef = DAG.getUNDEF(InVT);
15435
15436   SmallVector<int,8> ShufMask1(NumElems, -1);
15437   for (unsigned i = 0; i != NumElems/2; ++i)
15438     ShufMask1[i] = i;
15439
15440   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15441
15442   SmallVector<int,8> ShufMask2(NumElems, -1);
15443   for (unsigned i = 0; i != NumElems/2; ++i)
15444     ShufMask2[i] = i + NumElems/2;
15445
15446   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15447
15448   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15449                                 VT.getVectorNumElements()/2);
15450
15451   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15452   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15453
15454   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15455 }
15456
15457 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15458 // may emit an illegal shuffle but the expansion is still better than scalar
15459 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15460 // we'll emit a shuffle and a arithmetic shift.
15461 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15462 // TODO: It is possible to support ZExt by zeroing the undef values during
15463 // the shuffle phase or after the shuffle.
15464 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15465                                  SelectionDAG &DAG) {
15466   MVT RegVT = Op.getSimpleValueType();
15467   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15468   assert(RegVT.isInteger() &&
15469          "We only custom lower integer vector sext loads.");
15470
15471   // Nothing useful we can do without SSE2 shuffles.
15472   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15473
15474   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15475   SDLoc dl(Ld);
15476   EVT MemVT = Ld->getMemoryVT();
15477   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15478   unsigned RegSz = RegVT.getSizeInBits();
15479
15480   ISD::LoadExtType Ext = Ld->getExtensionType();
15481
15482   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15483          && "Only anyext and sext are currently implemented.");
15484   assert(MemVT != RegVT && "Cannot extend to the same type");
15485   assert(MemVT.isVector() && "Must load a vector from memory");
15486
15487   unsigned NumElems = RegVT.getVectorNumElements();
15488   unsigned MemSz = MemVT.getSizeInBits();
15489   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15490
15491   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15492     // The only way in which we have a legal 256-bit vector result but not the
15493     // integer 256-bit operations needed to directly lower a sextload is if we
15494     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15495     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15496     // correctly legalized. We do this late to allow the canonical form of
15497     // sextload to persist throughout the rest of the DAG combiner -- it wants
15498     // to fold together any extensions it can, and so will fuse a sign_extend
15499     // of an sextload into a sextload targeting a wider value.
15500     SDValue Load;
15501     if (MemSz == 128) {
15502       // Just switch this to a normal load.
15503       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15504                                        "it must be a legal 128-bit vector "
15505                                        "type!");
15506       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15507                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15508                   Ld->isInvariant(), Ld->getAlignment());
15509     } else {
15510       assert(MemSz < 128 &&
15511              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15512       // Do an sext load to a 128-bit vector type. We want to use the same
15513       // number of elements, but elements half as wide. This will end up being
15514       // recursively lowered by this routine, but will succeed as we definitely
15515       // have all the necessary features if we're using AVX1.
15516       EVT HalfEltVT =
15517           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15518       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15519       Load =
15520           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15521                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15522                          Ld->isNonTemporal(), Ld->isInvariant(),
15523                          Ld->getAlignment());
15524     }
15525
15526     // Replace chain users with the new chain.
15527     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15528     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15529
15530     // Finally, do a normal sign-extend to the desired register.
15531     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15532   }
15533
15534   // All sizes must be a power of two.
15535   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15536          "Non-power-of-two elements are not custom lowered!");
15537
15538   // Attempt to load the original value using scalar loads.
15539   // Find the largest scalar type that divides the total loaded size.
15540   MVT SclrLoadTy = MVT::i8;
15541   for (MVT Tp : MVT::integer_valuetypes()) {
15542     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15543       SclrLoadTy = Tp;
15544     }
15545   }
15546
15547   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15548   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15549       (64 <= MemSz))
15550     SclrLoadTy = MVT::f64;
15551
15552   // Calculate the number of scalar loads that we need to perform
15553   // in order to load our vector from memory.
15554   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15555
15556   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15557          "Can only lower sext loads with a single scalar load!");
15558
15559   unsigned loadRegZize = RegSz;
15560   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15561     loadRegZize = 128;
15562
15563   // Represent our vector as a sequence of elements which are the
15564   // largest scalar that we can load.
15565   EVT LoadUnitVecVT = EVT::getVectorVT(
15566       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15567
15568   // Represent the data using the same element type that is stored in
15569   // memory. In practice, we ''widen'' MemVT.
15570   EVT WideVecVT =
15571       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15572                        loadRegZize / MemVT.getScalarSizeInBits());
15573
15574   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15575          "Invalid vector type");
15576
15577   // We can't shuffle using an illegal type.
15578   assert(TLI.isTypeLegal(WideVecVT) &&
15579          "We only lower types that form legal widened vector types");
15580
15581   SmallVector<SDValue, 8> Chains;
15582   SDValue Ptr = Ld->getBasePtr();
15583   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15584                                       TLI.getPointerTy(DAG.getDataLayout()));
15585   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15586
15587   for (unsigned i = 0; i < NumLoads; ++i) {
15588     // Perform a single load.
15589     SDValue ScalarLoad =
15590         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15591                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15592                     Ld->getAlignment());
15593     Chains.push_back(ScalarLoad.getValue(1));
15594     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15595     // another round of DAGCombining.
15596     if (i == 0)
15597       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15598     else
15599       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15600                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15601
15602     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15603   }
15604
15605   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15606
15607   // Bitcast the loaded value to a vector of the original element type, in
15608   // the size of the target vector type.
15609   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15610   unsigned SizeRatio = RegSz / MemSz;
15611
15612   if (Ext == ISD::SEXTLOAD) {
15613     // If we have SSE4.1, we can directly emit a VSEXT node.
15614     if (Subtarget->hasSSE41()) {
15615       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15616       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15617       return Sext;
15618     }
15619
15620     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15621     // lanes.
15622     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15623            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15624
15625     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15626     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15627     return Shuff;
15628   }
15629
15630   // Redistribute the loaded elements into the different locations.
15631   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15632   for (unsigned i = 0; i != NumElems; ++i)
15633     ShuffleVec[i * SizeRatio] = i;
15634
15635   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15636                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15637
15638   // Bitcast to the requested type.
15639   Shuff = DAG.getBitcast(RegVT, Shuff);
15640   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15641   return Shuff;
15642 }
15643
15644 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15645 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15646 // from the AND / OR.
15647 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15648   Opc = Op.getOpcode();
15649   if (Opc != ISD::OR && Opc != ISD::AND)
15650     return false;
15651   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15652           Op.getOperand(0).hasOneUse() &&
15653           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15654           Op.getOperand(1).hasOneUse());
15655 }
15656
15657 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15658 // 1 and that the SETCC node has a single use.
15659 static bool isXor1OfSetCC(SDValue Op) {
15660   if (Op.getOpcode() != ISD::XOR)
15661     return false;
15662   if (isOneConstant(Op.getOperand(1)))
15663     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15664            Op.getOperand(0).hasOneUse();
15665   return false;
15666 }
15667
15668 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15669   bool addTest = true;
15670   SDValue Chain = Op.getOperand(0);
15671   SDValue Cond  = Op.getOperand(1);
15672   SDValue Dest  = Op.getOperand(2);
15673   SDLoc dl(Op);
15674   SDValue CC;
15675   bool Inverted = false;
15676
15677   if (Cond.getOpcode() == ISD::SETCC) {
15678     // Check for setcc([su]{add,sub,mul}o == 0).
15679     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15680         isNullConstant(Cond.getOperand(1)) &&
15681         Cond.getOperand(0).getResNo() == 1 &&
15682         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15683          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15684          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15685          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15686          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15687          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15688       Inverted = true;
15689       Cond = Cond.getOperand(0);
15690     } else {
15691       SDValue NewCond = LowerSETCC(Cond, DAG);
15692       if (NewCond.getNode())
15693         Cond = NewCond;
15694     }
15695   }
15696 #if 0
15697   // FIXME: LowerXALUO doesn't handle these!!
15698   else if (Cond.getOpcode() == X86ISD::ADD  ||
15699            Cond.getOpcode() == X86ISD::SUB  ||
15700            Cond.getOpcode() == X86ISD::SMUL ||
15701            Cond.getOpcode() == X86ISD::UMUL)
15702     Cond = LowerXALUO(Cond, DAG);
15703 #endif
15704
15705   // Look pass (and (setcc_carry (cmp ...)), 1).
15706   if (Cond.getOpcode() == ISD::AND &&
15707       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15708       isOneConstant(Cond.getOperand(1)))
15709     Cond = Cond.getOperand(0);
15710
15711   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15712   // setting operand in place of the X86ISD::SETCC.
15713   unsigned CondOpcode = Cond.getOpcode();
15714   if (CondOpcode == X86ISD::SETCC ||
15715       CondOpcode == X86ISD::SETCC_CARRY) {
15716     CC = Cond.getOperand(0);
15717
15718     SDValue Cmp = Cond.getOperand(1);
15719     unsigned Opc = Cmp.getOpcode();
15720     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15721     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15722       Cond = Cmp;
15723       addTest = false;
15724     } else {
15725       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15726       default: break;
15727       case X86::COND_O:
15728       case X86::COND_B:
15729         // These can only come from an arithmetic instruction with overflow,
15730         // e.g. SADDO, UADDO.
15731         Cond = Cond.getNode()->getOperand(1);
15732         addTest = false;
15733         break;
15734       }
15735     }
15736   }
15737   CondOpcode = Cond.getOpcode();
15738   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15739       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15740       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15741        Cond.getOperand(0).getValueType() != MVT::i8)) {
15742     SDValue LHS = Cond.getOperand(0);
15743     SDValue RHS = Cond.getOperand(1);
15744     unsigned X86Opcode;
15745     unsigned X86Cond;
15746     SDVTList VTs;
15747     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15748     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15749     // X86ISD::INC).
15750     switch (CondOpcode) {
15751     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15752     case ISD::SADDO:
15753       if (isOneConstant(RHS)) {
15754           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15755           break;
15756         }
15757       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15758     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15759     case ISD::SSUBO:
15760       if (isOneConstant(RHS)) {
15761           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15762           break;
15763         }
15764       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15765     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15766     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15767     default: llvm_unreachable("unexpected overflowing operator");
15768     }
15769     if (Inverted)
15770       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15771     if (CondOpcode == ISD::UMULO)
15772       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15773                           MVT::i32);
15774     else
15775       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15776
15777     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15778
15779     if (CondOpcode == ISD::UMULO)
15780       Cond = X86Op.getValue(2);
15781     else
15782       Cond = X86Op.getValue(1);
15783
15784     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15785     addTest = false;
15786   } else {
15787     unsigned CondOpc;
15788     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15789       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15790       if (CondOpc == ISD::OR) {
15791         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15792         // two branches instead of an explicit OR instruction with a
15793         // separate test.
15794         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15795             isX86LogicalCmp(Cmp)) {
15796           CC = Cond.getOperand(0).getOperand(0);
15797           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15798                               Chain, Dest, CC, Cmp);
15799           CC = Cond.getOperand(1).getOperand(0);
15800           Cond = Cmp;
15801           addTest = false;
15802         }
15803       } else { // ISD::AND
15804         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15805         // two branches instead of an explicit AND instruction with a
15806         // separate test. However, we only do this if this block doesn't
15807         // have a fall-through edge, because this requires an explicit
15808         // jmp when the condition is false.
15809         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15810             isX86LogicalCmp(Cmp) &&
15811             Op.getNode()->hasOneUse()) {
15812           X86::CondCode CCode =
15813             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15814           CCode = X86::GetOppositeBranchCondition(CCode);
15815           CC = DAG.getConstant(CCode, dl, MVT::i8);
15816           SDNode *User = *Op.getNode()->use_begin();
15817           // Look for an unconditional branch following this conditional branch.
15818           // We need this because we need to reverse the successors in order
15819           // to implement FCMP_OEQ.
15820           if (User->getOpcode() == ISD::BR) {
15821             SDValue FalseBB = User->getOperand(1);
15822             SDNode *NewBR =
15823               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15824             assert(NewBR == User);
15825             (void)NewBR;
15826             Dest = FalseBB;
15827
15828             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15829                                 Chain, Dest, CC, Cmp);
15830             X86::CondCode CCode =
15831               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15832             CCode = X86::GetOppositeBranchCondition(CCode);
15833             CC = DAG.getConstant(CCode, dl, MVT::i8);
15834             Cond = Cmp;
15835             addTest = false;
15836           }
15837         }
15838       }
15839     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15840       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15841       // It should be transformed during dag combiner except when the condition
15842       // is set by a arithmetics with overflow node.
15843       X86::CondCode CCode =
15844         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15845       CCode = X86::GetOppositeBranchCondition(CCode);
15846       CC = DAG.getConstant(CCode, dl, MVT::i8);
15847       Cond = Cond.getOperand(0).getOperand(1);
15848       addTest = false;
15849     } else if (Cond.getOpcode() == ISD::SETCC &&
15850                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15851       // For FCMP_OEQ, we can emit
15852       // two branches instead of an explicit AND instruction with a
15853       // separate test. However, we only do this if this block doesn't
15854       // have a fall-through edge, because this requires an explicit
15855       // jmp when the condition is false.
15856       if (Op.getNode()->hasOneUse()) {
15857         SDNode *User = *Op.getNode()->use_begin();
15858         // Look for an unconditional branch following this conditional branch.
15859         // We need this because we need to reverse the successors in order
15860         // to implement FCMP_OEQ.
15861         if (User->getOpcode() == ISD::BR) {
15862           SDValue FalseBB = User->getOperand(1);
15863           SDNode *NewBR =
15864             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15865           assert(NewBR == User);
15866           (void)NewBR;
15867           Dest = FalseBB;
15868
15869           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15870                                     Cond.getOperand(0), Cond.getOperand(1));
15871           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15872           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15873           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15874                               Chain, Dest, CC, Cmp);
15875           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15876           Cond = Cmp;
15877           addTest = false;
15878         }
15879       }
15880     } else if (Cond.getOpcode() == ISD::SETCC &&
15881                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15882       // For FCMP_UNE, we can emit
15883       // two branches instead of an explicit AND instruction with a
15884       // separate test. However, we only do this if this block doesn't
15885       // have a fall-through edge, because this requires an explicit
15886       // jmp when the condition is false.
15887       if (Op.getNode()->hasOneUse()) {
15888         SDNode *User = *Op.getNode()->use_begin();
15889         // Look for an unconditional branch following this conditional branch.
15890         // We need this because we need to reverse the successors in order
15891         // to implement FCMP_UNE.
15892         if (User->getOpcode() == ISD::BR) {
15893           SDValue FalseBB = User->getOperand(1);
15894           SDNode *NewBR =
15895             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15896           assert(NewBR == User);
15897           (void)NewBR;
15898
15899           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15900                                     Cond.getOperand(0), Cond.getOperand(1));
15901           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15902           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15903           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15904                               Chain, Dest, CC, Cmp);
15905           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15906           Cond = Cmp;
15907           addTest = false;
15908           Dest = FalseBB;
15909         }
15910       }
15911     }
15912   }
15913
15914   if (addTest) {
15915     // Look pass the truncate if the high bits are known zero.
15916     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15917         Cond = Cond.getOperand(0);
15918
15919     // We know the result of AND is compared against zero. Try to match
15920     // it to BT.
15921     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15922       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15923         CC = NewSetCC.getOperand(0);
15924         Cond = NewSetCC.getOperand(1);
15925         addTest = false;
15926       }
15927     }
15928   }
15929
15930   if (addTest) {
15931     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15932     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15933     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15934   }
15935   Cond = ConvertCmpIfNecessary(Cond, DAG);
15936   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15937                      Chain, Dest, CC, Cond);
15938 }
15939
15940 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15941 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15942 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15943 // that the guard pages used by the OS virtual memory manager are allocated in
15944 // correct sequence.
15945 SDValue
15946 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15947                                            SelectionDAG &DAG) const {
15948   MachineFunction &MF = DAG.getMachineFunction();
15949   bool SplitStack = MF.shouldSplitStack();
15950   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15951                SplitStack;
15952   SDLoc dl(Op);
15953
15954   // Get the inputs.
15955   SDNode *Node = Op.getNode();
15956   SDValue Chain = Op.getOperand(0);
15957   SDValue Size  = Op.getOperand(1);
15958   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15959   EVT VT = Node->getValueType(0);
15960
15961   // Chain the dynamic stack allocation so that it doesn't modify the stack
15962   // pointer when other instructions are using the stack.
15963   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15964
15965   bool Is64Bit = Subtarget->is64Bit();
15966   MVT SPTy = getPointerTy(DAG.getDataLayout());
15967
15968   SDValue Result;
15969   if (!Lower) {
15970     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15971     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15972     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15973                     " not tell us which reg is the stack pointer!");
15974     EVT VT = Node->getValueType(0);
15975     SDValue Tmp3 = Node->getOperand(2);
15976
15977     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15978     Chain = SP.getValue(1);
15979     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15980     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15981     unsigned StackAlign = TFI.getStackAlignment();
15982     Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15983     if (Align > StackAlign)
15984       Result = DAG.getNode(ISD::AND, dl, VT, Result,
15985                          DAG.getConstant(-(uint64_t)Align, dl, VT));
15986     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15987   } else if (SplitStack) {
15988     MachineRegisterInfo &MRI = MF.getRegInfo();
15989
15990     if (Is64Bit) {
15991       // The 64 bit implementation of segmented stacks needs to clobber both r10
15992       // r11. This makes it impossible to use it along with nested parameters.
15993       const Function *F = MF.getFunction();
15994
15995       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15996            I != E; ++I)
15997         if (I->hasNestAttr())
15998           report_fatal_error("Cannot use segmented stacks with functions that "
15999                              "have nested arguments.");
16000     }
16001
16002     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
16003     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16004     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16005     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16006                                 DAG.getRegister(Vreg, SPTy));
16007   } else {
16008     SDValue Flag;
16009     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
16010
16011     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
16012     Flag = Chain.getValue(1);
16013     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16014
16015     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
16016
16017     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16018     unsigned SPReg = RegInfo->getStackRegister();
16019     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16020     Chain = SP.getValue(1);
16021
16022     if (Align) {
16023       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16024                        DAG.getConstant(-(uint64_t)Align, dl, VT));
16025       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16026     }
16027
16028     Result = SP;
16029   }
16030
16031   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
16032                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
16033
16034   SDValue Ops[2] = {Result, Chain};
16035   return DAG.getMergeValues(Ops, dl);
16036 }
16037
16038 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16039   MachineFunction &MF = DAG.getMachineFunction();
16040   auto PtrVT = getPointerTy(MF.getDataLayout());
16041   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16042
16043   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16044   SDLoc DL(Op);
16045
16046   if (!Subtarget->is64Bit() ||
16047       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
16048     // vastart just stores the address of the VarArgsFrameIndex slot into the
16049     // memory location argument.
16050     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16051     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16052                         MachinePointerInfo(SV), false, false, 0);
16053   }
16054
16055   // __va_list_tag:
16056   //   gp_offset         (0 - 6 * 8)
16057   //   fp_offset         (48 - 48 + 8 * 16)
16058   //   overflow_arg_area (point to parameters coming in memory).
16059   //   reg_save_area
16060   SmallVector<SDValue, 8> MemOps;
16061   SDValue FIN = Op.getOperand(1);
16062   // Store gp_offset
16063   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16064                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16065                                                DL, MVT::i32),
16066                                FIN, MachinePointerInfo(SV), false, false, 0);
16067   MemOps.push_back(Store);
16068
16069   // Store fp_offset
16070   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16071   Store = DAG.getStore(Op.getOperand(0), DL,
16072                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
16073                                        MVT::i32),
16074                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
16075   MemOps.push_back(Store);
16076
16077   // Store ptr to overflow_arg_area
16078   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16079   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16080   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16081                        MachinePointerInfo(SV, 8),
16082                        false, false, 0);
16083   MemOps.push_back(Store);
16084
16085   // Store ptr to reg_save_area.
16086   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
16087       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
16088   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
16089   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
16090       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
16091   MemOps.push_back(Store);
16092   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16093 }
16094
16095 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16096   assert(Subtarget->is64Bit() &&
16097          "LowerVAARG only handles 64-bit va_arg!");
16098   assert(Op.getNode()->getNumOperands() == 4);
16099
16100   MachineFunction &MF = DAG.getMachineFunction();
16101   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
16102     // The Win64 ABI uses char* instead of a structure.
16103     return DAG.expandVAArg(Op.getNode());
16104
16105   SDValue Chain = Op.getOperand(0);
16106   SDValue SrcPtr = Op.getOperand(1);
16107   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16108   unsigned Align = Op.getConstantOperandVal(3);
16109   SDLoc dl(Op);
16110
16111   EVT ArgVT = Op.getNode()->getValueType(0);
16112   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16113   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
16114   uint8_t ArgMode;
16115
16116   // Decide which area this value should be read from.
16117   // TODO: Implement the AMD64 ABI in its entirety. This simple
16118   // selection mechanism works only for the basic types.
16119   if (ArgVT == MVT::f80) {
16120     llvm_unreachable("va_arg for f80 not yet implemented");
16121   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16122     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16123   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16124     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16125   } else {
16126     llvm_unreachable("Unhandled argument type in LowerVAARG");
16127   }
16128
16129   if (ArgMode == 2) {
16130     // Sanity Check: Make sure using fp_offset makes sense.
16131     assert(!Subtarget->useSoftFloat() &&
16132            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
16133            Subtarget->hasSSE1());
16134   }
16135
16136   // Insert VAARG_64 node into the DAG
16137   // VAARG_64 returns two values: Variable Argument Address, Chain
16138   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
16139                        DAG.getConstant(ArgMode, dl, MVT::i8),
16140                        DAG.getConstant(Align, dl, MVT::i32)};
16141   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
16142   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16143                                           VTs, InstOps, MVT::i64,
16144                                           MachinePointerInfo(SV),
16145                                           /*Align=*/0,
16146                                           /*Volatile=*/false,
16147                                           /*ReadMem=*/true,
16148                                           /*WriteMem=*/true);
16149   Chain = VAARG.getValue(1);
16150
16151   // Load the next argument and return it
16152   return DAG.getLoad(ArgVT, dl,
16153                      Chain,
16154                      VAARG,
16155                      MachinePointerInfo(),
16156                      false, false, false, 0);
16157 }
16158
16159 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16160                            SelectionDAG &DAG) {
16161   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
16162   // where a va_list is still an i8*.
16163   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16164   if (Subtarget->isCallingConvWin64(
16165         DAG.getMachineFunction().getFunction()->getCallingConv()))
16166     // Probably a Win64 va_copy.
16167     return DAG.expandVACopy(Op.getNode());
16168
16169   SDValue Chain = Op.getOperand(0);
16170   SDValue DstPtr = Op.getOperand(1);
16171   SDValue SrcPtr = Op.getOperand(2);
16172   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16173   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16174   SDLoc DL(Op);
16175
16176   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16177                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
16178                        false, false,
16179                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16180 }
16181
16182 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16183 // amount is a constant. Takes immediate version of shift as input.
16184 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16185                                           SDValue SrcOp, uint64_t ShiftAmt,
16186                                           SelectionDAG &DAG) {
16187   MVT ElementType = VT.getVectorElementType();
16188
16189   // Fold this packed shift into its first operand if ShiftAmt is 0.
16190   if (ShiftAmt == 0)
16191     return SrcOp;
16192
16193   // Check for ShiftAmt >= element width
16194   if (ShiftAmt >= ElementType.getSizeInBits()) {
16195     if (Opc == X86ISD::VSRAI)
16196       ShiftAmt = ElementType.getSizeInBits() - 1;
16197     else
16198       return DAG.getConstant(0, dl, VT);
16199   }
16200
16201   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16202          && "Unknown target vector shift-by-constant node");
16203
16204   // Fold this packed vector shift into a build vector if SrcOp is a
16205   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16206   if (VT == SrcOp.getSimpleValueType() &&
16207       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16208     SmallVector<SDValue, 8> Elts;
16209     unsigned NumElts = SrcOp->getNumOperands();
16210     ConstantSDNode *ND;
16211
16212     switch(Opc) {
16213     default: llvm_unreachable(nullptr);
16214     case X86ISD::VSHLI:
16215       for (unsigned i=0; i!=NumElts; ++i) {
16216         SDValue CurrentOp = SrcOp->getOperand(i);
16217         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16218           Elts.push_back(CurrentOp);
16219           continue;
16220         }
16221         ND = cast<ConstantSDNode>(CurrentOp);
16222         const APInt &C = ND->getAPIntValue();
16223         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
16224       }
16225       break;
16226     case X86ISD::VSRLI:
16227       for (unsigned i=0; i!=NumElts; ++i) {
16228         SDValue CurrentOp = SrcOp->getOperand(i);
16229         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16230           Elts.push_back(CurrentOp);
16231           continue;
16232         }
16233         ND = cast<ConstantSDNode>(CurrentOp);
16234         const APInt &C = ND->getAPIntValue();
16235         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
16236       }
16237       break;
16238     case X86ISD::VSRAI:
16239       for (unsigned i=0; i!=NumElts; ++i) {
16240         SDValue CurrentOp = SrcOp->getOperand(i);
16241         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16242           Elts.push_back(CurrentOp);
16243           continue;
16244         }
16245         ND = cast<ConstantSDNode>(CurrentOp);
16246         const APInt &C = ND->getAPIntValue();
16247         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
16248       }
16249       break;
16250     }
16251
16252     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16253   }
16254
16255   return DAG.getNode(Opc, dl, VT, SrcOp,
16256                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
16257 }
16258
16259 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16260 // may or may not be a constant. Takes immediate version of shift as input.
16261 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16262                                    SDValue SrcOp, SDValue ShAmt,
16263                                    SelectionDAG &DAG) {
16264   MVT SVT = ShAmt.getSimpleValueType();
16265   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16266
16267   // Catch shift-by-constant.
16268   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16269     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16270                                       CShAmt->getZExtValue(), DAG);
16271
16272   // Change opcode to non-immediate version
16273   switch (Opc) {
16274     default: llvm_unreachable("Unknown target vector shift node");
16275     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16276     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16277     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16278   }
16279
16280   const X86Subtarget &Subtarget =
16281       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16282   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16283       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16284     // Let the shuffle legalizer expand this shift amount node.
16285     SDValue Op0 = ShAmt.getOperand(0);
16286     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16287     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16288   } else {
16289     // Need to build a vector containing shift amount.
16290     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16291     SmallVector<SDValue, 4> ShOps;
16292     ShOps.push_back(ShAmt);
16293     if (SVT == MVT::i32) {
16294       ShOps.push_back(DAG.getConstant(0, dl, SVT));
16295       ShOps.push_back(DAG.getUNDEF(SVT));
16296     }
16297     ShOps.push_back(DAG.getUNDEF(SVT));
16298
16299     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16300     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16301   }
16302
16303   // The return type has to be a 128-bit type with the same element
16304   // type as the input type.
16305   MVT EltVT = VT.getVectorElementType();
16306   MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16307
16308   ShAmt = DAG.getBitcast(ShVT, ShAmt);
16309   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16310 }
16311
16312 /// \brief Return Mask with the necessary casting or extending
16313 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16314 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16315                            const X86Subtarget *Subtarget,
16316                            SelectionDAG &DAG, SDLoc dl) {
16317
16318   if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16319     // Mask should be extended
16320     Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16321                        MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16322   }
16323
16324   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16325     if (MaskVT == MVT::v64i1) {
16326       assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16327       // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16328       SDValue Lo, Hi;
16329       Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16330                           DAG.getConstant(0, dl, MVT::i32));
16331       Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16332                           DAG.getConstant(1, dl, MVT::i32));
16333
16334       Lo = DAG.getBitcast(MVT::v32i1, Lo);
16335       Hi = DAG.getBitcast(MVT::v32i1, Hi);
16336
16337       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16338     } else {
16339       // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16340       // and bitcast.
16341       MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16342       return DAG.getBitcast(MaskVT,
16343                             DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16344     }
16345
16346   } else {
16347     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16348                                      Mask.getSimpleValueType().getSizeInBits());
16349     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16350     // are extracted by EXTRACT_SUBVECTOR.
16351     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16352                        DAG.getBitcast(BitcastVT, Mask),
16353                        DAG.getIntPtrConstant(0, dl));
16354   }
16355 }
16356
16357 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16358 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16359 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16360 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16361                   SDValue PreservedSrc,
16362                   const X86Subtarget *Subtarget,
16363                   SelectionDAG &DAG) {
16364   MVT VT = Op.getSimpleValueType();
16365   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16366   unsigned OpcodeSelect = ISD::VSELECT;
16367   SDLoc dl(Op);
16368
16369   if (isAllOnesConstant(Mask))
16370     return Op;
16371
16372   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16373
16374   switch (Op.getOpcode()) {
16375   default: break;
16376   case X86ISD::PCMPEQM:
16377   case X86ISD::PCMPGTM:
16378   case X86ISD::CMPM:
16379   case X86ISD::CMPMU:
16380     return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16381   case X86ISD::VFPCLASS:
16382     case X86ISD::VFPCLASSS:
16383     return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16384   case X86ISD::VTRUNC:
16385   case X86ISD::VTRUNCS:
16386   case X86ISD::VTRUNCUS:
16387     // We can't use ISD::VSELECT here because it is not always "Legal"
16388     // for the destination type. For example vpmovqb require only AVX512
16389     // and vselect that can operate on byte element type require BWI
16390     OpcodeSelect = X86ISD::SELECT;
16391     break;
16392   }
16393   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16394     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16395   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16396 }
16397
16398 /// \brief Creates an SDNode for a predicated scalar operation.
16399 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16400 /// The mask is coming as MVT::i8 and it should be truncated
16401 /// to MVT::i1 while lowering masking intrinsics.
16402 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16403 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16404 /// for a scalar instruction.
16405 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16406                                     SDValue PreservedSrc,
16407                                     const X86Subtarget *Subtarget,
16408                                     SelectionDAG &DAG) {
16409   if (isAllOnesConstant(Mask))
16410     return Op;
16411
16412   MVT VT = Op.getSimpleValueType();
16413   SDLoc dl(Op);
16414   // The mask should be of type MVT::i1
16415   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16416
16417   if (Op.getOpcode() == X86ISD::FSETCC)
16418     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16419   if (Op.getOpcode() == X86ISD::VFPCLASS ||
16420       Op.getOpcode() == X86ISD::VFPCLASSS)
16421     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16422
16423   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16424     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16425   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16426 }
16427
16428 static int getSEHRegistrationNodeSize(const Function *Fn) {
16429   if (!Fn->hasPersonalityFn())
16430     report_fatal_error(
16431         "querying registration node size for function without personality");
16432   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16433   // WinEHStatePass for the full struct definition.
16434   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16435   case EHPersonality::MSVC_X86SEH: return 24;
16436   case EHPersonality::MSVC_CXX: return 16;
16437   default: break;
16438   }
16439   report_fatal_error(
16440       "can only recover FP for 32-bit MSVC EH personality functions");
16441 }
16442
16443 /// When the MSVC runtime transfers control to us, either to an outlined
16444 /// function or when returning to a parent frame after catching an exception, we
16445 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16446 /// Here's the math:
16447 ///   RegNodeBase = EntryEBP - RegNodeSize
16448 ///   ParentFP = RegNodeBase - ParentFrameOffset
16449 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16450 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16451 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16452                                    SDValue EntryEBP) {
16453   MachineFunction &MF = DAG.getMachineFunction();
16454   SDLoc dl;
16455
16456   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16457   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16458
16459   // It's possible that the parent function no longer has a personality function
16460   // if the exceptional code was optimized away, in which case we just return
16461   // the incoming EBP.
16462   if (!Fn->hasPersonalityFn())
16463     return EntryEBP;
16464
16465   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16466   // registration, or the .set_setframe offset.
16467   MCSymbol *OffsetSym =
16468       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16469           GlobalValue::getRealLinkageName(Fn->getName()));
16470   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16471   SDValue ParentFrameOffset =
16472       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16473
16474   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
16475   // prologue to RBP in the parent function.
16476   const X86Subtarget &Subtarget =
16477       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16478   if (Subtarget.is64Bit())
16479     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
16480
16481   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16482   // RegNodeBase = EntryEBP - RegNodeSize
16483   // ParentFP = RegNodeBase - ParentFrameOffset
16484   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16485                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16486   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
16487 }
16488
16489 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16490                                        SelectionDAG &DAG) {
16491   SDLoc dl(Op);
16492   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16493   MVT VT = Op.getSimpleValueType();
16494   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16495   if (IntrData) {
16496     switch(IntrData->Type) {
16497     case INTR_TYPE_1OP:
16498       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16499     case INTR_TYPE_2OP:
16500       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16501         Op.getOperand(2));
16502     case INTR_TYPE_2OP_IMM8:
16503       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16504                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16505     case INTR_TYPE_3OP:
16506       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16507         Op.getOperand(2), Op.getOperand(3));
16508     case INTR_TYPE_4OP:
16509       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16510         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16511     case INTR_TYPE_1OP_MASK_RM: {
16512       SDValue Src = Op.getOperand(1);
16513       SDValue PassThru = Op.getOperand(2);
16514       SDValue Mask = Op.getOperand(3);
16515       SDValue RoundingMode;
16516       // We allways add rounding mode to the Node.
16517       // If the rounding mode is not specified, we add the
16518       // "current direction" mode.
16519       if (Op.getNumOperands() == 4)
16520         RoundingMode =
16521           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16522       else
16523         RoundingMode = Op.getOperand(4);
16524       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16525       if (IntrWithRoundingModeOpcode != 0)
16526         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16527             X86::STATIC_ROUNDING::CUR_DIRECTION)
16528           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16529                                       dl, Op.getValueType(), Src, RoundingMode),
16530                                       Mask, PassThru, Subtarget, DAG);
16531       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16532                                               RoundingMode),
16533                                   Mask, PassThru, Subtarget, DAG);
16534     }
16535     case INTR_TYPE_1OP_MASK: {
16536       SDValue Src = Op.getOperand(1);
16537       SDValue PassThru = Op.getOperand(2);
16538       SDValue Mask = Op.getOperand(3);
16539       // We add rounding mode to the Node when
16540       //   - RM Opcode is specified and
16541       //   - RM is not "current direction".
16542       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16543       if (IntrWithRoundingModeOpcode != 0) {
16544         SDValue Rnd = Op.getOperand(4);
16545         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16546         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16547           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16548                                       dl, Op.getValueType(),
16549                                       Src, Rnd),
16550                                       Mask, PassThru, Subtarget, DAG);
16551         }
16552       }
16553       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16554                                   Mask, PassThru, Subtarget, DAG);
16555     }
16556     case INTR_TYPE_SCALAR_MASK: {
16557       SDValue Src1 = Op.getOperand(1);
16558       SDValue Src2 = Op.getOperand(2);
16559       SDValue passThru = Op.getOperand(3);
16560       SDValue Mask = Op.getOperand(4);
16561       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16562                                   Mask, passThru, Subtarget, DAG);
16563     }
16564     case INTR_TYPE_SCALAR_MASK_RM: {
16565       SDValue Src1 = Op.getOperand(1);
16566       SDValue Src2 = Op.getOperand(2);
16567       SDValue Src0 = Op.getOperand(3);
16568       SDValue Mask = Op.getOperand(4);
16569       // There are 2 kinds of intrinsics in this group:
16570       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16571       // (2) With rounding mode and sae - 7 operands.
16572       if (Op.getNumOperands() == 6) {
16573         SDValue Sae  = Op.getOperand(5);
16574         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16575         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16576                                                 Sae),
16577                                     Mask, Src0, Subtarget, DAG);
16578       }
16579       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16580       SDValue RoundingMode  = Op.getOperand(5);
16581       SDValue Sae  = Op.getOperand(6);
16582       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16583                                               RoundingMode, Sae),
16584                                   Mask, Src0, Subtarget, DAG);
16585     }
16586     case INTR_TYPE_2OP_MASK:
16587     case INTR_TYPE_2OP_IMM8_MASK: {
16588       SDValue Src1 = Op.getOperand(1);
16589       SDValue Src2 = Op.getOperand(2);
16590       SDValue PassThru = Op.getOperand(3);
16591       SDValue Mask = Op.getOperand(4);
16592
16593       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16594         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16595
16596       // We specify 2 possible opcodes for intrinsics with rounding modes.
16597       // First, we check if the intrinsic may have non-default rounding mode,
16598       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16599       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16600       if (IntrWithRoundingModeOpcode != 0) {
16601         SDValue Rnd = Op.getOperand(5);
16602         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16603         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16604           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16605                                       dl, Op.getValueType(),
16606                                       Src1, Src2, Rnd),
16607                                       Mask, PassThru, Subtarget, DAG);
16608         }
16609       }
16610       // TODO: Intrinsics should have fast-math-flags to propagate.
16611       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16612                                   Mask, PassThru, Subtarget, DAG);
16613     }
16614     case INTR_TYPE_2OP_MASK_RM: {
16615       SDValue Src1 = Op.getOperand(1);
16616       SDValue Src2 = Op.getOperand(2);
16617       SDValue PassThru = Op.getOperand(3);
16618       SDValue Mask = Op.getOperand(4);
16619       // We specify 2 possible modes for intrinsics, with/without rounding
16620       // modes.
16621       // First, we check if the intrinsic have rounding mode (6 operands),
16622       // if not, we set rounding mode to "current".
16623       SDValue Rnd;
16624       if (Op.getNumOperands() == 6)
16625         Rnd = Op.getOperand(5);
16626       else
16627         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16628       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16629                                               Src1, Src2, Rnd),
16630                                   Mask, PassThru, Subtarget, DAG);
16631     }
16632     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16633       SDValue Src1 = Op.getOperand(1);
16634       SDValue Src2 = Op.getOperand(2);
16635       SDValue Src3 = Op.getOperand(3);
16636       SDValue PassThru = Op.getOperand(4);
16637       SDValue Mask = Op.getOperand(5);
16638       SDValue Sae  = Op.getOperand(6);
16639
16640       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16641                                               Src2, Src3, Sae),
16642                                   Mask, PassThru, Subtarget, DAG);
16643     }
16644     case INTR_TYPE_3OP_MASK_RM: {
16645       SDValue Src1 = Op.getOperand(1);
16646       SDValue Src2 = Op.getOperand(2);
16647       SDValue Imm = Op.getOperand(3);
16648       SDValue PassThru = Op.getOperand(4);
16649       SDValue Mask = Op.getOperand(5);
16650       // We specify 2 possible modes for intrinsics, with/without rounding
16651       // modes.
16652       // First, we check if the intrinsic have rounding mode (7 operands),
16653       // if not, we set rounding mode to "current".
16654       SDValue Rnd;
16655       if (Op.getNumOperands() == 7)
16656         Rnd = Op.getOperand(6);
16657       else
16658         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16659       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16660         Src1, Src2, Imm, Rnd),
16661         Mask, PassThru, Subtarget, DAG);
16662     }
16663     case INTR_TYPE_3OP_IMM8_MASK:
16664     case INTR_TYPE_3OP_MASK:
16665     case INSERT_SUBVEC: {
16666       SDValue Src1 = Op.getOperand(1);
16667       SDValue Src2 = Op.getOperand(2);
16668       SDValue Src3 = Op.getOperand(3);
16669       SDValue PassThru = Op.getOperand(4);
16670       SDValue Mask = Op.getOperand(5);
16671
16672       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16673         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16674       else if (IntrData->Type == INSERT_SUBVEC) {
16675         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16676         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16677         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16678         Imm *= Src2.getSimpleValueType().getVectorNumElements();
16679         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16680       }
16681
16682       // We specify 2 possible opcodes for intrinsics with rounding modes.
16683       // First, we check if the intrinsic may have non-default rounding mode,
16684       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16685       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16686       if (IntrWithRoundingModeOpcode != 0) {
16687         SDValue Rnd = Op.getOperand(6);
16688         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16689         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16690           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16691                                       dl, Op.getValueType(),
16692                                       Src1, Src2, Src3, Rnd),
16693                                       Mask, PassThru, Subtarget, DAG);
16694         }
16695       }
16696       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16697                                               Src1, Src2, Src3),
16698                                   Mask, PassThru, Subtarget, DAG);
16699     }
16700     case VPERM_3OP_MASKZ:
16701     case VPERM_3OP_MASK:{
16702       // Src2 is the PassThru
16703       SDValue Src1 = Op.getOperand(1);
16704       SDValue Src2 = Op.getOperand(2);
16705       SDValue Src3 = Op.getOperand(3);
16706       SDValue Mask = Op.getOperand(4);
16707       MVT VT = Op.getSimpleValueType();
16708       SDValue PassThru = SDValue();
16709
16710       // set PassThru element
16711       if (IntrData->Type == VPERM_3OP_MASKZ)
16712         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16713       else
16714         PassThru = DAG.getBitcast(VT, Src2);
16715
16716       // Swap Src1 and Src2 in the node creation
16717       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16718                                               dl, Op.getValueType(),
16719                                               Src2, Src1, Src3),
16720                                   Mask, PassThru, Subtarget, DAG);
16721     }
16722     case FMA_OP_MASK3:
16723     case FMA_OP_MASKZ:
16724     case FMA_OP_MASK: {
16725       SDValue Src1 = Op.getOperand(1);
16726       SDValue Src2 = Op.getOperand(2);
16727       SDValue Src3 = Op.getOperand(3);
16728       SDValue Mask = Op.getOperand(4);
16729       MVT VT = Op.getSimpleValueType();
16730       SDValue PassThru = SDValue();
16731
16732       // set PassThru element
16733       if (IntrData->Type == FMA_OP_MASKZ)
16734         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16735       else if (IntrData->Type == FMA_OP_MASK3)
16736         PassThru = Src3;
16737       else
16738         PassThru = Src1;
16739
16740       // We specify 2 possible opcodes for intrinsics with rounding modes.
16741       // First, we check if the intrinsic may have non-default rounding mode,
16742       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16743       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16744       if (IntrWithRoundingModeOpcode != 0) {
16745         SDValue Rnd = Op.getOperand(5);
16746         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16747             X86::STATIC_ROUNDING::CUR_DIRECTION)
16748           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16749                                                   dl, Op.getValueType(),
16750                                                   Src1, Src2, Src3, Rnd),
16751                                       Mask, PassThru, Subtarget, DAG);
16752       }
16753       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16754                                               dl, Op.getValueType(),
16755                                               Src1, Src2, Src3),
16756                                   Mask, PassThru, Subtarget, DAG);
16757     }
16758     case TERLOG_OP_MASK:
16759     case TERLOG_OP_MASKZ: {
16760       SDValue Src1 = Op.getOperand(1);
16761       SDValue Src2 = Op.getOperand(2);
16762       SDValue Src3 = Op.getOperand(3);
16763       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16764       SDValue Mask = Op.getOperand(5);
16765       MVT VT = Op.getSimpleValueType();
16766       SDValue PassThru = Src1;
16767       // Set PassThru element.
16768       if (IntrData->Type == TERLOG_OP_MASKZ)
16769         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16770
16771       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16772                                               Src1, Src2, Src3, Src4),
16773                                   Mask, PassThru, Subtarget, DAG);
16774     }
16775     case FPCLASS: {
16776       // FPclass intrinsics with mask
16777        SDValue Src1 = Op.getOperand(1);
16778        MVT VT = Src1.getSimpleValueType();
16779        MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16780        SDValue Imm = Op.getOperand(2);
16781        SDValue Mask = Op.getOperand(3);
16782        MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16783                                      Mask.getSimpleValueType().getSizeInBits());
16784        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16785        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16786                                                  DAG.getTargetConstant(0, dl, MaskVT),
16787                                                  Subtarget, DAG);
16788        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16789                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16790                                  DAG.getIntPtrConstant(0, dl));
16791        return DAG.getBitcast(Op.getValueType(), Res);
16792     }
16793     case FPCLASSS: {
16794       SDValue Src1 = Op.getOperand(1);
16795       SDValue Imm = Op.getOperand(2);
16796       SDValue Mask = Op.getOperand(3);
16797       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16798       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16799         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16800       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16801     }
16802     case CMP_MASK:
16803     case CMP_MASK_CC: {
16804       // Comparison intrinsics with masks.
16805       // Example of transformation:
16806       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16807       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16808       // (i8 (bitcast
16809       //   (v8i1 (insert_subvector undef,
16810       //           (v2i1 (and (PCMPEQM %a, %b),
16811       //                      (extract_subvector
16812       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16813       MVT VT = Op.getOperand(1).getSimpleValueType();
16814       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16815       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16816       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16817                                        Mask.getSimpleValueType().getSizeInBits());
16818       SDValue Cmp;
16819       if (IntrData->Type == CMP_MASK_CC) {
16820         SDValue CC = Op.getOperand(3);
16821         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16822         // We specify 2 possible opcodes for intrinsics with rounding modes.
16823         // First, we check if the intrinsic may have non-default rounding mode,
16824         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16825         if (IntrData->Opc1 != 0) {
16826           SDValue Rnd = Op.getOperand(5);
16827           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16828               X86::STATIC_ROUNDING::CUR_DIRECTION)
16829             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16830                               Op.getOperand(2), CC, Rnd);
16831         }
16832         //default rounding mode
16833         if(!Cmp.getNode())
16834             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16835                               Op.getOperand(2), CC);
16836
16837       } else {
16838         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16839         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16840                           Op.getOperand(2));
16841       }
16842       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16843                                              DAG.getTargetConstant(0, dl,
16844                                                                    MaskVT),
16845                                              Subtarget, DAG);
16846       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16847                                 DAG.getUNDEF(BitcastVT), CmpMask,
16848                                 DAG.getIntPtrConstant(0, dl));
16849       return DAG.getBitcast(Op.getValueType(), Res);
16850     }
16851     case CMP_MASK_SCALAR_CC: {
16852       SDValue Src1 = Op.getOperand(1);
16853       SDValue Src2 = Op.getOperand(2);
16854       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16855       SDValue Mask = Op.getOperand(4);
16856
16857       SDValue Cmp;
16858       if (IntrData->Opc1 != 0) {
16859         SDValue Rnd = Op.getOperand(5);
16860         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16861             X86::STATIC_ROUNDING::CUR_DIRECTION)
16862           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16863       }
16864       //default rounding mode
16865       if(!Cmp.getNode())
16866         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16867
16868       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16869                                              DAG.getTargetConstant(0, dl,
16870                                                                    MVT::i1),
16871                                              Subtarget, DAG);
16872
16873       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16874                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16875                          DAG.getValueType(MVT::i1));
16876     }
16877     case COMI: { // Comparison intrinsics
16878       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16879       SDValue LHS = Op.getOperand(1);
16880       SDValue RHS = Op.getOperand(2);
16881       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16882       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16883       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16884       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16885                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16886       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16887     }
16888     case COMI_RM: { // Comparison intrinsics with Sae
16889       SDValue LHS = Op.getOperand(1);
16890       SDValue RHS = Op.getOperand(2);
16891       SDValue CC = Op.getOperand(3);
16892       SDValue Sae = Op.getOperand(4);
16893       auto ComiType = TranslateX86ConstCondToX86CC(CC);
16894       // choose between ordered and unordered (comi/ucomi)
16895       unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16896       SDValue Cond;
16897       if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16898                                            X86::STATIC_ROUNDING::CUR_DIRECTION)
16899         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16900       else
16901         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16902       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16903         DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16904       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16905     }
16906     case VSHIFT:
16907       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16908                                  Op.getOperand(1), Op.getOperand(2), DAG);
16909     case VSHIFT_MASK:
16910       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16911                                                       Op.getSimpleValueType(),
16912                                                       Op.getOperand(1),
16913                                                       Op.getOperand(2), DAG),
16914                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16915                                   DAG);
16916     case COMPRESS_EXPAND_IN_REG: {
16917       SDValue Mask = Op.getOperand(3);
16918       SDValue DataToCompress = Op.getOperand(1);
16919       SDValue PassThru = Op.getOperand(2);
16920       if (isAllOnesConstant(Mask)) // return data as is
16921         return Op.getOperand(1);
16922
16923       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16924                                               DataToCompress),
16925                                   Mask, PassThru, Subtarget, DAG);
16926     }
16927     case BROADCASTM: {
16928       SDValue Mask = Op.getOperand(1);
16929       MVT MaskVT = MVT::getVectorVT(MVT::i1,
16930                                     Mask.getSimpleValueType().getSizeInBits());
16931       Mask = DAG.getBitcast(MaskVT, Mask);
16932       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16933     }
16934     case BLEND: {
16935       SDValue Mask = Op.getOperand(3);
16936       MVT VT = Op.getSimpleValueType();
16937       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16938       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16939       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16940                          Op.getOperand(2));
16941     }
16942     case KUNPCK: {
16943       MVT VT = Op.getSimpleValueType();
16944       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16945
16946       SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16947       SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16948       // Arguments should be swapped.
16949       SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16950                                 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16951                                 Src2, Src1);
16952       return DAG.getBitcast(VT, Res);
16953     }
16954     case CONVERT_TO_MASK: {
16955       MVT SrcVT = Op.getOperand(1).getSimpleValueType();
16956       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
16957       MVT BitcastVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits());
16958
16959       SDValue CvtMask = DAG.getNode(IntrData->Opc0, dl, MaskVT,
16960                                     Op.getOperand(1));
16961       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16962                                 DAG.getUNDEF(BitcastVT), CvtMask,
16963                                 DAG.getIntPtrConstant(0, dl));
16964       return DAG.getBitcast(Op.getValueType(), Res);
16965     }
16966     case CONVERT_MASK_TO_VEC: {
16967       SDValue Mask = Op.getOperand(1);
16968       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16969       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16970       return DAG.getNode(IntrData->Opc0, dl, VT, VMask);
16971     }
16972     case BRCST_SUBVEC_TO_VEC: {
16973       SDValue Src = Op.getOperand(1);
16974       SDValue Passthru = Op.getOperand(2);
16975       SDValue Mask = Op.getOperand(3);
16976       EVT resVT = Passthru.getValueType();
16977       SDValue subVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, resVT,
16978                                        DAG.getUNDEF(resVT), Src,
16979                                        DAG.getIntPtrConstant(0, dl));
16980       SDValue immVal;
16981       if (Src.getSimpleValueType().is256BitVector() && resVT.is512BitVector())
16982         immVal = DAG.getConstant(0x44, dl, MVT::i8);
16983       else
16984         immVal = DAG.getConstant(0, dl, MVT::i8);
16985       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16986                                               subVec, subVec, immVal),
16987                                   Mask, Passthru, Subtarget, DAG);
16988     }
16989     default:
16990       break;
16991     }
16992   }
16993
16994   switch (IntNo) {
16995   default: return SDValue();    // Don't custom lower most intrinsics.
16996
16997   case Intrinsic::x86_avx2_permd:
16998   case Intrinsic::x86_avx2_permps:
16999     // Operands intentionally swapped. Mask is last operand to intrinsic,
17000     // but second operand for node/instruction.
17001     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
17002                        Op.getOperand(2), Op.getOperand(1));
17003
17004   // ptest and testp intrinsics. The intrinsic these come from are designed to
17005   // return an integer value, not just an instruction so lower it to the ptest
17006   // or testp pattern and a setcc for the result.
17007   case Intrinsic::x86_sse41_ptestz:
17008   case Intrinsic::x86_sse41_ptestc:
17009   case Intrinsic::x86_sse41_ptestnzc:
17010   case Intrinsic::x86_avx_ptestz_256:
17011   case Intrinsic::x86_avx_ptestc_256:
17012   case Intrinsic::x86_avx_ptestnzc_256:
17013   case Intrinsic::x86_avx_vtestz_ps:
17014   case Intrinsic::x86_avx_vtestc_ps:
17015   case Intrinsic::x86_avx_vtestnzc_ps:
17016   case Intrinsic::x86_avx_vtestz_pd:
17017   case Intrinsic::x86_avx_vtestc_pd:
17018   case Intrinsic::x86_avx_vtestnzc_pd:
17019   case Intrinsic::x86_avx_vtestz_ps_256:
17020   case Intrinsic::x86_avx_vtestc_ps_256:
17021   case Intrinsic::x86_avx_vtestnzc_ps_256:
17022   case Intrinsic::x86_avx_vtestz_pd_256:
17023   case Intrinsic::x86_avx_vtestc_pd_256:
17024   case Intrinsic::x86_avx_vtestnzc_pd_256: {
17025     bool IsTestPacked = false;
17026     unsigned X86CC;
17027     switch (IntNo) {
17028     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
17029     case Intrinsic::x86_avx_vtestz_ps:
17030     case Intrinsic::x86_avx_vtestz_pd:
17031     case Intrinsic::x86_avx_vtestz_ps_256:
17032     case Intrinsic::x86_avx_vtestz_pd_256:
17033       IsTestPacked = true; // Fallthrough
17034     case Intrinsic::x86_sse41_ptestz:
17035     case Intrinsic::x86_avx_ptestz_256:
17036       // ZF = 1
17037       X86CC = X86::COND_E;
17038       break;
17039     case Intrinsic::x86_avx_vtestc_ps:
17040     case Intrinsic::x86_avx_vtestc_pd:
17041     case Intrinsic::x86_avx_vtestc_ps_256:
17042     case Intrinsic::x86_avx_vtestc_pd_256:
17043       IsTestPacked = true; // Fallthrough
17044     case Intrinsic::x86_sse41_ptestc:
17045     case Intrinsic::x86_avx_ptestc_256:
17046       // CF = 1
17047       X86CC = X86::COND_B;
17048       break;
17049     case Intrinsic::x86_avx_vtestnzc_ps:
17050     case Intrinsic::x86_avx_vtestnzc_pd:
17051     case Intrinsic::x86_avx_vtestnzc_ps_256:
17052     case Intrinsic::x86_avx_vtestnzc_pd_256:
17053       IsTestPacked = true; // Fallthrough
17054     case Intrinsic::x86_sse41_ptestnzc:
17055     case Intrinsic::x86_avx_ptestnzc_256:
17056       // ZF and CF = 0
17057       X86CC = X86::COND_A;
17058       break;
17059     }
17060
17061     SDValue LHS = Op.getOperand(1);
17062     SDValue RHS = Op.getOperand(2);
17063     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17064     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17065     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17066     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17067     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17068   }
17069   case Intrinsic::x86_avx512_kortestz_w:
17070   case Intrinsic::x86_avx512_kortestc_w: {
17071     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17072     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
17073     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
17074     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17075     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17076     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17077     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17078   }
17079
17080   case Intrinsic::x86_sse42_pcmpistria128:
17081   case Intrinsic::x86_sse42_pcmpestria128:
17082   case Intrinsic::x86_sse42_pcmpistric128:
17083   case Intrinsic::x86_sse42_pcmpestric128:
17084   case Intrinsic::x86_sse42_pcmpistrio128:
17085   case Intrinsic::x86_sse42_pcmpestrio128:
17086   case Intrinsic::x86_sse42_pcmpistris128:
17087   case Intrinsic::x86_sse42_pcmpestris128:
17088   case Intrinsic::x86_sse42_pcmpistriz128:
17089   case Intrinsic::x86_sse42_pcmpestriz128: {
17090     unsigned Opcode;
17091     unsigned X86CC;
17092     switch (IntNo) {
17093     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17094     case Intrinsic::x86_sse42_pcmpistria128:
17095       Opcode = X86ISD::PCMPISTRI;
17096       X86CC = X86::COND_A;
17097       break;
17098     case Intrinsic::x86_sse42_pcmpestria128:
17099       Opcode = X86ISD::PCMPESTRI;
17100       X86CC = X86::COND_A;
17101       break;
17102     case Intrinsic::x86_sse42_pcmpistric128:
17103       Opcode = X86ISD::PCMPISTRI;
17104       X86CC = X86::COND_B;
17105       break;
17106     case Intrinsic::x86_sse42_pcmpestric128:
17107       Opcode = X86ISD::PCMPESTRI;
17108       X86CC = X86::COND_B;
17109       break;
17110     case Intrinsic::x86_sse42_pcmpistrio128:
17111       Opcode = X86ISD::PCMPISTRI;
17112       X86CC = X86::COND_O;
17113       break;
17114     case Intrinsic::x86_sse42_pcmpestrio128:
17115       Opcode = X86ISD::PCMPESTRI;
17116       X86CC = X86::COND_O;
17117       break;
17118     case Intrinsic::x86_sse42_pcmpistris128:
17119       Opcode = X86ISD::PCMPISTRI;
17120       X86CC = X86::COND_S;
17121       break;
17122     case Intrinsic::x86_sse42_pcmpestris128:
17123       Opcode = X86ISD::PCMPESTRI;
17124       X86CC = X86::COND_S;
17125       break;
17126     case Intrinsic::x86_sse42_pcmpistriz128:
17127       Opcode = X86ISD::PCMPISTRI;
17128       X86CC = X86::COND_E;
17129       break;
17130     case Intrinsic::x86_sse42_pcmpestriz128:
17131       Opcode = X86ISD::PCMPESTRI;
17132       X86CC = X86::COND_E;
17133       break;
17134     }
17135     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17136     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17137     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17138     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17139                                 DAG.getConstant(X86CC, dl, MVT::i8),
17140                                 SDValue(PCMP.getNode(), 1));
17141     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17142   }
17143
17144   case Intrinsic::x86_sse42_pcmpistri128:
17145   case Intrinsic::x86_sse42_pcmpestri128: {
17146     unsigned Opcode;
17147     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17148       Opcode = X86ISD::PCMPISTRI;
17149     else
17150       Opcode = X86ISD::PCMPESTRI;
17151
17152     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17153     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17154     return DAG.getNode(Opcode, dl, VTs, NewOps);
17155   }
17156
17157   case Intrinsic::x86_seh_lsda: {
17158     // Compute the symbol for the LSDA. We know it'll get emitted later.
17159     MachineFunction &MF = DAG.getMachineFunction();
17160     SDValue Op1 = Op.getOperand(1);
17161     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
17162     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
17163         GlobalValue::getRealLinkageName(Fn->getName()));
17164
17165     // Generate a simple absolute symbol reference. This intrinsic is only
17166     // supported on 32-bit Windows, which isn't PIC.
17167     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
17168     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
17169   }
17170
17171   case Intrinsic::x86_seh_recoverfp: {
17172     SDValue FnOp = Op.getOperand(1);
17173     SDValue IncomingFPOp = Op.getOperand(2);
17174     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
17175     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
17176     if (!Fn)
17177       report_fatal_error(
17178           "llvm.x86.seh.recoverfp must take a function as the first argument");
17179     return recoverFramePointer(DAG, Fn, IncomingFPOp);
17180   }
17181
17182   case Intrinsic::localaddress: {
17183     // Returns one of the stack, base, or frame pointer registers, depending on
17184     // which is used to reference local variables.
17185     MachineFunction &MF = DAG.getMachineFunction();
17186     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17187     unsigned Reg;
17188     if (RegInfo->hasBasePointer(MF))
17189       Reg = RegInfo->getBaseRegister();
17190     else // This function handles the SP or FP case.
17191       Reg = RegInfo->getPtrSizedFrameRegister(MF);
17192     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
17193   }
17194   }
17195 }
17196
17197 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17198                               SDValue Src, SDValue Mask, SDValue Base,
17199                               SDValue Index, SDValue ScaleOp, SDValue Chain,
17200                               const X86Subtarget * Subtarget) {
17201   SDLoc dl(Op);
17202   auto *C = cast<ConstantSDNode>(ScaleOp);
17203   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17204   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17205                              Index.getSimpleValueType().getVectorNumElements());
17206   SDValue MaskInReg;
17207   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17208   if (MaskC)
17209     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17210   else {
17211     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17212                                      Mask.getSimpleValueType().getSizeInBits());
17213
17214     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17215     // are extracted by EXTRACT_SUBVECTOR.
17216     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17217                             DAG.getBitcast(BitcastVT, Mask),
17218                             DAG.getIntPtrConstant(0, dl));
17219   }
17220   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17221   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17222   SDValue Segment = DAG.getRegister(0, MVT::i32);
17223   if (Src.getOpcode() == ISD::UNDEF)
17224     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
17225   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17226   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17227   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17228   return DAG.getMergeValues(RetOps, dl);
17229 }
17230
17231 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17232                                SDValue Src, SDValue Mask, SDValue Base,
17233                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
17234   SDLoc dl(Op);
17235   auto *C = cast<ConstantSDNode>(ScaleOp);
17236   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17237   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17238   SDValue Segment = DAG.getRegister(0, MVT::i32);
17239   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17240                              Index.getSimpleValueType().getVectorNumElements());
17241   SDValue MaskInReg;
17242   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17243   if (MaskC)
17244     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17245   else {
17246     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17247                                      Mask.getSimpleValueType().getSizeInBits());
17248
17249     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17250     // are extracted by EXTRACT_SUBVECTOR.
17251     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17252                             DAG.getBitcast(BitcastVT, Mask),
17253                             DAG.getIntPtrConstant(0, dl));
17254   }
17255   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17256   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17257   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17258   return SDValue(Res, 1);
17259 }
17260
17261 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17262                                SDValue Mask, SDValue Base, SDValue Index,
17263                                SDValue ScaleOp, SDValue Chain) {
17264   SDLoc dl(Op);
17265   auto *C = cast<ConstantSDNode>(ScaleOp);
17266   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17267   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17268   SDValue Segment = DAG.getRegister(0, MVT::i32);
17269   MVT MaskVT =
17270     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17271   SDValue MaskInReg;
17272   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17273   if (MaskC)
17274     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17275   else
17276     MaskInReg = DAG.getBitcast(MaskVT, Mask);
17277   //SDVTList VTs = DAG.getVTList(MVT::Other);
17278   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17279   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17280   return SDValue(Res, 0);
17281 }
17282
17283 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17284 // read performance monitor counters (x86_rdpmc).
17285 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17286                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17287                               SmallVectorImpl<SDValue> &Results) {
17288   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17289   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17290   SDValue LO, HI;
17291
17292   // The ECX register is used to select the index of the performance counter
17293   // to read.
17294   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17295                                    N->getOperand(2));
17296   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17297
17298   // Reads the content of a 64-bit performance counter and returns it in the
17299   // registers EDX:EAX.
17300   if (Subtarget->is64Bit()) {
17301     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17302     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17303                             LO.getValue(2));
17304   } else {
17305     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17306     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17307                             LO.getValue(2));
17308   }
17309   Chain = HI.getValue(1);
17310
17311   if (Subtarget->is64Bit()) {
17312     // The EAX register is loaded with the low-order 32 bits. The EDX register
17313     // is loaded with the supported high-order bits of the counter.
17314     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17315                               DAG.getConstant(32, DL, MVT::i8));
17316     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17317     Results.push_back(Chain);
17318     return;
17319   }
17320
17321   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17322   SDValue Ops[] = { LO, HI };
17323   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17324   Results.push_back(Pair);
17325   Results.push_back(Chain);
17326 }
17327
17328 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17329 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17330 // also used to custom lower READCYCLECOUNTER nodes.
17331 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17332                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17333                               SmallVectorImpl<SDValue> &Results) {
17334   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17335   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17336   SDValue LO, HI;
17337
17338   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17339   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17340   // and the EAX register is loaded with the low-order 32 bits.
17341   if (Subtarget->is64Bit()) {
17342     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17343     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17344                             LO.getValue(2));
17345   } else {
17346     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17347     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17348                             LO.getValue(2));
17349   }
17350   SDValue Chain = HI.getValue(1);
17351
17352   if (Opcode == X86ISD::RDTSCP_DAG) {
17353     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17354
17355     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17356     // the ECX register. Add 'ecx' explicitly to the chain.
17357     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17358                                      HI.getValue(2));
17359     // Explicitly store the content of ECX at the location passed in input
17360     // to the 'rdtscp' intrinsic.
17361     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17362                          MachinePointerInfo(), false, false, 0);
17363   }
17364
17365   if (Subtarget->is64Bit()) {
17366     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17367     // the EAX register is loaded with the low-order 32 bits.
17368     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17369                               DAG.getConstant(32, DL, MVT::i8));
17370     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17371     Results.push_back(Chain);
17372     return;
17373   }
17374
17375   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17376   SDValue Ops[] = { LO, HI };
17377   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17378   Results.push_back(Pair);
17379   Results.push_back(Chain);
17380 }
17381
17382 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17383                                      SelectionDAG &DAG) {
17384   SmallVector<SDValue, 2> Results;
17385   SDLoc DL(Op);
17386   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17387                           Results);
17388   return DAG.getMergeValues(Results, DL);
17389 }
17390
17391 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17392   MachineFunction &MF = DAG.getMachineFunction();
17393   SDValue Chain = Op.getOperand(0);
17394   SDValue RegNode = Op.getOperand(2);
17395   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17396   if (!EHInfo)
17397     report_fatal_error("EH registrations only live in functions using WinEH");
17398
17399   // Cast the operand to an alloca, and remember the frame index.
17400   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17401   if (!FINode)
17402     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17403   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17404
17405   // Return the chain operand without making any DAG nodes.
17406   return Chain;
17407 }
17408
17409 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17410 /// return truncate Store/MaskedStore Node
17411 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17412                                                SelectionDAG &DAG,
17413                                                MVT ElementType) {
17414   SDLoc dl(Op);
17415   SDValue Mask = Op.getOperand(4);
17416   SDValue DataToTruncate = Op.getOperand(3);
17417   SDValue Addr = Op.getOperand(2);
17418   SDValue Chain = Op.getOperand(0);
17419
17420   MVT VT  = DataToTruncate.getSimpleValueType();
17421   MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17422
17423   if (isAllOnesConstant(Mask)) // return just a truncate store
17424     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17425                              MachinePointerInfo(), SVT, false, false,
17426                              SVT.getScalarSizeInBits()/8);
17427
17428   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17429   MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17430                                    Mask.getSimpleValueType().getSizeInBits());
17431   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17432   // are extracted by EXTRACT_SUBVECTOR.
17433   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17434                               DAG.getBitcast(BitcastVT, Mask),
17435                               DAG.getIntPtrConstant(0, dl));
17436
17437   MachineMemOperand *MMO = DAG.getMachineFunction().
17438     getMachineMemOperand(MachinePointerInfo(),
17439                          MachineMemOperand::MOStore, SVT.getStoreSize(),
17440                          SVT.getScalarSizeInBits()/8);
17441
17442   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17443                             VMask, SVT, MMO, true);
17444 }
17445
17446 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17447                                       SelectionDAG &DAG) {
17448   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17449
17450   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17451   if (!IntrData) {
17452     if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17453       return MarkEHRegistrationNode(Op, DAG);
17454     if (IntNo == llvm::Intrinsic::x86_flags_read_u32 ||
17455         IntNo == llvm::Intrinsic::x86_flags_read_u64 ||
17456         IntNo == llvm::Intrinsic::x86_flags_write_u32 ||
17457         IntNo == llvm::Intrinsic::x86_flags_write_u64) {
17458       // We need a frame pointer because this will get lowered to a PUSH/POP
17459       // sequence.
17460       MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17461       MFI->setHasCopyImplyingStackAdjustment(true);
17462       // Don't do anything here, we will expand these intrinsics out later
17463       // during ExpandISelPseudos in EmitInstrWithCustomInserter.
17464       return SDValue();
17465     }
17466     return SDValue();
17467   }
17468
17469   SDLoc dl(Op);
17470   switch(IntrData->Type) {
17471   default: llvm_unreachable("Unknown Intrinsic Type");
17472   case RDSEED:
17473   case RDRAND: {
17474     // Emit the node with the right value type.
17475     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17476     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17477
17478     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17479     // Otherwise return the value from Rand, which is always 0, casted to i32.
17480     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17481                       DAG.getConstant(1, dl, Op->getValueType(1)),
17482                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
17483                       SDValue(Result.getNode(), 1) };
17484     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17485                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17486                                   Ops);
17487
17488     // Return { result, isValid, chain }.
17489     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17490                        SDValue(Result.getNode(), 2));
17491   }
17492   case GATHER: {
17493   //gather(v1, mask, index, base, scale);
17494     SDValue Chain = Op.getOperand(0);
17495     SDValue Src   = Op.getOperand(2);
17496     SDValue Base  = Op.getOperand(3);
17497     SDValue Index = Op.getOperand(4);
17498     SDValue Mask  = Op.getOperand(5);
17499     SDValue Scale = Op.getOperand(6);
17500     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17501                          Chain, Subtarget);
17502   }
17503   case SCATTER: {
17504   //scatter(base, mask, index, v1, scale);
17505     SDValue Chain = Op.getOperand(0);
17506     SDValue Base  = Op.getOperand(2);
17507     SDValue Mask  = Op.getOperand(3);
17508     SDValue Index = Op.getOperand(4);
17509     SDValue Src   = Op.getOperand(5);
17510     SDValue Scale = Op.getOperand(6);
17511     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17512                           Scale, Chain);
17513   }
17514   case PREFETCH: {
17515     SDValue Hint = Op.getOperand(6);
17516     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17517     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17518     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17519     SDValue Chain = Op.getOperand(0);
17520     SDValue Mask  = Op.getOperand(2);
17521     SDValue Index = Op.getOperand(3);
17522     SDValue Base  = Op.getOperand(4);
17523     SDValue Scale = Op.getOperand(5);
17524     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17525   }
17526   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17527   case RDTSC: {
17528     SmallVector<SDValue, 2> Results;
17529     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17530                             Results);
17531     return DAG.getMergeValues(Results, dl);
17532   }
17533   // Read Performance Monitoring Counters.
17534   case RDPMC: {
17535     SmallVector<SDValue, 2> Results;
17536     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17537     return DAG.getMergeValues(Results, dl);
17538   }
17539   // XTEST intrinsics.
17540   case XTEST: {
17541     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17542     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17543     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17544                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17545                                 InTrans);
17546     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17547     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17548                        Ret, SDValue(InTrans.getNode(), 1));
17549   }
17550   // ADC/ADCX/SBB
17551   case ADX: {
17552     SmallVector<SDValue, 2> Results;
17553     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17554     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17555     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17556                                 DAG.getConstant(-1, dl, MVT::i8));
17557     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17558                               Op.getOperand(4), GenCF.getValue(1));
17559     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17560                                  Op.getOperand(5), MachinePointerInfo(),
17561                                  false, false, 0);
17562     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17563                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17564                                 Res.getValue(1));
17565     Results.push_back(SetCC);
17566     Results.push_back(Store);
17567     return DAG.getMergeValues(Results, dl);
17568   }
17569   case COMPRESS_TO_MEM: {
17570     SDValue Mask = Op.getOperand(4);
17571     SDValue DataToCompress = Op.getOperand(3);
17572     SDValue Addr = Op.getOperand(2);
17573     SDValue Chain = Op.getOperand(0);
17574
17575     MVT VT = DataToCompress.getSimpleValueType();
17576     if (isAllOnesConstant(Mask)) // return just a store
17577       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17578                           MachinePointerInfo(), false, false,
17579                           VT.getScalarSizeInBits()/8);
17580
17581     SDValue Compressed =
17582       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17583                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17584     return DAG.getStore(Chain, dl, Compressed, Addr,
17585                         MachinePointerInfo(), false, false,
17586                         VT.getScalarSizeInBits()/8);
17587   }
17588   case TRUNCATE_TO_MEM_VI8:
17589     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17590   case TRUNCATE_TO_MEM_VI16:
17591     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17592   case TRUNCATE_TO_MEM_VI32:
17593     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17594   case EXPAND_FROM_MEM: {
17595     SDValue Mask = Op.getOperand(4);
17596     SDValue PassThru = Op.getOperand(3);
17597     SDValue Addr = Op.getOperand(2);
17598     SDValue Chain = Op.getOperand(0);
17599     MVT VT = Op.getSimpleValueType();
17600
17601     if (isAllOnesConstant(Mask)) // return just a load
17602       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17603                          false, VT.getScalarSizeInBits()/8);
17604
17605     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17606                                        false, false, false,
17607                                        VT.getScalarSizeInBits()/8);
17608
17609     SDValue Results[] = {
17610       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17611                            Mask, PassThru, Subtarget, DAG), Chain};
17612     return DAG.getMergeValues(Results, dl);
17613   }
17614   case LOADU:
17615   case LOADA: {
17616     SDValue Mask = Op.getOperand(4);
17617     SDValue PassThru = Op.getOperand(3);
17618     SDValue Addr = Op.getOperand(2);
17619     SDValue Chain = Op.getOperand(0);
17620     MVT VT = Op.getSimpleValueType();
17621
17622     MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
17623     assert(MemIntr && "Expected MemIntrinsicSDNode!");
17624
17625     if (isAllOnesConstant(Mask)) // return just a load
17626       return DAG.getLoad(VT, dl, Chain, Addr, MemIntr->getMemOperand());
17627
17628     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17629     SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
17630     return DAG.getMaskedLoad(VT, dl, Chain, Addr, VMask, PassThru, VT,
17631                              MemIntr->getMemOperand(), ISD::NON_EXTLOAD);
17632   }
17633   }
17634 }
17635
17636 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17637                                            SelectionDAG &DAG) const {
17638   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17639   MFI->setReturnAddressIsTaken(true);
17640
17641   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17642     return SDValue();
17643
17644   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17645   SDLoc dl(Op);
17646   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17647
17648   if (Depth > 0) {
17649     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17650     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17651     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17652     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17653                        DAG.getNode(ISD::ADD, dl, PtrVT,
17654                                    FrameAddr, Offset),
17655                        MachinePointerInfo(), false, false, false, 0);
17656   }
17657
17658   // Just load the return address.
17659   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17660   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17661                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17662 }
17663
17664 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17665   MachineFunction &MF = DAG.getMachineFunction();
17666   MachineFrameInfo *MFI = MF.getFrameInfo();
17667   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17668   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17669   EVT VT = Op.getValueType();
17670
17671   MFI->setFrameAddressIsTaken(true);
17672
17673   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17674     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17675     // is not possible to crawl up the stack without looking at the unwind codes
17676     // simultaneously.
17677     int FrameAddrIndex = FuncInfo->getFAIndex();
17678     if (!FrameAddrIndex) {
17679       // Set up a frame object for the return address.
17680       unsigned SlotSize = RegInfo->getSlotSize();
17681       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17682           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17683       FuncInfo->setFAIndex(FrameAddrIndex);
17684     }
17685     return DAG.getFrameIndex(FrameAddrIndex, VT);
17686   }
17687
17688   unsigned FrameReg =
17689       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17690   SDLoc dl(Op);  // FIXME probably not meaningful
17691   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17692   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17693           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17694          "Invalid Frame Register!");
17695   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17696   while (Depth--)
17697     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17698                             MachinePointerInfo(),
17699                             false, false, false, 0);
17700   return FrameAddr;
17701 }
17702
17703 // FIXME? Maybe this could be a TableGen attribute on some registers and
17704 // this table could be generated automatically from RegInfo.
17705 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17706                                               SelectionDAG &DAG) const {
17707   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17708   const MachineFunction &MF = DAG.getMachineFunction();
17709
17710   unsigned Reg = StringSwitch<unsigned>(RegName)
17711                        .Case("esp", X86::ESP)
17712                        .Case("rsp", X86::RSP)
17713                        .Case("ebp", X86::EBP)
17714                        .Case("rbp", X86::RBP)
17715                        .Default(0);
17716
17717   if (Reg == X86::EBP || Reg == X86::RBP) {
17718     if (!TFI.hasFP(MF))
17719       report_fatal_error("register " + StringRef(RegName) +
17720                          " is allocatable: function has no frame pointer");
17721 #ifndef NDEBUG
17722     else {
17723       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17724       unsigned FrameReg =
17725           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17726       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17727              "Invalid Frame Register!");
17728     }
17729 #endif
17730   }
17731
17732   if (Reg)
17733     return Reg;
17734
17735   report_fatal_error("Invalid register name global variable");
17736 }
17737
17738 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17739                                                      SelectionDAG &DAG) const {
17740   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17741   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17742 }
17743
17744 unsigned X86TargetLowering::getExceptionPointerRegister(
17745     const Constant *PersonalityFn) const {
17746   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17747     return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17748
17749   return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17750 }
17751
17752 unsigned X86TargetLowering::getExceptionSelectorRegister(
17753     const Constant *PersonalityFn) const {
17754   // Funclet personalities don't use selectors (the runtime does the selection).
17755   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17756   return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17757 }
17758
17759 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17760   SDValue Chain     = Op.getOperand(0);
17761   SDValue Offset    = Op.getOperand(1);
17762   SDValue Handler   = Op.getOperand(2);
17763   SDLoc dl      (Op);
17764
17765   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17766   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17767   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17768   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17769           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17770          "Invalid Frame Register!");
17771   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17772   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17773
17774   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17775                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17776                                                        dl));
17777   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17778   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17779                        false, false, 0);
17780   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17781
17782   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17783                      DAG.getRegister(StoreAddrReg, PtrVT));
17784 }
17785
17786 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17787                                                SelectionDAG &DAG) const {
17788   SDLoc DL(Op);
17789   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17790                      DAG.getVTList(MVT::i32, MVT::Other),
17791                      Op.getOperand(0), Op.getOperand(1));
17792 }
17793
17794 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17795                                                 SelectionDAG &DAG) const {
17796   SDLoc DL(Op);
17797   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17798                      Op.getOperand(0), Op.getOperand(1));
17799 }
17800
17801 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17802   return Op.getOperand(0);
17803 }
17804
17805 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17806                                                 SelectionDAG &DAG) const {
17807   SDValue Root = Op.getOperand(0);
17808   SDValue Trmp = Op.getOperand(1); // trampoline
17809   SDValue FPtr = Op.getOperand(2); // nested function
17810   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17811   SDLoc dl (Op);
17812
17813   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17814   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17815
17816   if (Subtarget->is64Bit()) {
17817     SDValue OutChains[6];
17818
17819     // Large code-model.
17820     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17821     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17822
17823     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17824     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17825
17826     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17827
17828     // Load the pointer to the nested function into R11.
17829     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17830     SDValue Addr = Trmp;
17831     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17832                                 Addr, MachinePointerInfo(TrmpAddr),
17833                                 false, false, 0);
17834
17835     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17836                        DAG.getConstant(2, dl, MVT::i64));
17837     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17838                                 MachinePointerInfo(TrmpAddr, 2),
17839                                 false, false, 2);
17840
17841     // Load the 'nest' parameter value into R10.
17842     // R10 is specified in X86CallingConv.td
17843     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17844     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17845                        DAG.getConstant(10, dl, MVT::i64));
17846     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17847                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17848                                 false, false, 0);
17849
17850     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17851                        DAG.getConstant(12, dl, MVT::i64));
17852     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17853                                 MachinePointerInfo(TrmpAddr, 12),
17854                                 false, false, 2);
17855
17856     // Jump to the nested function.
17857     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17858     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17859                        DAG.getConstant(20, dl, MVT::i64));
17860     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17861                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17862                                 false, false, 0);
17863
17864     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17865     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17866                        DAG.getConstant(22, dl, MVT::i64));
17867     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17868                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17869                                 false, false, 0);
17870
17871     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17872   } else {
17873     const Function *Func =
17874       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17875     CallingConv::ID CC = Func->getCallingConv();
17876     unsigned NestReg;
17877
17878     switch (CC) {
17879     default:
17880       llvm_unreachable("Unsupported calling convention");
17881     case CallingConv::C:
17882     case CallingConv::X86_StdCall: {
17883       // Pass 'nest' parameter in ECX.
17884       // Must be kept in sync with X86CallingConv.td
17885       NestReg = X86::ECX;
17886
17887       // Check that ECX wasn't needed by an 'inreg' parameter.
17888       FunctionType *FTy = Func->getFunctionType();
17889       const AttributeSet &Attrs = Func->getAttributes();
17890
17891       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17892         unsigned InRegCount = 0;
17893         unsigned Idx = 1;
17894
17895         for (FunctionType::param_iterator I = FTy->param_begin(),
17896              E = FTy->param_end(); I != E; ++I, ++Idx)
17897           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17898             auto &DL = DAG.getDataLayout();
17899             // FIXME: should only count parameters that are lowered to integers.
17900             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17901           }
17902
17903         if (InRegCount > 2) {
17904           report_fatal_error("Nest register in use - reduce number of inreg"
17905                              " parameters!");
17906         }
17907       }
17908       break;
17909     }
17910     case CallingConv::X86_FastCall:
17911     case CallingConv::X86_ThisCall:
17912     case CallingConv::Fast:
17913       // Pass 'nest' parameter in EAX.
17914       // Must be kept in sync with X86CallingConv.td
17915       NestReg = X86::EAX;
17916       break;
17917     }
17918
17919     SDValue OutChains[4];
17920     SDValue Addr, Disp;
17921
17922     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17923                        DAG.getConstant(10, dl, MVT::i32));
17924     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17925
17926     // This is storing the opcode for MOV32ri.
17927     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17928     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17929     OutChains[0] = DAG.getStore(Root, dl,
17930                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17931                                 Trmp, MachinePointerInfo(TrmpAddr),
17932                                 false, false, 0);
17933
17934     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17935                        DAG.getConstant(1, dl, MVT::i32));
17936     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17937                                 MachinePointerInfo(TrmpAddr, 1),
17938                                 false, false, 1);
17939
17940     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17941     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17942                        DAG.getConstant(5, dl, MVT::i32));
17943     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17944                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17945                                 false, false, 1);
17946
17947     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17948                        DAG.getConstant(6, dl, MVT::i32));
17949     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17950                                 MachinePointerInfo(TrmpAddr, 6),
17951                                 false, false, 1);
17952
17953     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17954   }
17955 }
17956
17957 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17958                                             SelectionDAG &DAG) const {
17959   /*
17960    The rounding mode is in bits 11:10 of FPSR, and has the following
17961    settings:
17962      00 Round to nearest
17963      01 Round to -inf
17964      10 Round to +inf
17965      11 Round to 0
17966
17967   FLT_ROUNDS, on the other hand, expects the following:
17968     -1 Undefined
17969      0 Round to 0
17970      1 Round to nearest
17971      2 Round to +inf
17972      3 Round to -inf
17973
17974   To perform the conversion, we do:
17975     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17976   */
17977
17978   MachineFunction &MF = DAG.getMachineFunction();
17979   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17980   unsigned StackAlignment = TFI.getStackAlignment();
17981   MVT VT = Op.getSimpleValueType();
17982   SDLoc DL(Op);
17983
17984   // Save FP Control Word to stack slot
17985   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17986   SDValue StackSlot =
17987       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17988
17989   MachineMemOperand *MMO =
17990       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17991                               MachineMemOperand::MOStore, 2, 2);
17992
17993   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17994   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17995                                           DAG.getVTList(MVT::Other),
17996                                           Ops, MVT::i16, MMO);
17997
17998   // Load FP Control Word from stack slot
17999   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
18000                             MachinePointerInfo(), false, false, false, 0);
18001
18002   // Transform as necessary
18003   SDValue CWD1 =
18004     DAG.getNode(ISD::SRL, DL, MVT::i16,
18005                 DAG.getNode(ISD::AND, DL, MVT::i16,
18006                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
18007                 DAG.getConstant(11, DL, MVT::i8));
18008   SDValue CWD2 =
18009     DAG.getNode(ISD::SRL, DL, MVT::i16,
18010                 DAG.getNode(ISD::AND, DL, MVT::i16,
18011                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
18012                 DAG.getConstant(9, DL, MVT::i8));
18013
18014   SDValue RetVal =
18015     DAG.getNode(ISD::AND, DL, MVT::i16,
18016                 DAG.getNode(ISD::ADD, DL, MVT::i16,
18017                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
18018                             DAG.getConstant(1, DL, MVT::i16)),
18019                 DAG.getConstant(3, DL, MVT::i16));
18020
18021   return DAG.getNode((VT.getSizeInBits() < 16 ?
18022                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
18023 }
18024
18025 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
18026 //
18027 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
18028 //    to 512-bit vector.
18029 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
18030 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
18031 //    split the vector, perform operation on it's Lo a Hi part and
18032 //    concatenate the results.
18033 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
18034   SDLoc dl(Op);
18035   MVT VT = Op.getSimpleValueType();
18036   MVT EltVT = VT.getVectorElementType();
18037   unsigned NumElems = VT.getVectorNumElements();
18038
18039   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
18040     // Extend to 512 bit vector.
18041     assert((VT.is256BitVector() || VT.is128BitVector()) &&
18042               "Unsupported value type for operation");
18043
18044     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
18045     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
18046                                  DAG.getUNDEF(NewVT),
18047                                  Op.getOperand(0),
18048                                  DAG.getIntPtrConstant(0, dl));
18049     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
18050
18051     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
18052                        DAG.getIntPtrConstant(0, dl));
18053   }
18054
18055   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
18056           "Unsupported element type");
18057
18058   if (16 < NumElems) {
18059     // Split vector, it's Lo and Hi parts will be handled in next iteration.
18060     SDValue Lo, Hi;
18061     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
18062     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
18063
18064     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
18065     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
18066
18067     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
18068   }
18069
18070   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
18071
18072   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
18073           "Unsupported value type for operation");
18074
18075   // Use native supported vector instruction vplzcntd.
18076   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
18077   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
18078   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
18079   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
18080
18081   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
18082 }
18083
18084 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
18085                          SelectionDAG &DAG) {
18086   MVT VT = Op.getSimpleValueType();
18087   MVT OpVT = VT;
18088   unsigned NumBits = VT.getSizeInBits();
18089   SDLoc dl(Op);
18090
18091   if (VT.isVector() && Subtarget->hasAVX512())
18092     return LowerVectorCTLZ_AVX512(Op, DAG);
18093
18094   Op = Op.getOperand(0);
18095   if (VT == MVT::i8) {
18096     // Zero extend to i32 since there is not an i8 bsr.
18097     OpVT = MVT::i32;
18098     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18099   }
18100
18101   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
18102   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18103   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18104
18105   // If src is zero (i.e. bsr sets ZF), returns NumBits.
18106   SDValue Ops[] = {
18107     Op,
18108     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
18109     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18110     Op.getValue(1)
18111   };
18112   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
18113
18114   // Finally xor with NumBits-1.
18115   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18116                    DAG.getConstant(NumBits - 1, dl, OpVT));
18117
18118   if (VT == MVT::i8)
18119     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18120   return Op;
18121 }
18122
18123 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
18124                                     SelectionDAG &DAG) {
18125   MVT VT = Op.getSimpleValueType();
18126   EVT OpVT = VT;
18127   unsigned NumBits = VT.getSizeInBits();
18128   SDLoc dl(Op);
18129
18130   Op = Op.getOperand(0);
18131   if (VT == MVT::i8) {
18132     // Zero extend to i32 since there is not an i8 bsr.
18133     OpVT = MVT::i32;
18134     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18135   }
18136
18137   // Issue a bsr (scan bits in reverse).
18138   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18139   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18140
18141   // And xor with NumBits-1.
18142   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18143                    DAG.getConstant(NumBits - 1, dl, OpVT));
18144
18145   if (VT == MVT::i8)
18146     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18147   return Op;
18148 }
18149
18150 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18151   MVT VT = Op.getSimpleValueType();
18152   unsigned NumBits = VT.getScalarSizeInBits();
18153   SDLoc dl(Op);
18154
18155   if (VT.isVector()) {
18156     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18157
18158     SDValue N0 = Op.getOperand(0);
18159     SDValue Zero = DAG.getConstant(0, dl, VT);
18160
18161     // lsb(x) = (x & -x)
18162     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
18163                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
18164
18165     // cttz_undef(x) = (width - 1) - ctlz(lsb)
18166     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
18167         TLI.isOperationLegal(ISD::CTLZ, VT)) {
18168       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
18169       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
18170                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
18171     }
18172
18173     // cttz(x) = ctpop(lsb - 1)
18174     SDValue One = DAG.getConstant(1, dl, VT);
18175     return DAG.getNode(ISD::CTPOP, dl, VT,
18176                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
18177   }
18178
18179   assert(Op.getOpcode() == ISD::CTTZ &&
18180          "Only scalar CTTZ requires custom lowering");
18181
18182   // Issue a bsf (scan bits forward) which also sets EFLAGS.
18183   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18184   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
18185
18186   // If src is zero (i.e. bsf sets ZF), returns NumBits.
18187   SDValue Ops[] = {
18188     Op,
18189     DAG.getConstant(NumBits, dl, VT),
18190     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18191     Op.getValue(1)
18192   };
18193   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18194 }
18195
18196 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18197 // ones, and then concatenate the result back.
18198 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18199   MVT VT = Op.getSimpleValueType();
18200
18201   assert(VT.is256BitVector() && VT.isInteger() &&
18202          "Unsupported value type for operation");
18203
18204   unsigned NumElems = VT.getVectorNumElements();
18205   SDLoc dl(Op);
18206
18207   // Extract the LHS vectors
18208   SDValue LHS = Op.getOperand(0);
18209   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18210   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18211
18212   // Extract the RHS vectors
18213   SDValue RHS = Op.getOperand(1);
18214   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18215   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18216
18217   MVT EltVT = VT.getVectorElementType();
18218   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18219
18220   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18221                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18222                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18223 }
18224
18225 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18226   if (Op.getValueType() == MVT::i1)
18227     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18228                        Op.getOperand(0), Op.getOperand(1));
18229   assert(Op.getSimpleValueType().is256BitVector() &&
18230          Op.getSimpleValueType().isInteger() &&
18231          "Only handle AVX 256-bit vector integer operation");
18232   return Lower256IntArith(Op, DAG);
18233 }
18234
18235 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18236   if (Op.getValueType() == MVT::i1)
18237     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18238                        Op.getOperand(0), Op.getOperand(1));
18239   assert(Op.getSimpleValueType().is256BitVector() &&
18240          Op.getSimpleValueType().isInteger() &&
18241          "Only handle AVX 256-bit vector integer operation");
18242   return Lower256IntArith(Op, DAG);
18243 }
18244
18245 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
18246   assert(Op.getSimpleValueType().is256BitVector() &&
18247          Op.getSimpleValueType().isInteger() &&
18248          "Only handle AVX 256-bit vector integer operation");
18249   return Lower256IntArith(Op, DAG);
18250 }
18251
18252 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18253                         SelectionDAG &DAG) {
18254   SDLoc dl(Op);
18255   MVT VT = Op.getSimpleValueType();
18256
18257   if (VT == MVT::i1)
18258     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
18259
18260   // Decompose 256-bit ops into smaller 128-bit ops.
18261   if (VT.is256BitVector() && !Subtarget->hasInt256())
18262     return Lower256IntArith(Op, DAG);
18263
18264   SDValue A = Op.getOperand(0);
18265   SDValue B = Op.getOperand(1);
18266
18267   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
18268   // pairs, multiply and truncate.
18269   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
18270     if (Subtarget->hasInt256()) {
18271       if (VT == MVT::v32i8) {
18272         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
18273         SDValue Lo = DAG.getIntPtrConstant(0, dl);
18274         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
18275         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
18276         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
18277         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
18278         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18279         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18280                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18281                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18282       }
18283
18284       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18285       return DAG.getNode(
18286           ISD::TRUNCATE, dl, VT,
18287           DAG.getNode(ISD::MUL, dl, ExVT,
18288                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18289                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18290     }
18291
18292     assert(VT == MVT::v16i8 &&
18293            "Pre-AVX2 support only supports v16i8 multiplication");
18294     MVT ExVT = MVT::v8i16;
18295
18296     // Extract the lo parts and sign extend to i16
18297     SDValue ALo, BLo;
18298     if (Subtarget->hasSSE41()) {
18299       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18300       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18301     } else {
18302       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18303                               -1, 4, -1, 5, -1, 6, -1, 7};
18304       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18305       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18306       ALo = DAG.getBitcast(ExVT, ALo);
18307       BLo = DAG.getBitcast(ExVT, BLo);
18308       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18309       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18310     }
18311
18312     // Extract the hi parts and sign extend to i16
18313     SDValue AHi, BHi;
18314     if (Subtarget->hasSSE41()) {
18315       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
18316                               -1, -1, -1, -1, -1, -1, -1, -1};
18317       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18318       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18319       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18320       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18321     } else {
18322       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
18323                               -1, 12, -1, 13, -1, 14, -1, 15};
18324       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18325       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18326       AHi = DAG.getBitcast(ExVT, AHi);
18327       BHi = DAG.getBitcast(ExVT, BHi);
18328       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18329       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18330     }
18331
18332     // Multiply, mask the lower 8bits of the lo/hi results and pack
18333     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18334     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18335     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18336     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18337     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18338   }
18339
18340   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18341   if (VT == MVT::v4i32) {
18342     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18343            "Should not custom lower when pmuldq is available!");
18344
18345     // Extract the odd parts.
18346     static const int UnpackMask[] = { 1, -1, 3, -1 };
18347     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18348     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18349
18350     // Multiply the even parts.
18351     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18352     // Now multiply odd parts.
18353     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18354
18355     Evens = DAG.getBitcast(VT, Evens);
18356     Odds = DAG.getBitcast(VT, Odds);
18357
18358     // Merge the two vectors back together with a shuffle. This expands into 2
18359     // shuffles.
18360     static const int ShufMask[] = { 0, 4, 2, 6 };
18361     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18362   }
18363
18364   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18365          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18366
18367   //  Ahi = psrlqi(a, 32);
18368   //  Bhi = psrlqi(b, 32);
18369   //
18370   //  AloBlo = pmuludq(a, b);
18371   //  AloBhi = pmuludq(a, Bhi);
18372   //  AhiBlo = pmuludq(Ahi, b);
18373
18374   //  AloBhi = psllqi(AloBhi, 32);
18375   //  AhiBlo = psllqi(AhiBlo, 32);
18376   //  return AloBlo + AloBhi + AhiBlo;
18377
18378   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18379   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18380
18381   SDValue AhiBlo = Ahi;
18382   SDValue AloBhi = Bhi;
18383   // Bit cast to 32-bit vectors for MULUDQ
18384   MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18385                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18386   A = DAG.getBitcast(MulVT, A);
18387   B = DAG.getBitcast(MulVT, B);
18388   Ahi = DAG.getBitcast(MulVT, Ahi);
18389   Bhi = DAG.getBitcast(MulVT, Bhi);
18390
18391   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18392   // After shifting right const values the result may be all-zero.
18393   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18394     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18395     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18396   }
18397   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18398     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18399     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18400   }
18401
18402   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18403   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18404 }
18405
18406 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18407   assert(Subtarget->isTargetWin64() && "Unexpected target");
18408   EVT VT = Op.getValueType();
18409   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18410          "Unexpected return type for lowering");
18411
18412   RTLIB::Libcall LC;
18413   bool isSigned;
18414   switch (Op->getOpcode()) {
18415   default: llvm_unreachable("Unexpected request for libcall!");
18416   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18417   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18418   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18419   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18420   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18421   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18422   }
18423
18424   SDLoc dl(Op);
18425   SDValue InChain = DAG.getEntryNode();
18426
18427   TargetLowering::ArgListTy Args;
18428   TargetLowering::ArgListEntry Entry;
18429   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18430     EVT ArgVT = Op->getOperand(i).getValueType();
18431     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18432            "Unexpected argument type for lowering");
18433     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18434     Entry.Node = StackPtr;
18435     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18436                            false, false, 16);
18437     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18438     Entry.Ty = PointerType::get(ArgTy,0);
18439     Entry.isSExt = false;
18440     Entry.isZExt = false;
18441     Args.push_back(Entry);
18442   }
18443
18444   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18445                                          getPointerTy(DAG.getDataLayout()));
18446
18447   TargetLowering::CallLoweringInfo CLI(DAG);
18448   CLI.setDebugLoc(dl).setChain(InChain)
18449     .setCallee(getLibcallCallingConv(LC),
18450                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18451                Callee, std::move(Args), 0)
18452     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18453
18454   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18455   return DAG.getBitcast(VT, CallInfo.first);
18456 }
18457
18458 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18459                              SelectionDAG &DAG) {
18460   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18461   MVT VT = Op0.getSimpleValueType();
18462   SDLoc dl(Op);
18463
18464   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18465          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18466
18467   // PMULxD operations multiply each even value (starting at 0) of LHS with
18468   // the related value of RHS and produce a widen result.
18469   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18470   // => <2 x i64> <ae|cg>
18471   //
18472   // In other word, to have all the results, we need to perform two PMULxD:
18473   // 1. one with the even values.
18474   // 2. one with the odd values.
18475   // To achieve #2, with need to place the odd values at an even position.
18476   //
18477   // Place the odd value at an even position (basically, shift all values 1
18478   // step to the left):
18479   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18480   // <a|b|c|d> => <b|undef|d|undef>
18481   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18482   // <e|f|g|h> => <f|undef|h|undef>
18483   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18484
18485   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18486   // ints.
18487   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18488   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18489   unsigned Opcode =
18490       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18491   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18492   // => <2 x i64> <ae|cg>
18493   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18494   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18495   // => <2 x i64> <bf|dh>
18496   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18497
18498   // Shuffle it back into the right order.
18499   SDValue Highs, Lows;
18500   if (VT == MVT::v8i32) {
18501     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18502     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18503     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18504     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18505   } else {
18506     const int HighMask[] = {1, 5, 3, 7};
18507     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18508     const int LowMask[] = {0, 4, 2, 6};
18509     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18510   }
18511
18512   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18513   // unsigned multiply.
18514   if (IsSigned && !Subtarget->hasSSE41()) {
18515     SDValue ShAmt = DAG.getConstant(
18516         31, dl,
18517         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18518     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18519                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18520     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18521                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18522
18523     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18524     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18525   }
18526
18527   // The first result of MUL_LOHI is actually the low value, followed by the
18528   // high value.
18529   SDValue Ops[] = {Lows, Highs};
18530   return DAG.getMergeValues(Ops, dl);
18531 }
18532
18533 // Return true if the required (according to Opcode) shift-imm form is natively
18534 // supported by the Subtarget
18535 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18536                                         unsigned Opcode) {
18537   if (VT.getScalarSizeInBits() < 16)
18538     return false;
18539
18540   if (VT.is512BitVector() &&
18541       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18542     return true;
18543
18544   bool LShift = VT.is128BitVector() ||
18545     (VT.is256BitVector() && Subtarget->hasInt256());
18546
18547   bool AShift = LShift && (Subtarget->hasVLX() ||
18548     (VT != MVT::v2i64 && VT != MVT::v4i64));
18549   return (Opcode == ISD::SRA) ? AShift : LShift;
18550 }
18551
18552 // The shift amount is a variable, but it is the same for all vector lanes.
18553 // These instructions are defined together with shift-immediate.
18554 static
18555 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18556                                       unsigned Opcode) {
18557   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18558 }
18559
18560 // Return true if the required (according to Opcode) variable-shift form is
18561 // natively supported by the Subtarget
18562 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18563                                     unsigned Opcode) {
18564
18565   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18566     return false;
18567
18568   // vXi16 supported only on AVX-512, BWI
18569   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18570     return false;
18571
18572   if (VT.is512BitVector() || Subtarget->hasVLX())
18573     return true;
18574
18575   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18576   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18577   return (Opcode == ISD::SRA) ? AShift : LShift;
18578 }
18579
18580 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18581                                          const X86Subtarget *Subtarget) {
18582   MVT VT = Op.getSimpleValueType();
18583   SDLoc dl(Op);
18584   SDValue R = Op.getOperand(0);
18585   SDValue Amt = Op.getOperand(1);
18586
18587   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18588     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18589
18590   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18591     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18592     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18593     SDValue Ex = DAG.getBitcast(ExVT, R);
18594
18595     if (ShiftAmt >= 32) {
18596       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18597       SDValue Upper =
18598           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18599       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18600                                                  ShiftAmt - 32, DAG);
18601       if (VT == MVT::v2i64)
18602         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18603       if (VT == MVT::v4i64)
18604         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18605                                   {9, 1, 11, 3, 13, 5, 15, 7});
18606     } else {
18607       // SRA upper i32, SHL whole i64 and select lower i32.
18608       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18609                                                  ShiftAmt, DAG);
18610       SDValue Lower =
18611           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18612       Lower = DAG.getBitcast(ExVT, Lower);
18613       if (VT == MVT::v2i64)
18614         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18615       if (VT == MVT::v4i64)
18616         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18617                                   {8, 1, 10, 3, 12, 5, 14, 7});
18618     }
18619     return DAG.getBitcast(VT, Ex);
18620   };
18621
18622   // Optimize shl/srl/sra with constant shift amount.
18623   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18624     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18625       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18626
18627       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18628         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18629
18630       // i64 SRA needs to be performed as partial shifts.
18631       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18632           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18633         return ArithmeticShiftRight64(ShiftAmt);
18634
18635       if (VT == MVT::v16i8 ||
18636           (Subtarget->hasInt256() && VT == MVT::v32i8) ||
18637           VT == MVT::v64i8) {
18638         unsigned NumElts = VT.getVectorNumElements();
18639         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18640
18641         // Simple i8 add case
18642         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18643           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18644
18645         // ashr(R, 7)  === cmp_slt(R, 0)
18646         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18647           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18648           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18649         }
18650
18651         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18652         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18653           return SDValue();
18654
18655         if (Op.getOpcode() == ISD::SHL) {
18656           // Make a large shift.
18657           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18658                                                    R, ShiftAmt, DAG);
18659           SHL = DAG.getBitcast(VT, SHL);
18660           // Zero out the rightmost bits.
18661           return DAG.getNode(ISD::AND, dl, VT, SHL,
18662                              DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
18663         }
18664         if (Op.getOpcode() == ISD::SRL) {
18665           // Make a large shift.
18666           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18667                                                    R, ShiftAmt, DAG);
18668           SRL = DAG.getBitcast(VT, SRL);
18669           // Zero out the leftmost bits.
18670           return DAG.getNode(ISD::AND, dl, VT, SRL,
18671                              DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
18672         }
18673         if (Op.getOpcode() == ISD::SRA) {
18674           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18675           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18676
18677           SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
18678           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18679           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18680           return Res;
18681         }
18682         llvm_unreachable("Unknown shift opcode.");
18683       }
18684     }
18685   }
18686
18687   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18688   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18689       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18690
18691     // Peek through any splat that was introduced for i64 shift vectorization.
18692     int SplatIndex = -1;
18693     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18694       if (SVN->isSplat()) {
18695         SplatIndex = SVN->getSplatIndex();
18696         Amt = Amt.getOperand(0);
18697         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18698                "Splat shuffle referencing second operand");
18699       }
18700
18701     if (Amt.getOpcode() != ISD::BITCAST ||
18702         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18703       return SDValue();
18704
18705     Amt = Amt.getOperand(0);
18706     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18707                      VT.getVectorNumElements();
18708     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18709     uint64_t ShiftAmt = 0;
18710     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18711     for (unsigned i = 0; i != Ratio; ++i) {
18712       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18713       if (!C)
18714         return SDValue();
18715       // 6 == Log2(64)
18716       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18717     }
18718
18719     // Check remaining shift amounts (if not a splat).
18720     if (SplatIndex < 0) {
18721       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18722         uint64_t ShAmt = 0;
18723         for (unsigned j = 0; j != Ratio; ++j) {
18724           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18725           if (!C)
18726             return SDValue();
18727           // 6 == Log2(64)
18728           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18729         }
18730         if (ShAmt != ShiftAmt)
18731           return SDValue();
18732       }
18733     }
18734
18735     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18736       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18737
18738     if (Op.getOpcode() == ISD::SRA)
18739       return ArithmeticShiftRight64(ShiftAmt);
18740   }
18741
18742   return SDValue();
18743 }
18744
18745 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18746                                         const X86Subtarget* Subtarget) {
18747   MVT VT = Op.getSimpleValueType();
18748   SDLoc dl(Op);
18749   SDValue R = Op.getOperand(0);
18750   SDValue Amt = Op.getOperand(1);
18751
18752   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18753     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18754
18755   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18756     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18757
18758   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18759     SDValue BaseShAmt;
18760     MVT EltVT = VT.getVectorElementType();
18761
18762     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18763       // Check if this build_vector node is doing a splat.
18764       // If so, then set BaseShAmt equal to the splat value.
18765       BaseShAmt = BV->getSplatValue();
18766       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18767         BaseShAmt = SDValue();
18768     } else {
18769       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18770         Amt = Amt.getOperand(0);
18771
18772       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18773       if (SVN && SVN->isSplat()) {
18774         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18775         SDValue InVec = Amt.getOperand(0);
18776         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18777           assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18778                  "Unexpected shuffle index found!");
18779           BaseShAmt = InVec.getOperand(SplatIdx);
18780         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18781            if (ConstantSDNode *C =
18782                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18783              if (C->getZExtValue() == SplatIdx)
18784                BaseShAmt = InVec.getOperand(1);
18785            }
18786         }
18787
18788         if (!BaseShAmt)
18789           // Avoid introducing an extract element from a shuffle.
18790           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18791                                   DAG.getIntPtrConstant(SplatIdx, dl));
18792       }
18793     }
18794
18795     if (BaseShAmt.getNode()) {
18796       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18797       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18798         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18799       else if (EltVT.bitsLT(MVT::i32))
18800         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18801
18802       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18803     }
18804   }
18805
18806   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18807   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18808       Amt.getOpcode() == ISD::BITCAST &&
18809       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18810     Amt = Amt.getOperand(0);
18811     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18812                      VT.getVectorNumElements();
18813     std::vector<SDValue> Vals(Ratio);
18814     for (unsigned i = 0; i != Ratio; ++i)
18815       Vals[i] = Amt.getOperand(i);
18816     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18817       for (unsigned j = 0; j != Ratio; ++j)
18818         if (Vals[j] != Amt.getOperand(i + j))
18819           return SDValue();
18820     }
18821
18822     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18823       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18824   }
18825   return SDValue();
18826 }
18827
18828 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18829                           SelectionDAG &DAG) {
18830   MVT VT = Op.getSimpleValueType();
18831   SDLoc dl(Op);
18832   SDValue R = Op.getOperand(0);
18833   SDValue Amt = Op.getOperand(1);
18834
18835   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18836   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18837
18838   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18839     return V;
18840
18841   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18842     return V;
18843
18844   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18845     return Op;
18846
18847   // XOP has 128-bit variable logical/arithmetic shifts.
18848   // +ve/-ve Amt = shift left/right.
18849   if (Subtarget->hasXOP() &&
18850       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18851        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18852     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18853       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18854       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18855     }
18856     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18857       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18858     if (Op.getOpcode() == ISD::SRA)
18859       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18860   }
18861
18862   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18863   // shifts per-lane and then shuffle the partial results back together.
18864   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18865     // Splat the shift amounts so the scalar shifts above will catch it.
18866     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18867     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18868     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18869     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18870     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18871   }
18872
18873   // i64 vector arithmetic shift can be emulated with the transform:
18874   // M = lshr(SIGN_BIT, Amt)
18875   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18876   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18877       Op.getOpcode() == ISD::SRA) {
18878     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18879     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18880     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18881     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18882     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18883     return R;
18884   }
18885
18886   // If possible, lower this packed shift into a vector multiply instead of
18887   // expanding it into a sequence of scalar shifts.
18888   // Do this only if the vector shift count is a constant build_vector.
18889   if (Op.getOpcode() == ISD::SHL &&
18890       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18891        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18892       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18893     SmallVector<SDValue, 8> Elts;
18894     MVT SVT = VT.getVectorElementType();
18895     unsigned SVTBits = SVT.getSizeInBits();
18896     APInt One(SVTBits, 1);
18897     unsigned NumElems = VT.getVectorNumElements();
18898
18899     for (unsigned i=0; i !=NumElems; ++i) {
18900       SDValue Op = Amt->getOperand(i);
18901       if (Op->getOpcode() == ISD::UNDEF) {
18902         Elts.push_back(Op);
18903         continue;
18904       }
18905
18906       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18907       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18908       uint64_t ShAmt = C.getZExtValue();
18909       if (ShAmt >= SVTBits) {
18910         Elts.push_back(DAG.getUNDEF(SVT));
18911         continue;
18912       }
18913       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18914     }
18915     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18916     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18917   }
18918
18919   // Lower SHL with variable shift amount.
18920   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18921     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18922
18923     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18924                      DAG.getConstant(0x3f800000U, dl, VT));
18925     Op = DAG.getBitcast(MVT::v4f32, Op);
18926     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18927     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18928   }
18929
18930   // If possible, lower this shift as a sequence of two shifts by
18931   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18932   // Example:
18933   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18934   //
18935   // Could be rewritten as:
18936   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18937   //
18938   // The advantage is that the two shifts from the example would be
18939   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18940   // the vector shift into four scalar shifts plus four pairs of vector
18941   // insert/extract.
18942   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18943       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18944     unsigned TargetOpcode = X86ISD::MOVSS;
18945     bool CanBeSimplified;
18946     // The splat value for the first packed shift (the 'X' from the example).
18947     SDValue Amt1 = Amt->getOperand(0);
18948     // The splat value for the second packed shift (the 'Y' from the example).
18949     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18950                                         Amt->getOperand(2);
18951
18952     // See if it is possible to replace this node with a sequence of
18953     // two shifts followed by a MOVSS/MOVSD
18954     if (VT == MVT::v4i32) {
18955       // Check if it is legal to use a MOVSS.
18956       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18957                         Amt2 == Amt->getOperand(3);
18958       if (!CanBeSimplified) {
18959         // Otherwise, check if we can still simplify this node using a MOVSD.
18960         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18961                           Amt->getOperand(2) == Amt->getOperand(3);
18962         TargetOpcode = X86ISD::MOVSD;
18963         Amt2 = Amt->getOperand(2);
18964       }
18965     } else {
18966       // Do similar checks for the case where the machine value type
18967       // is MVT::v8i16.
18968       CanBeSimplified = Amt1 == Amt->getOperand(1);
18969       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18970         CanBeSimplified = Amt2 == Amt->getOperand(i);
18971
18972       if (!CanBeSimplified) {
18973         TargetOpcode = X86ISD::MOVSD;
18974         CanBeSimplified = true;
18975         Amt2 = Amt->getOperand(4);
18976         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18977           CanBeSimplified = Amt1 == Amt->getOperand(i);
18978         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18979           CanBeSimplified = Amt2 == Amt->getOperand(j);
18980       }
18981     }
18982
18983     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18984         isa<ConstantSDNode>(Amt2)) {
18985       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18986       MVT CastVT = MVT::v4i32;
18987       SDValue Splat1 =
18988         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18989       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18990       SDValue Splat2 =
18991         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18992       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18993       if (TargetOpcode == X86ISD::MOVSD)
18994         CastVT = MVT::v2i64;
18995       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18996       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18997       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18998                                             BitCast1, DAG);
18999       return DAG.getBitcast(VT, Result);
19000     }
19001   }
19002
19003   // v4i32 Non Uniform Shifts.
19004   // If the shift amount is constant we can shift each lane using the SSE2
19005   // immediate shifts, else we need to zero-extend each lane to the lower i64
19006   // and shift using the SSE2 variable shifts.
19007   // The separate results can then be blended together.
19008   if (VT == MVT::v4i32) {
19009     unsigned Opc = Op.getOpcode();
19010     SDValue Amt0, Amt1, Amt2, Amt3;
19011     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
19012       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
19013       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
19014       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
19015       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
19016     } else {
19017       // ISD::SHL is handled above but we include it here for completeness.
19018       switch (Opc) {
19019       default:
19020         llvm_unreachable("Unknown target vector shift node");
19021       case ISD::SHL:
19022         Opc = X86ISD::VSHL;
19023         break;
19024       case ISD::SRL:
19025         Opc = X86ISD::VSRL;
19026         break;
19027       case ISD::SRA:
19028         Opc = X86ISD::VSRA;
19029         break;
19030       }
19031       // The SSE2 shifts use the lower i64 as the same shift amount for
19032       // all lanes and the upper i64 is ignored. These shuffle masks
19033       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
19034       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19035       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
19036       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
19037       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
19038       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
19039     }
19040
19041     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
19042     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
19043     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
19044     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
19045     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
19046     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
19047     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
19048   }
19049
19050   if (VT == MVT::v16i8 ||
19051       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
19052     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
19053     unsigned ShiftOpcode = Op->getOpcode();
19054
19055     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
19056       // On SSE41 targets we make use of the fact that VSELECT lowers
19057       // to PBLENDVB which selects bytes based just on the sign bit.
19058       if (Subtarget->hasSSE41()) {
19059         V0 = DAG.getBitcast(VT, V0);
19060         V1 = DAG.getBitcast(VT, V1);
19061         Sel = DAG.getBitcast(VT, Sel);
19062         return DAG.getBitcast(SelVT,
19063                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
19064       }
19065       // On pre-SSE41 targets we test for the sign bit by comparing to
19066       // zero - a negative value will set all bits of the lanes to true
19067       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
19068       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
19069       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
19070       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
19071     };
19072
19073     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
19074     // We can safely do this using i16 shifts as we're only interested in
19075     // the 3 lower bits of each byte.
19076     Amt = DAG.getBitcast(ExtVT, Amt);
19077     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
19078     Amt = DAG.getBitcast(VT, Amt);
19079
19080     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
19081       // r = VSELECT(r, shift(r, 4), a);
19082       SDValue M =
19083           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19084       R = SignBitSelect(VT, Amt, M, R);
19085
19086       // a += a
19087       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19088
19089       // r = VSELECT(r, shift(r, 2), a);
19090       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19091       R = SignBitSelect(VT, Amt, M, R);
19092
19093       // a += a
19094       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19095
19096       // return VSELECT(r, shift(r, 1), a);
19097       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19098       R = SignBitSelect(VT, Amt, M, R);
19099       return R;
19100     }
19101
19102     if (Op->getOpcode() == ISD::SRA) {
19103       // For SRA we need to unpack each byte to the higher byte of a i16 vector
19104       // so we can correctly sign extend. We don't care what happens to the
19105       // lower byte.
19106       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
19107       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
19108       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
19109       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
19110       ALo = DAG.getBitcast(ExtVT, ALo);
19111       AHi = DAG.getBitcast(ExtVT, AHi);
19112       RLo = DAG.getBitcast(ExtVT, RLo);
19113       RHi = DAG.getBitcast(ExtVT, RHi);
19114
19115       // r = VSELECT(r, shift(r, 4), a);
19116       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19117                                 DAG.getConstant(4, dl, ExtVT));
19118       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19119                                 DAG.getConstant(4, dl, ExtVT));
19120       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19121       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19122
19123       // a += a
19124       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19125       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19126
19127       // r = VSELECT(r, shift(r, 2), a);
19128       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19129                         DAG.getConstant(2, dl, ExtVT));
19130       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19131                         DAG.getConstant(2, dl, ExtVT));
19132       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19133       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19134
19135       // a += a
19136       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19137       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19138
19139       // r = VSELECT(r, shift(r, 1), a);
19140       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19141                         DAG.getConstant(1, dl, ExtVT));
19142       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19143                         DAG.getConstant(1, dl, ExtVT));
19144       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19145       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19146
19147       // Logical shift the result back to the lower byte, leaving a zero upper
19148       // byte
19149       // meaning that we can safely pack with PACKUSWB.
19150       RLo =
19151           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
19152       RHi =
19153           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
19154       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
19155     }
19156   }
19157
19158   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
19159   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
19160   // solution better.
19161   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
19162     MVT ExtVT = MVT::v8i32;
19163     unsigned ExtOpc =
19164         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19165     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
19166     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
19167     return DAG.getNode(ISD::TRUNCATE, dl, VT,
19168                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
19169   }
19170
19171   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
19172     MVT ExtVT = MVT::v8i32;
19173     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19174     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
19175     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
19176     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
19177     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
19178     ALo = DAG.getBitcast(ExtVT, ALo);
19179     AHi = DAG.getBitcast(ExtVT, AHi);
19180     RLo = DAG.getBitcast(ExtVT, RLo);
19181     RHi = DAG.getBitcast(ExtVT, RHi);
19182     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
19183     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
19184     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
19185     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
19186     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
19187   }
19188
19189   if (VT == MVT::v8i16) {
19190     unsigned ShiftOpcode = Op->getOpcode();
19191
19192     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
19193       // On SSE41 targets we make use of the fact that VSELECT lowers
19194       // to PBLENDVB which selects bytes based just on the sign bit.
19195       if (Subtarget->hasSSE41()) {
19196         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
19197         V0 = DAG.getBitcast(ExtVT, V0);
19198         V1 = DAG.getBitcast(ExtVT, V1);
19199         Sel = DAG.getBitcast(ExtVT, Sel);
19200         return DAG.getBitcast(
19201             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
19202       }
19203       // On pre-SSE41 targets we splat the sign bit - a negative value will
19204       // set all bits of the lanes to true and VSELECT uses that in
19205       // its OR(AND(V0,C),AND(V1,~C)) lowering.
19206       SDValue C =
19207           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
19208       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
19209     };
19210
19211     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
19212     if (Subtarget->hasSSE41()) {
19213       // On SSE41 targets we need to replicate the shift mask in both
19214       // bytes for PBLENDVB.
19215       Amt = DAG.getNode(
19216           ISD::OR, dl, VT,
19217           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
19218           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
19219     } else {
19220       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
19221     }
19222
19223     // r = VSELECT(r, shift(r, 8), a);
19224     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
19225     R = SignBitSelect(Amt, M, R);
19226
19227     // a += a
19228     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19229
19230     // r = VSELECT(r, shift(r, 4), a);
19231     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19232     R = SignBitSelect(Amt, M, R);
19233
19234     // a += a
19235     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19236
19237     // r = VSELECT(r, shift(r, 2), a);
19238     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19239     R = SignBitSelect(Amt, M, R);
19240
19241     // a += a
19242     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19243
19244     // return VSELECT(r, shift(r, 1), a);
19245     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19246     R = SignBitSelect(Amt, M, R);
19247     return R;
19248   }
19249
19250   // Decompose 256-bit shifts into smaller 128-bit shifts.
19251   if (VT.is256BitVector()) {
19252     unsigned NumElems = VT.getVectorNumElements();
19253     MVT EltVT = VT.getVectorElementType();
19254     MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19255
19256     // Extract the two vectors
19257     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
19258     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
19259
19260     // Recreate the shift amount vectors
19261     SDValue Amt1, Amt2;
19262     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
19263       // Constant shift amount
19264       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
19265       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
19266       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
19267
19268       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
19269       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
19270     } else {
19271       // Variable shift amount
19272       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19273       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19274     }
19275
19276     // Issue new vector shifts for the smaller types
19277     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19278     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19279
19280     // Concatenate the result back
19281     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19282   }
19283
19284   return SDValue();
19285 }
19286
19287 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19288                            SelectionDAG &DAG) {
19289   MVT VT = Op.getSimpleValueType();
19290   SDLoc DL(Op);
19291   SDValue R = Op.getOperand(0);
19292   SDValue Amt = Op.getOperand(1);
19293
19294   assert(VT.isVector() && "Custom lowering only for vector rotates!");
19295   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19296   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19297
19298   // XOP has 128-bit vector variable + immediate rotates.
19299   // +ve/-ve Amt = rotate left/right.
19300
19301   // Split 256-bit integers.
19302   if (VT.is256BitVector())
19303     return Lower256IntArith(Op, DAG);
19304
19305   assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19306
19307   // Attempt to rotate by immediate.
19308   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19309     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19310       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19311       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19312       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19313                          DAG.getConstant(RotateAmt, DL, MVT::i8));
19314     }
19315   }
19316
19317   // Use general rotate by variable (per-element).
19318   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19319 }
19320
19321 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19322   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19323   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19324   // looks for this combo and may remove the "setcc" instruction if the "setcc"
19325   // has only one use.
19326   SDNode *N = Op.getNode();
19327   SDValue LHS = N->getOperand(0);
19328   SDValue RHS = N->getOperand(1);
19329   unsigned BaseOp = 0;
19330   unsigned Cond = 0;
19331   SDLoc DL(Op);
19332   switch (Op.getOpcode()) {
19333   default: llvm_unreachable("Unknown ovf instruction!");
19334   case ISD::SADDO:
19335     // A subtract of one will be selected as a INC. Note that INC doesn't
19336     // set CF, so we can't do this for UADDO.
19337     if (isOneConstant(RHS)) {
19338         BaseOp = X86ISD::INC;
19339         Cond = X86::COND_O;
19340         break;
19341       }
19342     BaseOp = X86ISD::ADD;
19343     Cond = X86::COND_O;
19344     break;
19345   case ISD::UADDO:
19346     BaseOp = X86ISD::ADD;
19347     Cond = X86::COND_B;
19348     break;
19349   case ISD::SSUBO:
19350     // A subtract of one will be selected as a DEC. Note that DEC doesn't
19351     // set CF, so we can't do this for USUBO.
19352     if (isOneConstant(RHS)) {
19353         BaseOp = X86ISD::DEC;
19354         Cond = X86::COND_O;
19355         break;
19356       }
19357     BaseOp = X86ISD::SUB;
19358     Cond = X86::COND_O;
19359     break;
19360   case ISD::USUBO:
19361     BaseOp = X86ISD::SUB;
19362     Cond = X86::COND_B;
19363     break;
19364   case ISD::SMULO:
19365     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19366     Cond = X86::COND_O;
19367     break;
19368   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19369     if (N->getValueType(0) == MVT::i8) {
19370       BaseOp = X86ISD::UMUL8;
19371       Cond = X86::COND_O;
19372       break;
19373     }
19374     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19375                                  MVT::i32);
19376     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19377
19378     SDValue SetCC =
19379       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19380                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
19381                   SDValue(Sum.getNode(), 2));
19382
19383     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19384   }
19385   }
19386
19387   // Also sets EFLAGS.
19388   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19389   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19390
19391   SDValue SetCC =
19392     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19393                 DAG.getConstant(Cond, DL, MVT::i32),
19394                 SDValue(Sum.getNode(), 1));
19395
19396   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19397 }
19398
19399 /// Returns true if the operand type is exactly twice the native width, and
19400 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19401 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19402 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19403 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19404   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19405
19406   if (OpWidth == 64)
19407     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19408   else if (OpWidth == 128)
19409     return Subtarget->hasCmpxchg16b();
19410   else
19411     return false;
19412 }
19413
19414 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19415   return needsCmpXchgNb(SI->getValueOperand()->getType());
19416 }
19417
19418 // Note: this turns large loads into lock cmpxchg8b/16b.
19419 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19420 TargetLowering::AtomicExpansionKind
19421 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19422   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19423   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19424                                                : AtomicExpansionKind::None;
19425 }
19426
19427 TargetLowering::AtomicExpansionKind
19428 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19429   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19430   Type *MemType = AI->getType();
19431
19432   // If the operand is too big, we must see if cmpxchg8/16b is available
19433   // and default to library calls otherwise.
19434   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19435     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19436                                    : AtomicExpansionKind::None;
19437   }
19438
19439   AtomicRMWInst::BinOp Op = AI->getOperation();
19440   switch (Op) {
19441   default:
19442     llvm_unreachable("Unknown atomic operation");
19443   case AtomicRMWInst::Xchg:
19444   case AtomicRMWInst::Add:
19445   case AtomicRMWInst::Sub:
19446     // It's better to use xadd, xsub or xchg for these in all cases.
19447     return AtomicExpansionKind::None;
19448   case AtomicRMWInst::Or:
19449   case AtomicRMWInst::And:
19450   case AtomicRMWInst::Xor:
19451     // If the atomicrmw's result isn't actually used, we can just add a "lock"
19452     // prefix to a normal instruction for these operations.
19453     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19454                             : AtomicExpansionKind::None;
19455   case AtomicRMWInst::Nand:
19456   case AtomicRMWInst::Max:
19457   case AtomicRMWInst::Min:
19458   case AtomicRMWInst::UMax:
19459   case AtomicRMWInst::UMin:
19460     // These always require a non-trivial set of data operations on x86. We must
19461     // use a cmpxchg loop.
19462     return AtomicExpansionKind::CmpXChg;
19463   }
19464 }
19465
19466 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19467   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19468   // no-sse2). There isn't any reason to disable it if the target processor
19469   // supports it.
19470   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19471 }
19472
19473 LoadInst *
19474 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19475   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19476   Type *MemType = AI->getType();
19477   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19478   // there is no benefit in turning such RMWs into loads, and it is actually
19479   // harmful as it introduces a mfence.
19480   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19481     return nullptr;
19482
19483   auto Builder = IRBuilder<>(AI);
19484   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19485   auto SynchScope = AI->getSynchScope();
19486   // We must restrict the ordering to avoid generating loads with Release or
19487   // ReleaseAcquire orderings.
19488   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19489   auto Ptr = AI->getPointerOperand();
19490
19491   // Before the load we need a fence. Here is an example lifted from
19492   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19493   // is required:
19494   // Thread 0:
19495   //   x.store(1, relaxed);
19496   //   r1 = y.fetch_add(0, release);
19497   // Thread 1:
19498   //   y.fetch_add(42, acquire);
19499   //   r2 = x.load(relaxed);
19500   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19501   // lowered to just a load without a fence. A mfence flushes the store buffer,
19502   // making the optimization clearly correct.
19503   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19504   // otherwise, we might be able to be more aggressive on relaxed idempotent
19505   // rmw. In practice, they do not look useful, so we don't try to be
19506   // especially clever.
19507   if (SynchScope == SingleThread)
19508     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19509     // the IR level, so we must wrap it in an intrinsic.
19510     return nullptr;
19511
19512   if (!hasMFENCE(*Subtarget))
19513     // FIXME: it might make sense to use a locked operation here but on a
19514     // different cache-line to prevent cache-line bouncing. In practice it
19515     // is probably a small win, and x86 processors without mfence are rare
19516     // enough that we do not bother.
19517     return nullptr;
19518
19519   Function *MFence =
19520       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19521   Builder.CreateCall(MFence, {});
19522
19523   // Finally we can emit the atomic load.
19524   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19525           AI->getType()->getPrimitiveSizeInBits());
19526   Loaded->setAtomic(Order, SynchScope);
19527   AI->replaceAllUsesWith(Loaded);
19528   AI->eraseFromParent();
19529   return Loaded;
19530 }
19531
19532 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19533                                  SelectionDAG &DAG) {
19534   SDLoc dl(Op);
19535   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19536     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19537   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19538     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19539
19540   // The only fence that needs an instruction is a sequentially-consistent
19541   // cross-thread fence.
19542   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19543     if (hasMFENCE(*Subtarget))
19544       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19545
19546     SDValue Chain = Op.getOperand(0);
19547     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19548     SDValue Ops[] = {
19549       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19550       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19551       DAG.getRegister(0, MVT::i32),            // Index
19552       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19553       DAG.getRegister(0, MVT::i32),            // Segment.
19554       Zero,
19555       Chain
19556     };
19557     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19558     return SDValue(Res, 0);
19559   }
19560
19561   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19562   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19563 }
19564
19565 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19566                              SelectionDAG &DAG) {
19567   MVT T = Op.getSimpleValueType();
19568   SDLoc DL(Op);
19569   unsigned Reg = 0;
19570   unsigned size = 0;
19571   switch(T.SimpleTy) {
19572   default: llvm_unreachable("Invalid value type!");
19573   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19574   case MVT::i16: Reg = X86::AX;  size = 2; break;
19575   case MVT::i32: Reg = X86::EAX; size = 4; break;
19576   case MVT::i64:
19577     assert(Subtarget->is64Bit() && "Node not type legal!");
19578     Reg = X86::RAX; size = 8;
19579     break;
19580   }
19581   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19582                                   Op.getOperand(2), SDValue());
19583   SDValue Ops[] = { cpIn.getValue(0),
19584                     Op.getOperand(1),
19585                     Op.getOperand(3),
19586                     DAG.getTargetConstant(size, DL, MVT::i8),
19587                     cpIn.getValue(1) };
19588   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19589   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19590   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19591                                            Ops, T, MMO);
19592
19593   SDValue cpOut =
19594     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19595   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19596                                       MVT::i32, cpOut.getValue(2));
19597   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19598                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19599                                 EFLAGS);
19600
19601   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19602   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19603   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19604   return SDValue();
19605 }
19606
19607 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19608                             SelectionDAG &DAG) {
19609   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19610   MVT DstVT = Op.getSimpleValueType();
19611
19612   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
19613       SrcVT == MVT::i64) {
19614     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19615     if (DstVT != MVT::f64)
19616       // This conversion needs to be expanded.
19617       return SDValue();
19618
19619     SDValue Op0 = Op->getOperand(0);
19620     SmallVector<SDValue, 16> Elts;
19621     SDLoc dl(Op);
19622     unsigned NumElts;
19623     MVT SVT;
19624     if (SrcVT.isVector()) {
19625       NumElts = SrcVT.getVectorNumElements();
19626       SVT = SrcVT.getVectorElementType();
19627
19628       // Widen the vector in input in the case of MVT::v2i32.
19629       // Example: from MVT::v2i32 to MVT::v4i32.
19630       for (unsigned i = 0, e = NumElts; i != e; ++i)
19631         Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, Op0,
19632                                    DAG.getIntPtrConstant(i, dl)));
19633     } else {
19634       assert(SrcVT == MVT::i64 && !Subtarget->is64Bit() &&
19635              "Unexpected source type in LowerBITCAST");
19636       Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
19637                                  DAG.getIntPtrConstant(0, dl)));
19638       Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
19639                                  DAG.getIntPtrConstant(1, dl)));
19640       NumElts = 2;
19641       SVT = MVT::i32;
19642     }
19643     // Explicitly mark the extra elements as Undef.
19644     Elts.append(NumElts, DAG.getUNDEF(SVT));
19645
19646     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19647     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19648     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19649     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19650                        DAG.getIntPtrConstant(0, dl));
19651   }
19652
19653   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19654          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19655   assert((DstVT == MVT::i64 ||
19656           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19657          "Unexpected custom BITCAST");
19658   // i64 <=> MMX conversions are Legal.
19659   if (SrcVT==MVT::i64 && DstVT.isVector())
19660     return Op;
19661   if (DstVT==MVT::i64 && SrcVT.isVector())
19662     return Op;
19663   // MMX <=> MMX conversions are Legal.
19664   if (SrcVT.isVector() && DstVT.isVector())
19665     return Op;
19666   // All other conversions need to be expanded.
19667   return SDValue();
19668 }
19669
19670 /// Compute the horizontal sum of bytes in V for the elements of VT.
19671 ///
19672 /// Requires V to be a byte vector and VT to be an integer vector type with
19673 /// wider elements than V's type. The width of the elements of VT determines
19674 /// how many bytes of V are summed horizontally to produce each element of the
19675 /// result.
19676 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19677                                       const X86Subtarget *Subtarget,
19678                                       SelectionDAG &DAG) {
19679   SDLoc DL(V);
19680   MVT ByteVecVT = V.getSimpleValueType();
19681   MVT EltVT = VT.getVectorElementType();
19682   int NumElts = VT.getVectorNumElements();
19683   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19684          "Expected value to have byte element type.");
19685   assert(EltVT != MVT::i8 &&
19686          "Horizontal byte sum only makes sense for wider elements!");
19687   unsigned VecSize = VT.getSizeInBits();
19688   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19689
19690   // PSADBW instruction horizontally add all bytes and leave the result in i64
19691   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19692   if (EltVT == MVT::i64) {
19693     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19694     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19695     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19696     return DAG.getBitcast(VT, V);
19697   }
19698
19699   if (EltVT == MVT::i32) {
19700     // We unpack the low half and high half into i32s interleaved with zeros so
19701     // that we can use PSADBW to horizontally sum them. The most useful part of
19702     // this is that it lines up the results of two PSADBW instructions to be
19703     // two v2i64 vectors which concatenated are the 4 population counts. We can
19704     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19705     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19706     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19707     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19708
19709     // Do the horizontal sums into two v2i64s.
19710     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19711     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19712     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19713                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19714     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19715                        DAG.getBitcast(ByteVecVT, High), Zeros);
19716
19717     // Merge them together.
19718     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19719     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19720                     DAG.getBitcast(ShortVecVT, Low),
19721                     DAG.getBitcast(ShortVecVT, High));
19722
19723     return DAG.getBitcast(VT, V);
19724   }
19725
19726   // The only element type left is i16.
19727   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19728
19729   // To obtain pop count for each i16 element starting from the pop count for
19730   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19731   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19732   // directly supported.
19733   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19734   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19735   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19736   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19737                   DAG.getBitcast(ByteVecVT, V));
19738   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19739 }
19740
19741 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19742                                         const X86Subtarget *Subtarget,
19743                                         SelectionDAG &DAG) {
19744   MVT VT = Op.getSimpleValueType();
19745   MVT EltVT = VT.getVectorElementType();
19746   unsigned VecSize = VT.getSizeInBits();
19747
19748   // Implement a lookup table in register by using an algorithm based on:
19749   // http://wm.ite.pl/articles/sse-popcount.html
19750   //
19751   // The general idea is that every lower byte nibble in the input vector is an
19752   // index into a in-register pre-computed pop count table. We then split up the
19753   // input vector in two new ones: (1) a vector with only the shifted-right
19754   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19755   // masked out higher ones) for each byte. PSHUB is used separately with both
19756   // to index the in-register table. Next, both are added and the result is a
19757   // i8 vector where each element contains the pop count for input byte.
19758   //
19759   // To obtain the pop count for elements != i8, we follow up with the same
19760   // approach and use additional tricks as described below.
19761   //
19762   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19763                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19764                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19765                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19766
19767   int NumByteElts = VecSize / 8;
19768   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19769   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19770   SmallVector<SDValue, 16> LUTVec;
19771   for (int i = 0; i < NumByteElts; ++i)
19772     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19773   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19774   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19775                                   DAG.getConstant(0x0F, DL, MVT::i8));
19776   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19777
19778   // High nibbles
19779   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19780   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19781   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19782
19783   // Low nibbles
19784   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19785
19786   // The input vector is used as the shuffle mask that index elements into the
19787   // LUT. After counting low and high nibbles, add the vector to obtain the
19788   // final pop count per i8 element.
19789   SDValue HighPopCnt =
19790       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19791   SDValue LowPopCnt =
19792       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19793   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19794
19795   if (EltVT == MVT::i8)
19796     return PopCnt;
19797
19798   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19799 }
19800
19801 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19802                                        const X86Subtarget *Subtarget,
19803                                        SelectionDAG &DAG) {
19804   MVT VT = Op.getSimpleValueType();
19805   assert(VT.is128BitVector() &&
19806          "Only 128-bit vector bitmath lowering supported.");
19807
19808   int VecSize = VT.getSizeInBits();
19809   MVT EltVT = VT.getVectorElementType();
19810   int Len = EltVT.getSizeInBits();
19811
19812   // This is the vectorized version of the "best" algorithm from
19813   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19814   // with a minor tweak to use a series of adds + shifts instead of vector
19815   // multiplications. Implemented for all integer vector types. We only use
19816   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19817   // much faster, even faster than using native popcnt instructions.
19818
19819   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19820     MVT VT = V.getSimpleValueType();
19821     SmallVector<SDValue, 32> Shifters(
19822         VT.getVectorNumElements(),
19823         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19824     return DAG.getNode(OpCode, DL, VT, V,
19825                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19826   };
19827   auto GetMask = [&](SDValue V, APInt Mask) {
19828     MVT VT = V.getSimpleValueType();
19829     SmallVector<SDValue, 32> Masks(
19830         VT.getVectorNumElements(),
19831         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19832     return DAG.getNode(ISD::AND, DL, VT, V,
19833                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19834   };
19835
19836   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19837   // x86, so set the SRL type to have elements at least i16 wide. This is
19838   // correct because all of our SRLs are followed immediately by a mask anyways
19839   // that handles any bits that sneak into the high bits of the byte elements.
19840   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19841
19842   SDValue V = Op;
19843
19844   // v = v - ((v >> 1) & 0x55555555...)
19845   SDValue Srl =
19846       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19847   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19848   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19849
19850   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19851   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19852   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19853   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19854   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19855
19856   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19857   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19858   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19859   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19860
19861   // At this point, V contains the byte-wise population count, and we are
19862   // merely doing a horizontal sum if necessary to get the wider element
19863   // counts.
19864   if (EltVT == MVT::i8)
19865     return V;
19866
19867   return LowerHorizontalByteSum(
19868       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19869       DAG);
19870 }
19871
19872 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19873                                 SelectionDAG &DAG) {
19874   MVT VT = Op.getSimpleValueType();
19875   // FIXME: Need to add AVX-512 support here!
19876   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19877          "Unknown CTPOP type to handle");
19878   SDLoc DL(Op.getNode());
19879   SDValue Op0 = Op.getOperand(0);
19880
19881   if (!Subtarget->hasSSSE3()) {
19882     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19883     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19884     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19885   }
19886
19887   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19888     unsigned NumElems = VT.getVectorNumElements();
19889
19890     // Extract each 128-bit vector, compute pop count and concat the result.
19891     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19892     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19893
19894     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19895                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19896                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19897   }
19898
19899   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19900 }
19901
19902 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19903                           SelectionDAG &DAG) {
19904   assert(Op.getSimpleValueType().isVector() &&
19905          "We only do custom lowering for vector population count.");
19906   return LowerVectorCTPOP(Op, Subtarget, DAG);
19907 }
19908
19909 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19910   SDNode *Node = Op.getNode();
19911   SDLoc dl(Node);
19912   EVT T = Node->getValueType(0);
19913   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19914                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19915   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19916                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19917                        Node->getOperand(0),
19918                        Node->getOperand(1), negOp,
19919                        cast<AtomicSDNode>(Node)->getMemOperand(),
19920                        cast<AtomicSDNode>(Node)->getOrdering(),
19921                        cast<AtomicSDNode>(Node)->getSynchScope());
19922 }
19923
19924 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19925   SDNode *Node = Op.getNode();
19926   SDLoc dl(Node);
19927   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19928
19929   // Convert seq_cst store -> xchg
19930   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19931   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19932   //        (The only way to get a 16-byte store is cmpxchg16b)
19933   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19934   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19935       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19936     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19937                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19938                                  Node->getOperand(0),
19939                                  Node->getOperand(1), Node->getOperand(2),
19940                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19941                                  cast<AtomicSDNode>(Node)->getOrdering(),
19942                                  cast<AtomicSDNode>(Node)->getSynchScope());
19943     return Swap.getValue(1);
19944   }
19945   // Other atomic stores have a simple pattern.
19946   return Op;
19947 }
19948
19949 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19950   MVT VT = Op.getNode()->getSimpleValueType(0);
19951
19952   // Let legalize expand this if it isn't a legal type yet.
19953   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19954     return SDValue();
19955
19956   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19957
19958   unsigned Opc;
19959   bool ExtraOp = false;
19960   switch (Op.getOpcode()) {
19961   default: llvm_unreachable("Invalid code");
19962   case ISD::ADDC: Opc = X86ISD::ADD; break;
19963   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19964   case ISD::SUBC: Opc = X86ISD::SUB; break;
19965   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19966   }
19967
19968   if (!ExtraOp)
19969     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19970                        Op.getOperand(1));
19971   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19972                      Op.getOperand(1), Op.getOperand(2));
19973 }
19974
19975 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19976                             SelectionDAG &DAG) {
19977   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19978
19979   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19980   // which returns the values as { float, float } (in XMM0) or
19981   // { double, double } (which is returned in XMM0, XMM1).
19982   SDLoc dl(Op);
19983   SDValue Arg = Op.getOperand(0);
19984   EVT ArgVT = Arg.getValueType();
19985   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19986
19987   TargetLowering::ArgListTy Args;
19988   TargetLowering::ArgListEntry Entry;
19989
19990   Entry.Node = Arg;
19991   Entry.Ty = ArgTy;
19992   Entry.isSExt = false;
19993   Entry.isZExt = false;
19994   Args.push_back(Entry);
19995
19996   bool isF64 = ArgVT == MVT::f64;
19997   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19998   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19999   // the results are returned via SRet in memory.
20000   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
20001   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20002   SDValue Callee =
20003       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
20004
20005   Type *RetTy = isF64
20006     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
20007     : (Type*)VectorType::get(ArgTy, 4);
20008
20009   TargetLowering::CallLoweringInfo CLI(DAG);
20010   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
20011     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
20012
20013   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
20014
20015   if (isF64)
20016     // Returned in xmm0 and xmm1.
20017     return CallResult.first;
20018
20019   // Returned in bits 0:31 and 32:64 xmm0.
20020   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
20021                                CallResult.first, DAG.getIntPtrConstant(0, dl));
20022   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
20023                                CallResult.first, DAG.getIntPtrConstant(1, dl));
20024   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
20025   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
20026 }
20027
20028 /// Widen a vector input to a vector of NVT.  The
20029 /// input vector must have the same element type as NVT.
20030 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
20031                             bool FillWithZeroes = false) {
20032   // Check if InOp already has the right width.
20033   MVT InVT = InOp.getSimpleValueType();
20034   if (InVT == NVT)
20035     return InOp;
20036
20037   if (InOp.isUndef())
20038     return DAG.getUNDEF(NVT);
20039
20040   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
20041          "input and widen element type must match");
20042
20043   unsigned InNumElts = InVT.getVectorNumElements();
20044   unsigned WidenNumElts = NVT.getVectorNumElements();
20045   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
20046          "Unexpected request for vector widening");
20047
20048   EVT EltVT = NVT.getVectorElementType();
20049
20050   SDLoc dl(InOp);
20051   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
20052       InOp.getNumOperands() == 2) {
20053     SDValue N1 = InOp.getOperand(1);
20054     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
20055         N1.isUndef()) {
20056       InOp = InOp.getOperand(0);
20057       InVT = InOp.getSimpleValueType();
20058       InNumElts = InVT.getVectorNumElements();
20059     }
20060   }
20061   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
20062       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
20063     SmallVector<SDValue, 16> Ops;
20064     for (unsigned i = 0; i < InNumElts; ++i)
20065       Ops.push_back(InOp.getOperand(i));
20066
20067     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
20068       DAG.getUNDEF(EltVT);
20069     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
20070       Ops.push_back(FillVal);
20071     return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
20072   }
20073   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
20074     DAG.getUNDEF(NVT);
20075   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
20076                      InOp, DAG.getIntPtrConstant(0, dl));
20077 }
20078
20079 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
20080                              SelectionDAG &DAG) {
20081   assert(Subtarget->hasAVX512() &&
20082          "MGATHER/MSCATTER are supported on AVX-512 arch only");
20083
20084   // X86 scatter kills mask register, so its type should be added to
20085   // the list of return values.
20086   // If the "scatter" has 2 return values, it is already handled.
20087   if (Op.getNode()->getNumValues() == 2)
20088     return Op;
20089
20090   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
20091   SDValue Src = N->getValue();
20092   MVT VT = Src.getSimpleValueType();
20093   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
20094   SDLoc dl(Op);
20095
20096   SDValue NewScatter;
20097   SDValue Index = N->getIndex();
20098   SDValue Mask = N->getMask();
20099   SDValue Chain = N->getChain();
20100   SDValue BasePtr = N->getBasePtr();
20101   MVT MemVT = N->getMemoryVT().getSimpleVT();
20102   MVT IndexVT = Index.getSimpleValueType();
20103   MVT MaskVT = Mask.getSimpleValueType();
20104
20105   if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
20106     // The v2i32 value was promoted to v2i64.
20107     // Now we "redo" the type legalizer's work and widen the original
20108     // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
20109     // with a shuffle.
20110     assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
20111            "Unexpected memory type");
20112     int ShuffleMask[] = {0, 2, -1, -1};
20113     Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
20114                                DAG.getUNDEF(MVT::v4i32), ShuffleMask);
20115     // Now we have 4 elements instead of 2.
20116     // Expand the index.
20117     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
20118     Index = ExtendToType(Index, NewIndexVT, DAG);
20119
20120     // Expand the mask with zeroes
20121     // Mask may be <2 x i64> or <2 x i1> at this moment
20122     assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
20123            "Unexpected mask type");
20124     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
20125     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20126     VT = MVT::v4i32;
20127   }
20128
20129   unsigned NumElts = VT.getVectorNumElements();
20130   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20131       !Index.getSimpleValueType().is512BitVector()) {
20132     // AVX512F supports only 512-bit vectors. Or data or index should
20133     // be 512 bit wide. If now the both index and data are 256-bit, but
20134     // the vector contains 8 elements, we just sign-extend the index
20135     if (IndexVT == MVT::v8i32)
20136       // Just extend index
20137       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20138     else {
20139       // The minimal number of elts in scatter is 8
20140       NumElts = 8;
20141       // Index
20142       MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20143       // Use original index here, do not modify the index twice
20144       Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
20145       if (IndexVT.getScalarType() == MVT::i32)
20146         Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20147
20148       // Mask
20149       // At this point we have promoted mask operand
20150       assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20151       MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20152       // Use the original mask here, do not modify the mask twice
20153       Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true);
20154
20155       // The value that should be stored
20156       MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20157       Src = ExtendToType(Src, NewVT, DAG);
20158     }
20159   }
20160   // If the mask is "wide" at this point - truncate it to i1 vector
20161   MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
20162   Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
20163
20164   // The mask is killed by scatter, add it to the values
20165   SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
20166   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
20167   NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
20168                                     N->getMemOperand());
20169   DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
20170   return SDValue(NewScatter.getNode(), 0);
20171 }
20172
20173 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
20174                           SelectionDAG &DAG) {
20175
20176   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
20177   MVT VT = Op.getSimpleValueType();
20178   SDValue Mask = N->getMask();
20179   SDLoc dl(Op);
20180
20181   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20182       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20183     // This operation is legal for targets with VLX, but without
20184     // VLX the vector should be widened to 512 bit
20185     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20186     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20187     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20188     SDValue Src0 = N->getSrc0();
20189     Src0 = ExtendToType(Src0, WideDataVT, DAG);
20190     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20191     SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
20192                                         N->getBasePtr(), Mask, Src0,
20193                                         N->getMemoryVT(), N->getMemOperand(),
20194                                         N->getExtensionType());
20195
20196     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20197                                  NewLoad.getValue(0),
20198                                  DAG.getIntPtrConstant(0, dl));
20199     SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
20200     return DAG.getMergeValues(RetOps, dl);
20201   }
20202   return Op;
20203 }
20204
20205 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
20206                            SelectionDAG &DAG) {
20207   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
20208   SDValue DataToStore = N->getValue();
20209   MVT VT = DataToStore.getSimpleValueType();
20210   SDValue Mask = N->getMask();
20211   SDLoc dl(Op);
20212
20213   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20214       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20215     // This operation is legal for targets with VLX, but without
20216     // VLX the vector should be widened to 512 bit
20217     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20218     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20219     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20220     DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
20221     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20222     return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
20223                               Mask, N->getMemoryVT(), N->getMemOperand(),
20224                               N->isTruncatingStore());
20225   }
20226   return Op;
20227 }
20228
20229 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
20230                             SelectionDAG &DAG) {
20231   assert(Subtarget->hasAVX512() &&
20232          "MGATHER/MSCATTER are supported on AVX-512 arch only");
20233
20234   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
20235   SDLoc dl(Op);
20236   MVT VT = Op.getSimpleValueType();
20237   SDValue Index = N->getIndex();
20238   SDValue Mask = N->getMask();
20239   SDValue Src0 = N->getValue();
20240   MVT IndexVT = Index.getSimpleValueType();
20241   MVT MaskVT = Mask.getSimpleValueType();
20242
20243   unsigned NumElts = VT.getVectorNumElements();
20244   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
20245
20246   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20247       !Index.getSimpleValueType().is512BitVector()) {
20248     // AVX512F supports only 512-bit vectors. Or data or index should
20249     // be 512 bit wide. If now the both index and data are 256-bit, but
20250     // the vector contains 8 elements, we just sign-extend the index
20251     if (NumElts == 8) {
20252       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20253       SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
20254                         N->getOperand(3), Index };
20255       DAG.UpdateNodeOperands(N, Ops);
20256       return Op;
20257     }
20258
20259     // Minimal number of elements in Gather
20260     NumElts = 8;
20261     // Index
20262     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20263     Index = ExtendToType(Index, NewIndexVT, DAG);
20264     if (IndexVT.getScalarType() == MVT::i32)
20265       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20266
20267     // Mask
20268     MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
20269     // At this point we have promoted mask operand
20270     assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20271     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20272     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20273     Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
20274
20275     // The pass-thru value
20276     MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20277     Src0 = ExtendToType(Src0, NewVT, DAG);
20278
20279     SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
20280     SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
20281                                             N->getMemoryVT(), dl, Ops,
20282                                             N->getMemOperand());
20283     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20284                                  NewGather.getValue(0),
20285                                  DAG.getIntPtrConstant(0, dl));
20286     SDValue RetOps[] = {Exract, NewGather.getValue(1)};
20287     return DAG.getMergeValues(RetOps, dl);
20288   }
20289   return Op;
20290 }
20291
20292 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
20293                                                     SelectionDAG &DAG) const {
20294   // TODO: Eventually, the lowering of these nodes should be informed by or
20295   // deferred to the GC strategy for the function in which they appear. For
20296   // now, however, they must be lowered to something. Since they are logically
20297   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20298   // require special handling for these nodes), lower them as literal NOOPs for
20299   // the time being.
20300   SmallVector<SDValue, 2> Ops;
20301
20302   Ops.push_back(Op.getOperand(0));
20303   if (Op->getGluedNode())
20304     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20305
20306   SDLoc OpDL(Op);
20307   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20308   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20309
20310   return NOOP;
20311 }
20312
20313 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
20314                                                   SelectionDAG &DAG) const {
20315   // TODO: Eventually, the lowering of these nodes should be informed by or
20316   // deferred to the GC strategy for the function in which they appear. For
20317   // now, however, they must be lowered to something. Since they are logically
20318   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20319   // require special handling for these nodes), lower them as literal NOOPs for
20320   // the time being.
20321   SmallVector<SDValue, 2> Ops;
20322
20323   Ops.push_back(Op.getOperand(0));
20324   if (Op->getGluedNode())
20325     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20326
20327   SDLoc OpDL(Op);
20328   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20329   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20330
20331   return NOOP;
20332 }
20333
20334 /// LowerOperation - Provide custom lowering hooks for some operations.
20335 ///
20336 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
20337   switch (Op.getOpcode()) {
20338   default: llvm_unreachable("Should not custom lower this!");
20339   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
20340   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
20341     return LowerCMP_SWAP(Op, Subtarget, DAG);
20342   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
20343   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
20344   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
20345   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
20346   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
20347   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
20348   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
20349   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
20350   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
20351   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
20352   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
20353   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
20354   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
20355   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
20356   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
20357   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
20358   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
20359   case ISD::SHL_PARTS:
20360   case ISD::SRA_PARTS:
20361   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
20362   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
20363   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
20364   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
20365   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
20366   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
20367   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
20368   case ISD::SIGN_EXTEND_VECTOR_INREG:
20369     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
20370   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
20371   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
20372   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
20373   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
20374   case ISD::FABS:
20375   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
20376   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
20377   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
20378   case ISD::SETCC:              return LowerSETCC(Op, DAG);
20379   case ISD::SETCCE:             return LowerSETCCE(Op, DAG);
20380   case ISD::SELECT:             return LowerSELECT(Op, DAG);
20381   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
20382   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
20383   case ISD::VASTART:            return LowerVASTART(Op, DAG);
20384   case ISD::VAARG:              return LowerVAARG(Op, DAG);
20385   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
20386   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
20387   case ISD::INTRINSIC_VOID:
20388   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
20389   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
20390   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
20391   case ISD::FRAME_TO_ARGS_OFFSET:
20392                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
20393   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
20394   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
20395   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
20396   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
20397   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
20398   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
20399   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
20400   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
20401   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
20402   case ISD::CTTZ:
20403   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
20404   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
20405   case ISD::UMUL_LOHI:
20406   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
20407   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
20408   case ISD::SRA:
20409   case ISD::SRL:
20410   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
20411   case ISD::SADDO:
20412   case ISD::UADDO:
20413   case ISD::SSUBO:
20414   case ISD::USUBO:
20415   case ISD::SMULO:
20416   case ISD::UMULO:              return LowerXALUO(Op, DAG);
20417   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20418   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
20419   case ISD::ADDC:
20420   case ISD::ADDE:
20421   case ISD::SUBC:
20422   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20423   case ISD::ADD:                return LowerADD(Op, DAG);
20424   case ISD::SUB:                return LowerSUB(Op, DAG);
20425   case ISD::SMAX:
20426   case ISD::SMIN:
20427   case ISD::UMAX:
20428   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
20429   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
20430   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
20431   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
20432   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
20433   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
20434   case ISD::GC_TRANSITION_START:
20435                                 return LowerGC_TRANSITION_START(Op, DAG);
20436   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
20437   }
20438 }
20439
20440 /// ReplaceNodeResults - Replace a node with an illegal result type
20441 /// with a new node built out of custom code.
20442 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20443                                            SmallVectorImpl<SDValue>&Results,
20444                                            SelectionDAG &DAG) const {
20445   SDLoc dl(N);
20446   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20447   switch (N->getOpcode()) {
20448   default:
20449     llvm_unreachable("Do not know how to custom type legalize this operation!");
20450   case X86ISD::AVG: {
20451     // Legalize types for X86ISD::AVG by expanding vectors.
20452     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20453
20454     auto InVT = N->getValueType(0);
20455     auto InVTSize = InVT.getSizeInBits();
20456     const unsigned RegSize =
20457         (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20458     assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20459            "512-bit vector requires AVX512");
20460     assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20461            "256-bit vector requires AVX2");
20462
20463     auto ElemVT = InVT.getVectorElementType();
20464     auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20465                                   RegSize / ElemVT.getSizeInBits());
20466     assert(RegSize % InVT.getSizeInBits() == 0);
20467     unsigned NumConcat = RegSize / InVT.getSizeInBits();
20468
20469     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20470     Ops[0] = N->getOperand(0);
20471     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20472     Ops[0] = N->getOperand(1);
20473     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20474
20475     SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20476     Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20477                                   DAG.getIntPtrConstant(0, dl)));
20478     return;
20479   }
20480   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20481   case X86ISD::FMINC:
20482   case X86ISD::FMIN:
20483   case X86ISD::FMAXC:
20484   case X86ISD::FMAX: {
20485     EVT VT = N->getValueType(0);
20486     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20487     SDValue UNDEF = DAG.getUNDEF(VT);
20488     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20489                               N->getOperand(0), UNDEF);
20490     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20491                               N->getOperand(1), UNDEF);
20492     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20493     return;
20494   }
20495   case ISD::SIGN_EXTEND_INREG:
20496   case ISD::ADDC:
20497   case ISD::ADDE:
20498   case ISD::SUBC:
20499   case ISD::SUBE:
20500     // We don't want to expand or promote these.
20501     return;
20502   case ISD::SDIV:
20503   case ISD::UDIV:
20504   case ISD::SREM:
20505   case ISD::UREM:
20506   case ISD::SDIVREM:
20507   case ISD::UDIVREM: {
20508     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20509     Results.push_back(V);
20510     return;
20511   }
20512   case ISD::FP_TO_SINT:
20513   case ISD::FP_TO_UINT: {
20514     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20515
20516     std::pair<SDValue,SDValue> Vals =
20517         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20518     SDValue FIST = Vals.first, StackSlot = Vals.second;
20519     if (FIST.getNode()) {
20520       EVT VT = N->getValueType(0);
20521       // Return a load from the stack slot.
20522       if (StackSlot.getNode())
20523         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20524                                       MachinePointerInfo(),
20525                                       false, false, false, 0));
20526       else
20527         Results.push_back(FIST);
20528     }
20529     return;
20530   }
20531   case ISD::UINT_TO_FP: {
20532     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20533     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20534         N->getValueType(0) != MVT::v2f32)
20535       return;
20536     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20537                                  N->getOperand(0));
20538     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20539                                      MVT::f64);
20540     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20541     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20542                              DAG.getBitcast(MVT::v2i64, VBias));
20543     Or = DAG.getBitcast(MVT::v2f64, Or);
20544     // TODO: Are there any fast-math-flags to propagate here?
20545     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20546     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20547     return;
20548   }
20549   case ISD::FP_ROUND: {
20550     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20551         return;
20552     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20553     Results.push_back(V);
20554     return;
20555   }
20556   case ISD::FP_EXTEND: {
20557     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20558     // No other ValueType for FP_EXTEND should reach this point.
20559     assert(N->getValueType(0) == MVT::v2f32 &&
20560            "Do not know how to legalize this Node");
20561     return;
20562   }
20563   case ISD::INTRINSIC_W_CHAIN: {
20564     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20565     switch (IntNo) {
20566     default : llvm_unreachable("Do not know how to custom type "
20567                                "legalize this intrinsic operation!");
20568     case Intrinsic::x86_rdtsc:
20569       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20570                                      Results);
20571     case Intrinsic::x86_rdtscp:
20572       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20573                                      Results);
20574     case Intrinsic::x86_rdpmc:
20575       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20576     }
20577   }
20578   case ISD::INTRINSIC_WO_CHAIN: {
20579     if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20580       Results.push_back(V);
20581     return;
20582   }
20583   case ISD::READCYCLECOUNTER: {
20584     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20585                                    Results);
20586   }
20587   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20588     EVT T = N->getValueType(0);
20589     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20590     bool Regs64bit = T == MVT::i128;
20591     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20592     SDValue cpInL, cpInH;
20593     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20594                         DAG.getConstant(0, dl, HalfT));
20595     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20596                         DAG.getConstant(1, dl, HalfT));
20597     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20598                              Regs64bit ? X86::RAX : X86::EAX,
20599                              cpInL, SDValue());
20600     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20601                              Regs64bit ? X86::RDX : X86::EDX,
20602                              cpInH, cpInL.getValue(1));
20603     SDValue swapInL, swapInH;
20604     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20605                           DAG.getConstant(0, dl, HalfT));
20606     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20607                           DAG.getConstant(1, dl, HalfT));
20608     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20609                                Regs64bit ? X86::RBX : X86::EBX,
20610                                swapInL, cpInH.getValue(1));
20611     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20612                                Regs64bit ? X86::RCX : X86::ECX,
20613                                swapInH, swapInL.getValue(1));
20614     SDValue Ops[] = { swapInH.getValue(0),
20615                       N->getOperand(1),
20616                       swapInH.getValue(1) };
20617     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20618     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20619     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20620                                   X86ISD::LCMPXCHG8_DAG;
20621     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20622     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20623                                         Regs64bit ? X86::RAX : X86::EAX,
20624                                         HalfT, Result.getValue(1));
20625     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20626                                         Regs64bit ? X86::RDX : X86::EDX,
20627                                         HalfT, cpOutL.getValue(2));
20628     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20629
20630     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20631                                         MVT::i32, cpOutH.getValue(2));
20632     SDValue Success =
20633         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20634                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20635     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20636
20637     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20638     Results.push_back(Success);
20639     Results.push_back(EFLAGS.getValue(1));
20640     return;
20641   }
20642   case ISD::ATOMIC_SWAP:
20643   case ISD::ATOMIC_LOAD_ADD:
20644   case ISD::ATOMIC_LOAD_SUB:
20645   case ISD::ATOMIC_LOAD_AND:
20646   case ISD::ATOMIC_LOAD_OR:
20647   case ISD::ATOMIC_LOAD_XOR:
20648   case ISD::ATOMIC_LOAD_NAND:
20649   case ISD::ATOMIC_LOAD_MIN:
20650   case ISD::ATOMIC_LOAD_MAX:
20651   case ISD::ATOMIC_LOAD_UMIN:
20652   case ISD::ATOMIC_LOAD_UMAX:
20653   case ISD::ATOMIC_LOAD: {
20654     // Delegate to generic TypeLegalization. Situations we can really handle
20655     // should have already been dealt with by AtomicExpandPass.cpp.
20656     break;
20657   }
20658   case ISD::BITCAST: {
20659     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20660     EVT DstVT = N->getValueType(0);
20661     EVT SrcVT = N->getOperand(0)->getValueType(0);
20662
20663     if (SrcVT != MVT::f64 ||
20664         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20665       return;
20666
20667     unsigned NumElts = DstVT.getVectorNumElements();
20668     EVT SVT = DstVT.getVectorElementType();
20669     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20670     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20671                                    MVT::v2f64, N->getOperand(0));
20672     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20673
20674     if (ExperimentalVectorWideningLegalization) {
20675       // If we are legalizing vectors by widening, we already have the desired
20676       // legal vector type, just return it.
20677       Results.push_back(ToVecInt);
20678       return;
20679     }
20680
20681     SmallVector<SDValue, 8> Elts;
20682     for (unsigned i = 0, e = NumElts; i != e; ++i)
20683       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20684                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
20685
20686     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20687   }
20688   }
20689 }
20690
20691 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20692   switch ((X86ISD::NodeType)Opcode) {
20693   case X86ISD::FIRST_NUMBER:       break;
20694   case X86ISD::BSF:                return "X86ISD::BSF";
20695   case X86ISD::BSR:                return "X86ISD::BSR";
20696   case X86ISD::SHLD:               return "X86ISD::SHLD";
20697   case X86ISD::SHRD:               return "X86ISD::SHRD";
20698   case X86ISD::FAND:               return "X86ISD::FAND";
20699   case X86ISD::FANDN:              return "X86ISD::FANDN";
20700   case X86ISD::FOR:                return "X86ISD::FOR";
20701   case X86ISD::FXOR:               return "X86ISD::FXOR";
20702   case X86ISD::FILD:               return "X86ISD::FILD";
20703   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
20704   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20705   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20706   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20707   case X86ISD::FLD:                return "X86ISD::FLD";
20708   case X86ISD::FST:                return "X86ISD::FST";
20709   case X86ISD::CALL:               return "X86ISD::CALL";
20710   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
20711   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
20712   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
20713   case X86ISD::BT:                 return "X86ISD::BT";
20714   case X86ISD::CMP:                return "X86ISD::CMP";
20715   case X86ISD::COMI:               return "X86ISD::COMI";
20716   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
20717   case X86ISD::CMPM:               return "X86ISD::CMPM";
20718   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
20719   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
20720   case X86ISD::SETCC:              return "X86ISD::SETCC";
20721   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
20722   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
20723   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
20724   case X86ISD::CMOV:               return "X86ISD::CMOV";
20725   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
20726   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
20727   case X86ISD::IRET:               return "X86ISD::IRET";
20728   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
20729   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
20730   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
20731   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
20732   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
20733   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
20734   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
20735   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
20736   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
20737   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
20738   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
20739   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
20740   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
20741   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
20742   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
20743   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
20744   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
20745   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
20746   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
20747   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
20748   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
20749   case X86ISD::HADD:               return "X86ISD::HADD";
20750   case X86ISD::HSUB:               return "X86ISD::HSUB";
20751   case X86ISD::FHADD:              return "X86ISD::FHADD";
20752   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
20753   case X86ISD::ABS:                return "X86ISD::ABS";
20754   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
20755   case X86ISD::FMAX:               return "X86ISD::FMAX";
20756   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
20757   case X86ISD::FMIN:               return "X86ISD::FMIN";
20758   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
20759   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20760   case X86ISD::FMINC:              return "X86ISD::FMINC";
20761   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20762   case X86ISD::FRCP:               return "X86ISD::FRCP";
20763   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
20764   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
20765   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20766   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20767   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20768   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20769   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20770   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20771   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20772   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20773   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20774   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20775   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20776   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20777   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20778   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20779   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20780   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20781   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20782   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20783   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20784   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20785   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20786   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20787   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20788   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20789   case X86ISD::CVT2MASK:           return "X86ISD::CVT2MASK";
20790   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20791   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20792   case X86ISD::VSHL:               return "X86ISD::VSHL";
20793   case X86ISD::VSRL:               return "X86ISD::VSRL";
20794   case X86ISD::VSRA:               return "X86ISD::VSRA";
20795   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20796   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20797   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20798   case X86ISD::VROTLI:             return "X86ISD::VROTLI";
20799   case X86ISD::VROTRI:             return "X86ISD::VROTRI";
20800   case X86ISD::CMPP:               return "X86ISD::CMPP";
20801   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20802   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20803   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20804   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20805   case X86ISD::ADD:                return "X86ISD::ADD";
20806   case X86ISD::SUB:                return "X86ISD::SUB";
20807   case X86ISD::ADC:                return "X86ISD::ADC";
20808   case X86ISD::SBB:                return "X86ISD::SBB";
20809   case X86ISD::SMUL:               return "X86ISD::SMUL";
20810   case X86ISD::UMUL:               return "X86ISD::UMUL";
20811   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20812   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20813   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20814   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20815   case X86ISD::INC:                return "X86ISD::INC";
20816   case X86ISD::DEC:                return "X86ISD::DEC";
20817   case X86ISD::OR:                 return "X86ISD::OR";
20818   case X86ISD::XOR:                return "X86ISD::XOR";
20819   case X86ISD::AND:                return "X86ISD::AND";
20820   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20821   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20822   case X86ISD::PTEST:              return "X86ISD::PTEST";
20823   case X86ISD::TESTP:              return "X86ISD::TESTP";
20824   case X86ISD::TESTM:              return "X86ISD::TESTM";
20825   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20826   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20827   case X86ISD::KTEST:              return "X86ISD::KTEST";
20828   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20829   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20830   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20831   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20832   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20833   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20834   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20835   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20836   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20837   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20838   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20839   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20840   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20841   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20842   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20843   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20844   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20845   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20846   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20847   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20848   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20849   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20850   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
20851   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20852   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20853   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20854   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20855   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20856   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20857   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20858   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20859   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20860   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20861   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20862   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20863   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20864   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20865   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20866   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20867   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20868   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20869   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20870   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20871   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20872   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20873   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20874   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20875   case X86ISD::SAHF:               return "X86ISD::SAHF";
20876   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20877   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20878   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20879   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20880   case X86ISD::VPROT:              return "X86ISD::VPROT";
20881   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20882   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20883   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20884   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20885   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20886   case X86ISD::FMADD:              return "X86ISD::FMADD";
20887   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20888   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20889   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20890   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20891   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20892   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20893   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20894   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20895   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20896   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20897   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20898   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20899   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20900   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20901   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20902   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20903   case X86ISD::XTEST:              return "X86ISD::XTEST";
20904   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20905   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20906   case X86ISD::SELECT:             return "X86ISD::SELECT";
20907   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20908   case X86ISD::RCP28:              return "X86ISD::RCP28";
20909   case X86ISD::EXP2:               return "X86ISD::EXP2";
20910   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20911   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20912   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20913   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20914   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20915   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20916   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20917   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20918   case X86ISD::ADDS:               return "X86ISD::ADDS";
20919   case X86ISD::SUBS:               return "X86ISD::SUBS";
20920   case X86ISD::AVG:                return "X86ISD::AVG";
20921   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20922   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20923   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20924   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20925   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20926   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20927   case X86ISD::VFPCLASSS:          return "X86ISD::VFPCLASSS";
20928   }
20929   return nullptr;
20930 }
20931
20932 // isLegalAddressingMode - Return true if the addressing mode represented
20933 // by AM is legal for this target, for a load/store of the specified type.
20934 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20935                                               const AddrMode &AM, Type *Ty,
20936                                               unsigned AS) const {
20937   // X86 supports extremely general addressing modes.
20938   CodeModel::Model M = getTargetMachine().getCodeModel();
20939   Reloc::Model R = getTargetMachine().getRelocationModel();
20940
20941   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20942   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20943     return false;
20944
20945   if (AM.BaseGV) {
20946     unsigned GVFlags =
20947       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20948
20949     // If a reference to this global requires an extra load, we can't fold it.
20950     if (isGlobalStubReference(GVFlags))
20951       return false;
20952
20953     // If BaseGV requires a register for the PIC base, we cannot also have a
20954     // BaseReg specified.
20955     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20956       return false;
20957
20958     // If lower 4G is not available, then we must use rip-relative addressing.
20959     if ((M != CodeModel::Small || R != Reloc::Static) &&
20960         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20961       return false;
20962   }
20963
20964   switch (AM.Scale) {
20965   case 0:
20966   case 1:
20967   case 2:
20968   case 4:
20969   case 8:
20970     // These scales always work.
20971     break;
20972   case 3:
20973   case 5:
20974   case 9:
20975     // These scales are formed with basereg+scalereg.  Only accept if there is
20976     // no basereg yet.
20977     if (AM.HasBaseReg)
20978       return false;
20979     break;
20980   default:  // Other stuff never works.
20981     return false;
20982   }
20983
20984   return true;
20985 }
20986
20987 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20988   unsigned Bits = Ty->getScalarSizeInBits();
20989
20990   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20991   // particularly cheaper than those without.
20992   if (Bits == 8)
20993     return false;
20994
20995   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20996   // variable shifts just as cheap as scalar ones.
20997   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20998     return false;
20999
21000   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
21001   // fully general vector.
21002   return true;
21003 }
21004
21005 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
21006   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
21007     return false;
21008   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
21009   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
21010   return NumBits1 > NumBits2;
21011 }
21012
21013 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
21014   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
21015     return false;
21016
21017   if (!isTypeLegal(EVT::getEVT(Ty1)))
21018     return false;
21019
21020   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
21021
21022   // Assuming the caller doesn't have a zeroext or signext return parameter,
21023   // truncation all the way down to i1 is valid.
21024   return true;
21025 }
21026
21027 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
21028   return isInt<32>(Imm);
21029 }
21030
21031 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
21032   // Can also use sub to handle negated immediates.
21033   return isInt<32>(Imm);
21034 }
21035
21036 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
21037   if (!VT1.isInteger() || !VT2.isInteger())
21038     return false;
21039   unsigned NumBits1 = VT1.getSizeInBits();
21040   unsigned NumBits2 = VT2.getSizeInBits();
21041   return NumBits1 > NumBits2;
21042 }
21043
21044 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
21045   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
21046   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
21047 }
21048
21049 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
21050   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
21051   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
21052 }
21053
21054 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
21055   EVT VT1 = Val.getValueType();
21056   if (isZExtFree(VT1, VT2))
21057     return true;
21058
21059   if (Val.getOpcode() != ISD::LOAD)
21060     return false;
21061
21062   if (!VT1.isSimple() || !VT1.isInteger() ||
21063       !VT2.isSimple() || !VT2.isInteger())
21064     return false;
21065
21066   switch (VT1.getSimpleVT().SimpleTy) {
21067   default: break;
21068   case MVT::i8:
21069   case MVT::i16:
21070   case MVT::i32:
21071     // X86 has 8, 16, and 32-bit zero-extending loads.
21072     return true;
21073   }
21074
21075   return false;
21076 }
21077
21078 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
21079
21080 bool
21081 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
21082   if (!Subtarget->hasAnyFMA())
21083     return false;
21084
21085   VT = VT.getScalarType();
21086
21087   if (!VT.isSimple())
21088     return false;
21089
21090   switch (VT.getSimpleVT().SimpleTy) {
21091   case MVT::f32:
21092   case MVT::f64:
21093     return true;
21094   default:
21095     break;
21096   }
21097
21098   return false;
21099 }
21100
21101 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
21102   // i16 instructions are longer (0x66 prefix) and potentially slower.
21103   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
21104 }
21105
21106 /// isShuffleMaskLegal - Targets can use this to indicate that they only
21107 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
21108 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
21109 /// are assumed to be legal.
21110 bool
21111 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
21112                                       EVT VT) const {
21113   if (!VT.isSimple())
21114     return false;
21115
21116   // Not for i1 vectors
21117   if (VT.getSimpleVT().getScalarType() == MVT::i1)
21118     return false;
21119
21120   // Very little shuffling can be done for 64-bit vectors right now.
21121   if (VT.getSimpleVT().getSizeInBits() == 64)
21122     return false;
21123
21124   // We only care that the types being shuffled are legal. The lowering can
21125   // handle any possible shuffle mask that results.
21126   return isTypeLegal(VT.getSimpleVT());
21127 }
21128
21129 bool
21130 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
21131                                           EVT VT) const {
21132   // Just delegate to the generic legality, clear masks aren't special.
21133   return isShuffleMaskLegal(Mask, VT);
21134 }
21135
21136 //===----------------------------------------------------------------------===//
21137 //                           X86 Scheduler Hooks
21138 //===----------------------------------------------------------------------===//
21139
21140 /// Utility function to emit xbegin specifying the start of an RTM region.
21141 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
21142                                      const TargetInstrInfo *TII) {
21143   DebugLoc DL = MI->getDebugLoc();
21144
21145   const BasicBlock *BB = MBB->getBasicBlock();
21146   MachineFunction::iterator I = ++MBB->getIterator();
21147
21148   // For the v = xbegin(), we generate
21149   //
21150   // thisMBB:
21151   //  xbegin sinkMBB
21152   //
21153   // mainMBB:
21154   //  eax = -1
21155   //
21156   // sinkMBB:
21157   //  v = eax
21158
21159   MachineBasicBlock *thisMBB = MBB;
21160   MachineFunction *MF = MBB->getParent();
21161   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21162   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21163   MF->insert(I, mainMBB);
21164   MF->insert(I, sinkMBB);
21165
21166   // Transfer the remainder of BB and its successor edges to sinkMBB.
21167   sinkMBB->splice(sinkMBB->begin(), MBB,
21168                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21169   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21170
21171   // thisMBB:
21172   //  xbegin sinkMBB
21173   //  # fallthrough to mainMBB
21174   //  # abortion to sinkMBB
21175   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
21176   thisMBB->addSuccessor(mainMBB);
21177   thisMBB->addSuccessor(sinkMBB);
21178
21179   // mainMBB:
21180   //  EAX = -1
21181   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
21182   mainMBB->addSuccessor(sinkMBB);
21183
21184   // sinkMBB:
21185   // EAX is live into the sinkMBB
21186   sinkMBB->addLiveIn(X86::EAX);
21187   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21188           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21189     .addReg(X86::EAX);
21190
21191   MI->eraseFromParent();
21192   return sinkMBB;
21193 }
21194
21195 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
21196 // or XMM0_V32I8 in AVX all of this code can be replaced with that
21197 // in the .td file.
21198 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
21199                                        const TargetInstrInfo *TII) {
21200   unsigned Opc;
21201   switch (MI->getOpcode()) {
21202   default: llvm_unreachable("illegal opcode!");
21203   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
21204   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
21205   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
21206   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
21207   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
21208   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
21209   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
21210   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
21211   }
21212
21213   DebugLoc dl = MI->getDebugLoc();
21214   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21215
21216   unsigned NumArgs = MI->getNumOperands();
21217   for (unsigned i = 1; i < NumArgs; ++i) {
21218     MachineOperand &Op = MI->getOperand(i);
21219     if (!(Op.isReg() && Op.isImplicit()))
21220       MIB.addOperand(Op);
21221   }
21222   if (MI->hasOneMemOperand())
21223     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21224
21225   BuildMI(*BB, MI, dl,
21226     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21227     .addReg(X86::XMM0);
21228
21229   MI->eraseFromParent();
21230   return BB;
21231 }
21232
21233 // FIXME: Custom handling because TableGen doesn't support multiple implicit
21234 // defs in an instruction pattern
21235 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
21236                                        const TargetInstrInfo *TII) {
21237   unsigned Opc;
21238   switch (MI->getOpcode()) {
21239   default: llvm_unreachable("illegal opcode!");
21240   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
21241   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
21242   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
21243   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
21244   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
21245   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
21246   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
21247   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
21248   }
21249
21250   DebugLoc dl = MI->getDebugLoc();
21251   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21252
21253   unsigned NumArgs = MI->getNumOperands(); // remove the results
21254   for (unsigned i = 1; i < NumArgs; ++i) {
21255     MachineOperand &Op = MI->getOperand(i);
21256     if (!(Op.isReg() && Op.isImplicit()))
21257       MIB.addOperand(Op);
21258   }
21259   if (MI->hasOneMemOperand())
21260     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21261
21262   BuildMI(*BB, MI, dl,
21263     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21264     .addReg(X86::ECX);
21265
21266   MI->eraseFromParent();
21267   return BB;
21268 }
21269
21270 static MachineBasicBlock *EmitWRPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21271                                      const X86Subtarget *Subtarget) {
21272   DebugLoc dl = MI->getDebugLoc();
21273   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21274
21275   // insert input VAL into EAX
21276   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
21277                            .addReg(MI->getOperand(0).getReg());
21278   // insert zero to ECX
21279   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21280                            .addReg(X86::ECX)
21281                            .addReg(X86::ECX);
21282   // insert zero to EDX
21283   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::EDX)
21284                            .addReg(X86::EDX)
21285                            .addReg(X86::EDX);
21286   // insert WRPKRU instruction
21287   BuildMI(*BB, MI, dl, TII->get(X86::WRPKRUr));
21288
21289   MI->eraseFromParent(); // The pseudo is gone now.
21290   return BB;
21291 }
21292
21293 static MachineBasicBlock *EmitRDPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21294                                      const X86Subtarget *Subtarget) {
21295   DebugLoc dl = MI->getDebugLoc();
21296   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21297
21298   // insert zero to ECX
21299   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21300                            .addReg(X86::ECX)
21301                            .addReg(X86::ECX);
21302   // insert RDPKRU instruction
21303   BuildMI(*BB, MI, dl, TII->get(X86::RDPKRUr));
21304   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21305                            .addReg(X86::EAX);
21306
21307   MI->eraseFromParent(); // The pseudo is gone now.
21308   return BB;
21309 }
21310
21311 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
21312                                       const X86Subtarget *Subtarget) {
21313   DebugLoc dl = MI->getDebugLoc();
21314   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21315   // Address into RAX/EAX, other two args into ECX, EDX.
21316   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
21317   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
21318   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
21319   for (int i = 0; i < X86::AddrNumOperands; ++i)
21320     MIB.addOperand(MI->getOperand(i));
21321
21322   unsigned ValOps = X86::AddrNumOperands;
21323   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
21324     .addReg(MI->getOperand(ValOps).getReg());
21325   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
21326     .addReg(MI->getOperand(ValOps+1).getReg());
21327
21328   // The instruction doesn't actually take any operands though.
21329   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
21330
21331   MI->eraseFromParent(); // The pseudo is gone now.
21332   return BB;
21333 }
21334
21335 MachineBasicBlock *
21336 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
21337                                                  MachineBasicBlock *MBB) const {
21338   // Emit va_arg instruction on X86-64.
21339
21340   // Operands to this pseudo-instruction:
21341   // 0  ) Output        : destination address (reg)
21342   // 1-5) Input         : va_list address (addr, i64mem)
21343   // 6  ) ArgSize       : Size (in bytes) of vararg type
21344   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
21345   // 8  ) Align         : Alignment of type
21346   // 9  ) EFLAGS (implicit-def)
21347
21348   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
21349   static_assert(X86::AddrNumOperands == 5,
21350                 "VAARG_64 assumes 5 address operands");
21351
21352   unsigned DestReg = MI->getOperand(0).getReg();
21353   MachineOperand &Base = MI->getOperand(1);
21354   MachineOperand &Scale = MI->getOperand(2);
21355   MachineOperand &Index = MI->getOperand(3);
21356   MachineOperand &Disp = MI->getOperand(4);
21357   MachineOperand &Segment = MI->getOperand(5);
21358   unsigned ArgSize = MI->getOperand(6).getImm();
21359   unsigned ArgMode = MI->getOperand(7).getImm();
21360   unsigned Align = MI->getOperand(8).getImm();
21361
21362   // Memory Reference
21363   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
21364   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21365   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21366
21367   // Machine Information
21368   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21369   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
21370   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
21371   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
21372   DebugLoc DL = MI->getDebugLoc();
21373
21374   // struct va_list {
21375   //   i32   gp_offset
21376   //   i32   fp_offset
21377   //   i64   overflow_area (address)
21378   //   i64   reg_save_area (address)
21379   // }
21380   // sizeof(va_list) = 24
21381   // alignment(va_list) = 8
21382
21383   unsigned TotalNumIntRegs = 6;
21384   unsigned TotalNumXMMRegs = 8;
21385   bool UseGPOffset = (ArgMode == 1);
21386   bool UseFPOffset = (ArgMode == 2);
21387   unsigned MaxOffset = TotalNumIntRegs * 8 +
21388                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
21389
21390   /* Align ArgSize to a multiple of 8 */
21391   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
21392   bool NeedsAlign = (Align > 8);
21393
21394   MachineBasicBlock *thisMBB = MBB;
21395   MachineBasicBlock *overflowMBB;
21396   MachineBasicBlock *offsetMBB;
21397   MachineBasicBlock *endMBB;
21398
21399   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
21400   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
21401   unsigned OffsetReg = 0;
21402
21403   if (!UseGPOffset && !UseFPOffset) {
21404     // If we only pull from the overflow region, we don't create a branch.
21405     // We don't need to alter control flow.
21406     OffsetDestReg = 0; // unused
21407     OverflowDestReg = DestReg;
21408
21409     offsetMBB = nullptr;
21410     overflowMBB = thisMBB;
21411     endMBB = thisMBB;
21412   } else {
21413     // First emit code to check if gp_offset (or fp_offset) is below the bound.
21414     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
21415     // If not, pull from overflow_area. (branch to overflowMBB)
21416     //
21417     //       thisMBB
21418     //         |     .
21419     //         |        .
21420     //     offsetMBB   overflowMBB
21421     //         |        .
21422     //         |     .
21423     //        endMBB
21424
21425     // Registers for the PHI in endMBB
21426     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
21427     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
21428
21429     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21430     MachineFunction *MF = MBB->getParent();
21431     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21432     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21433     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21434
21435     MachineFunction::iterator MBBIter = ++MBB->getIterator();
21436
21437     // Insert the new basic blocks
21438     MF->insert(MBBIter, offsetMBB);
21439     MF->insert(MBBIter, overflowMBB);
21440     MF->insert(MBBIter, endMBB);
21441
21442     // Transfer the remainder of MBB and its successor edges to endMBB.
21443     endMBB->splice(endMBB->begin(), thisMBB,
21444                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
21445     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
21446
21447     // Make offsetMBB and overflowMBB successors of thisMBB
21448     thisMBB->addSuccessor(offsetMBB);
21449     thisMBB->addSuccessor(overflowMBB);
21450
21451     // endMBB is a successor of both offsetMBB and overflowMBB
21452     offsetMBB->addSuccessor(endMBB);
21453     overflowMBB->addSuccessor(endMBB);
21454
21455     // Load the offset value into a register
21456     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21457     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21458       .addOperand(Base)
21459       .addOperand(Scale)
21460       .addOperand(Index)
21461       .addDisp(Disp, UseFPOffset ? 4 : 0)
21462       .addOperand(Segment)
21463       .setMemRefs(MMOBegin, MMOEnd);
21464
21465     // Check if there is enough room left to pull this argument.
21466     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21467       .addReg(OffsetReg)
21468       .addImm(MaxOffset + 8 - ArgSizeA8);
21469
21470     // Branch to "overflowMBB" if offset >= max
21471     // Fall through to "offsetMBB" otherwise
21472     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21473       .addMBB(overflowMBB);
21474   }
21475
21476   // In offsetMBB, emit code to use the reg_save_area.
21477   if (offsetMBB) {
21478     assert(OffsetReg != 0);
21479
21480     // Read the reg_save_area address.
21481     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21482     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21483       .addOperand(Base)
21484       .addOperand(Scale)
21485       .addOperand(Index)
21486       .addDisp(Disp, 16)
21487       .addOperand(Segment)
21488       .setMemRefs(MMOBegin, MMOEnd);
21489
21490     // Zero-extend the offset
21491     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21492       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21493         .addImm(0)
21494         .addReg(OffsetReg)
21495         .addImm(X86::sub_32bit);
21496
21497     // Add the offset to the reg_save_area to get the final address.
21498     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21499       .addReg(OffsetReg64)
21500       .addReg(RegSaveReg);
21501
21502     // Compute the offset for the next argument
21503     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21504     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21505       .addReg(OffsetReg)
21506       .addImm(UseFPOffset ? 16 : 8);
21507
21508     // Store it back into the va_list.
21509     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21510       .addOperand(Base)
21511       .addOperand(Scale)
21512       .addOperand(Index)
21513       .addDisp(Disp, UseFPOffset ? 4 : 0)
21514       .addOperand(Segment)
21515       .addReg(NextOffsetReg)
21516       .setMemRefs(MMOBegin, MMOEnd);
21517
21518     // Jump to endMBB
21519     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21520       .addMBB(endMBB);
21521   }
21522
21523   //
21524   // Emit code to use overflow area
21525   //
21526
21527   // Load the overflow_area address into a register.
21528   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21529   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21530     .addOperand(Base)
21531     .addOperand(Scale)
21532     .addOperand(Index)
21533     .addDisp(Disp, 8)
21534     .addOperand(Segment)
21535     .setMemRefs(MMOBegin, MMOEnd);
21536
21537   // If we need to align it, do so. Otherwise, just copy the address
21538   // to OverflowDestReg.
21539   if (NeedsAlign) {
21540     // Align the overflow address
21541     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21542     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21543
21544     // aligned_addr = (addr + (align-1)) & ~(align-1)
21545     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21546       .addReg(OverflowAddrReg)
21547       .addImm(Align-1);
21548
21549     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21550       .addReg(TmpReg)
21551       .addImm(~(uint64_t)(Align-1));
21552   } else {
21553     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21554       .addReg(OverflowAddrReg);
21555   }
21556
21557   // Compute the next overflow address after this argument.
21558   // (the overflow address should be kept 8-byte aligned)
21559   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21560   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21561     .addReg(OverflowDestReg)
21562     .addImm(ArgSizeA8);
21563
21564   // Store the new overflow address.
21565   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21566     .addOperand(Base)
21567     .addOperand(Scale)
21568     .addOperand(Index)
21569     .addDisp(Disp, 8)
21570     .addOperand(Segment)
21571     .addReg(NextAddrReg)
21572     .setMemRefs(MMOBegin, MMOEnd);
21573
21574   // If we branched, emit the PHI to the front of endMBB.
21575   if (offsetMBB) {
21576     BuildMI(*endMBB, endMBB->begin(), DL,
21577             TII->get(X86::PHI), DestReg)
21578       .addReg(OffsetDestReg).addMBB(offsetMBB)
21579       .addReg(OverflowDestReg).addMBB(overflowMBB);
21580   }
21581
21582   // Erase the pseudo instruction
21583   MI->eraseFromParent();
21584
21585   return endMBB;
21586 }
21587
21588 MachineBasicBlock *
21589 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21590                                                  MachineInstr *MI,
21591                                                  MachineBasicBlock *MBB) const {
21592   // Emit code to save XMM registers to the stack. The ABI says that the
21593   // number of registers to save is given in %al, so it's theoretically
21594   // possible to do an indirect jump trick to avoid saving all of them,
21595   // however this code takes a simpler approach and just executes all
21596   // of the stores if %al is non-zero. It's less code, and it's probably
21597   // easier on the hardware branch predictor, and stores aren't all that
21598   // expensive anyway.
21599
21600   // Create the new basic blocks. One block contains all the XMM stores,
21601   // and one block is the final destination regardless of whether any
21602   // stores were performed.
21603   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21604   MachineFunction *F = MBB->getParent();
21605   MachineFunction::iterator MBBIter = ++MBB->getIterator();
21606   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21607   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21608   F->insert(MBBIter, XMMSaveMBB);
21609   F->insert(MBBIter, EndMBB);
21610
21611   // Transfer the remainder of MBB and its successor edges to EndMBB.
21612   EndMBB->splice(EndMBB->begin(), MBB,
21613                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21614   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21615
21616   // The original block will now fall through to the XMM save block.
21617   MBB->addSuccessor(XMMSaveMBB);
21618   // The XMMSaveMBB will fall through to the end block.
21619   XMMSaveMBB->addSuccessor(EndMBB);
21620
21621   // Now add the instructions.
21622   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21623   DebugLoc DL = MI->getDebugLoc();
21624
21625   unsigned CountReg = MI->getOperand(0).getReg();
21626   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21627   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21628
21629   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21630     // If %al is 0, branch around the XMM save block.
21631     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21632     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21633     MBB->addSuccessor(EndMBB);
21634   }
21635
21636   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21637   // that was just emitted, but clearly shouldn't be "saved".
21638   assert((MI->getNumOperands() <= 3 ||
21639           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21640           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21641          && "Expected last argument to be EFLAGS");
21642   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21643   // In the XMM save block, save all the XMM argument registers.
21644   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21645     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21646     MachineMemOperand *MMO = F->getMachineMemOperand(
21647         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21648         MachineMemOperand::MOStore,
21649         /*Size=*/16, /*Align=*/16);
21650     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21651       .addFrameIndex(RegSaveFrameIndex)
21652       .addImm(/*Scale=*/1)
21653       .addReg(/*IndexReg=*/0)
21654       .addImm(/*Disp=*/Offset)
21655       .addReg(/*Segment=*/0)
21656       .addReg(MI->getOperand(i).getReg())
21657       .addMemOperand(MMO);
21658   }
21659
21660   MI->eraseFromParent();   // The pseudo instruction is gone now.
21661
21662   return EndMBB;
21663 }
21664
21665 // The EFLAGS operand of SelectItr might be missing a kill marker
21666 // because there were multiple uses of EFLAGS, and ISel didn't know
21667 // which to mark. Figure out whether SelectItr should have had a
21668 // kill marker, and set it if it should. Returns the correct kill
21669 // marker value.
21670 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21671                                      MachineBasicBlock* BB,
21672                                      const TargetRegisterInfo* TRI) {
21673   // Scan forward through BB for a use/def of EFLAGS.
21674   MachineBasicBlock::iterator miI(std::next(SelectItr));
21675   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21676     const MachineInstr& mi = *miI;
21677     if (mi.readsRegister(X86::EFLAGS))
21678       return false;
21679     if (mi.definesRegister(X86::EFLAGS))
21680       break; // Should have kill-flag - update below.
21681   }
21682
21683   // If we hit the end of the block, check whether EFLAGS is live into a
21684   // successor.
21685   if (miI == BB->end()) {
21686     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21687                                           sEnd = BB->succ_end();
21688          sItr != sEnd; ++sItr) {
21689       MachineBasicBlock* succ = *sItr;
21690       if (succ->isLiveIn(X86::EFLAGS))
21691         return false;
21692     }
21693   }
21694
21695   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21696   // out. SelectMI should have a kill flag on EFLAGS.
21697   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21698   return true;
21699 }
21700
21701 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21702 // together with other CMOV pseudo-opcodes into a single basic-block with
21703 // conditional jump around it.
21704 static bool isCMOVPseudo(MachineInstr *MI) {
21705   switch (MI->getOpcode()) {
21706   case X86::CMOV_FR32:
21707   case X86::CMOV_FR64:
21708   case X86::CMOV_GR8:
21709   case X86::CMOV_GR16:
21710   case X86::CMOV_GR32:
21711   case X86::CMOV_RFP32:
21712   case X86::CMOV_RFP64:
21713   case X86::CMOV_RFP80:
21714   case X86::CMOV_V2F64:
21715   case X86::CMOV_V2I64:
21716   case X86::CMOV_V4F32:
21717   case X86::CMOV_V4F64:
21718   case X86::CMOV_V4I64:
21719   case X86::CMOV_V16F32:
21720   case X86::CMOV_V8F32:
21721   case X86::CMOV_V8F64:
21722   case X86::CMOV_V8I64:
21723   case X86::CMOV_V8I1:
21724   case X86::CMOV_V16I1:
21725   case X86::CMOV_V32I1:
21726   case X86::CMOV_V64I1:
21727     return true;
21728
21729   default:
21730     return false;
21731   }
21732 }
21733
21734 MachineBasicBlock *
21735 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21736                                      MachineBasicBlock *BB) const {
21737   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21738   DebugLoc DL = MI->getDebugLoc();
21739
21740   // To "insert" a SELECT_CC instruction, we actually have to insert the
21741   // diamond control-flow pattern.  The incoming instruction knows the
21742   // destination vreg to set, the condition code register to branch on, the
21743   // true/false values to select between, and a branch opcode to use.
21744   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21745   MachineFunction::iterator It = ++BB->getIterator();
21746
21747   //  thisMBB:
21748   //  ...
21749   //   TrueVal = ...
21750   //   cmpTY ccX, r1, r2
21751   //   bCC copy1MBB
21752   //   fallthrough --> copy0MBB
21753   MachineBasicBlock *thisMBB = BB;
21754   MachineFunction *F = BB->getParent();
21755
21756   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21757   // as described above, by inserting a BB, and then making a PHI at the join
21758   // point to select the true and false operands of the CMOV in the PHI.
21759   //
21760   // The code also handles two different cases of multiple CMOV opcodes
21761   // in a row.
21762   //
21763   // Case 1:
21764   // In this case, there are multiple CMOVs in a row, all which are based on
21765   // the same condition setting (or the exact opposite condition setting).
21766   // In this case we can lower all the CMOVs using a single inserted BB, and
21767   // then make a number of PHIs at the join point to model the CMOVs. The only
21768   // trickiness here, is that in a case like:
21769   //
21770   // t2 = CMOV cond1 t1, f1
21771   // t3 = CMOV cond1 t2, f2
21772   //
21773   // when rewriting this into PHIs, we have to perform some renaming on the
21774   // temps since you cannot have a PHI operand refer to a PHI result earlier
21775   // in the same block.  The "simple" but wrong lowering would be:
21776   //
21777   // t2 = PHI t1(BB1), f1(BB2)
21778   // t3 = PHI t2(BB1), f2(BB2)
21779   //
21780   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21781   // renaming is to note that on the path through BB1, t2 is really just a
21782   // copy of t1, and do that renaming, properly generating:
21783   //
21784   // t2 = PHI t1(BB1), f1(BB2)
21785   // t3 = PHI t1(BB1), f2(BB2)
21786   //
21787   // Case 2, we lower cascaded CMOVs such as
21788   //
21789   //   (CMOV (CMOV F, T, cc1), T, cc2)
21790   //
21791   // to two successives branches.  For that, we look for another CMOV as the
21792   // following instruction.
21793   //
21794   // Without this, we would add a PHI between the two jumps, which ends up
21795   // creating a few copies all around. For instance, for
21796   //
21797   //    (sitofp (zext (fcmp une)))
21798   //
21799   // we would generate:
21800   //
21801   //         ucomiss %xmm1, %xmm0
21802   //         movss  <1.0f>, %xmm0
21803   //         movaps  %xmm0, %xmm1
21804   //         jne     .LBB5_2
21805   //         xorps   %xmm1, %xmm1
21806   // .LBB5_2:
21807   //         jp      .LBB5_4
21808   //         movaps  %xmm1, %xmm0
21809   // .LBB5_4:
21810   //         retq
21811   //
21812   // because this custom-inserter would have generated:
21813   //
21814   //   A
21815   //   | \
21816   //   |  B
21817   //   | /
21818   //   C
21819   //   | \
21820   //   |  D
21821   //   | /
21822   //   E
21823   //
21824   // A: X = ...; Y = ...
21825   // B: empty
21826   // C: Z = PHI [X, A], [Y, B]
21827   // D: empty
21828   // E: PHI [X, C], [Z, D]
21829   //
21830   // If we lower both CMOVs in a single step, we can instead generate:
21831   //
21832   //   A
21833   //   | \
21834   //   |  C
21835   //   | /|
21836   //   |/ |
21837   //   |  |
21838   //   |  D
21839   //   | /
21840   //   E
21841   //
21842   // A: X = ...; Y = ...
21843   // D: empty
21844   // E: PHI [X, A], [X, C], [Y, D]
21845   //
21846   // Which, in our sitofp/fcmp example, gives us something like:
21847   //
21848   //         ucomiss %xmm1, %xmm0
21849   //         movss  <1.0f>, %xmm0
21850   //         jne     .LBB5_4
21851   //         jp      .LBB5_4
21852   //         xorps   %xmm0, %xmm0
21853   // .LBB5_4:
21854   //         retq
21855   //
21856   MachineInstr *CascadedCMOV = nullptr;
21857   MachineInstr *LastCMOV = MI;
21858   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21859   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21860   MachineBasicBlock::iterator NextMIIt =
21861       std::next(MachineBasicBlock::iterator(MI));
21862
21863   // Check for case 1, where there are multiple CMOVs with the same condition
21864   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21865   // number of jumps the most.
21866
21867   if (isCMOVPseudo(MI)) {
21868     // See if we have a string of CMOVS with the same condition.
21869     while (NextMIIt != BB->end() &&
21870            isCMOVPseudo(NextMIIt) &&
21871            (NextMIIt->getOperand(3).getImm() == CC ||
21872             NextMIIt->getOperand(3).getImm() == OppCC)) {
21873       LastCMOV = &*NextMIIt;
21874       ++NextMIIt;
21875     }
21876   }
21877
21878   // This checks for case 2, but only do this if we didn't already find
21879   // case 1, as indicated by LastCMOV == MI.
21880   if (LastCMOV == MI &&
21881       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21882       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21883       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21884     CascadedCMOV = &*NextMIIt;
21885   }
21886
21887   MachineBasicBlock *jcc1MBB = nullptr;
21888
21889   // If we have a cascaded CMOV, we lower it to two successive branches to
21890   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21891   if (CascadedCMOV) {
21892     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21893     F->insert(It, jcc1MBB);
21894     jcc1MBB->addLiveIn(X86::EFLAGS);
21895   }
21896
21897   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21898   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21899   F->insert(It, copy0MBB);
21900   F->insert(It, sinkMBB);
21901
21902   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21903   // live into the sink and copy blocks.
21904   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21905
21906   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21907   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21908       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21909     copy0MBB->addLiveIn(X86::EFLAGS);
21910     sinkMBB->addLiveIn(X86::EFLAGS);
21911   }
21912
21913   // Transfer the remainder of BB and its successor edges to sinkMBB.
21914   sinkMBB->splice(sinkMBB->begin(), BB,
21915                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21916   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21917
21918   // Add the true and fallthrough blocks as its successors.
21919   if (CascadedCMOV) {
21920     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21921     BB->addSuccessor(jcc1MBB);
21922
21923     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21924     // jump to the sinkMBB.
21925     jcc1MBB->addSuccessor(copy0MBB);
21926     jcc1MBB->addSuccessor(sinkMBB);
21927   } else {
21928     BB->addSuccessor(copy0MBB);
21929   }
21930
21931   // The true block target of the first (or only) branch is always sinkMBB.
21932   BB->addSuccessor(sinkMBB);
21933
21934   // Create the conditional branch instruction.
21935   unsigned Opc = X86::GetCondBranchFromCond(CC);
21936   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21937
21938   if (CascadedCMOV) {
21939     unsigned Opc2 = X86::GetCondBranchFromCond(
21940         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21941     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21942   }
21943
21944   //  copy0MBB:
21945   //   %FalseValue = ...
21946   //   # fallthrough to sinkMBB
21947   copy0MBB->addSuccessor(sinkMBB);
21948
21949   //  sinkMBB:
21950   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21951   //  ...
21952   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21953   MachineBasicBlock::iterator MIItEnd =
21954     std::next(MachineBasicBlock::iterator(LastCMOV));
21955   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21956   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21957   MachineInstrBuilder MIB;
21958
21959   // As we are creating the PHIs, we have to be careful if there is more than
21960   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21961   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21962   // That also means that PHI construction must work forward from earlier to
21963   // later, and that the code must maintain a mapping from earlier PHI's
21964   // destination registers, and the registers that went into the PHI.
21965
21966   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21967     unsigned DestReg = MIIt->getOperand(0).getReg();
21968     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21969     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21970
21971     // If this CMOV we are generating is the opposite condition from
21972     // the jump we generated, then we have to swap the operands for the
21973     // PHI that is going to be generated.
21974     if (MIIt->getOperand(3).getImm() == OppCC)
21975         std::swap(Op1Reg, Op2Reg);
21976
21977     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21978       Op1Reg = RegRewriteTable[Op1Reg].first;
21979
21980     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21981       Op2Reg = RegRewriteTable[Op2Reg].second;
21982
21983     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21984                   TII->get(X86::PHI), DestReg)
21985           .addReg(Op1Reg).addMBB(copy0MBB)
21986           .addReg(Op2Reg).addMBB(thisMBB);
21987
21988     // Add this PHI to the rewrite table.
21989     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21990   }
21991
21992   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21993   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21994   if (CascadedCMOV) {
21995     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21996     // Copy the PHI result to the register defined by the second CMOV.
21997     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21998             DL, TII->get(TargetOpcode::COPY),
21999             CascadedCMOV->getOperand(0).getReg())
22000         .addReg(MI->getOperand(0).getReg());
22001     CascadedCMOV->eraseFromParent();
22002   }
22003
22004   // Now remove the CMOV(s).
22005   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
22006     (MIIt++)->eraseFromParent();
22007
22008   return sinkMBB;
22009 }
22010
22011 MachineBasicBlock *
22012 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
22013                                        MachineBasicBlock *BB) const {
22014   // Combine the following atomic floating-point modification pattern:
22015   //   a.store(reg OP a.load(acquire), release)
22016   // Transform them into:
22017   //   OPss (%gpr), %xmm
22018   //   movss %xmm, (%gpr)
22019   // Or sd equivalent for 64-bit operations.
22020   unsigned MOp, FOp;
22021   switch (MI->getOpcode()) {
22022   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
22023   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
22024   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
22025   }
22026   const X86InstrInfo *TII = Subtarget->getInstrInfo();
22027   DebugLoc DL = MI->getDebugLoc();
22028   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
22029   MachineOperand MSrc = MI->getOperand(0);
22030   unsigned VSrc = MI->getOperand(5).getReg();
22031   const MachineOperand &Disp = MI->getOperand(3);
22032   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
22033   bool hasDisp = Disp.isGlobal() || Disp.isImm();
22034   if (hasDisp && MSrc.isReg())
22035     MSrc.setIsKill(false);
22036   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
22037                                 .addOperand(/*Base=*/MSrc)
22038                                 .addImm(/*Scale=*/1)
22039                                 .addReg(/*Index=*/0)
22040                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
22041                                 .addReg(0);
22042   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
22043                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
22044                           .addReg(VSrc)
22045                           .addOperand(/*Base=*/MSrc)
22046                           .addImm(/*Scale=*/1)
22047                           .addReg(/*Index=*/0)
22048                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
22049                           .addReg(/*Segment=*/0);
22050   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
22051   MI->eraseFromParent(); // The pseudo instruction is gone now.
22052   return BB;
22053 }
22054
22055 MachineBasicBlock *
22056 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
22057                                         MachineBasicBlock *BB) const {
22058   MachineFunction *MF = BB->getParent();
22059   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22060   DebugLoc DL = MI->getDebugLoc();
22061   const BasicBlock *LLVM_BB = BB->getBasicBlock();
22062
22063   assert(MF->shouldSplitStack());
22064
22065   const bool Is64Bit = Subtarget->is64Bit();
22066   const bool IsLP64 = Subtarget->isTarget64BitLP64();
22067
22068   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
22069   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
22070
22071   // BB:
22072   //  ... [Till the alloca]
22073   // If stacklet is not large enough, jump to mallocMBB
22074   //
22075   // bumpMBB:
22076   //  Allocate by subtracting from RSP
22077   //  Jump to continueMBB
22078   //
22079   // mallocMBB:
22080   //  Allocate by call to runtime
22081   //
22082   // continueMBB:
22083   //  ...
22084   //  [rest of original BB]
22085   //
22086
22087   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22088   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22089   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22090
22091   MachineRegisterInfo &MRI = MF->getRegInfo();
22092   const TargetRegisterClass *AddrRegClass =
22093       getRegClassFor(getPointerTy(MF->getDataLayout()));
22094
22095   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22096     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22097     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
22098     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
22099     sizeVReg = MI->getOperand(1).getReg(),
22100     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
22101
22102   MachineFunction::iterator MBBIter = ++BB->getIterator();
22103
22104   MF->insert(MBBIter, bumpMBB);
22105   MF->insert(MBBIter, mallocMBB);
22106   MF->insert(MBBIter, continueMBB);
22107
22108   continueMBB->splice(continueMBB->begin(), BB,
22109                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
22110   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
22111
22112   // Add code to the main basic block to check if the stack limit has been hit,
22113   // and if so, jump to mallocMBB otherwise to bumpMBB.
22114   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
22115   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
22116     .addReg(tmpSPVReg).addReg(sizeVReg);
22117   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
22118     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
22119     .addReg(SPLimitVReg);
22120   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
22121
22122   // bumpMBB simply decreases the stack pointer, since we know the current
22123   // stacklet has enough space.
22124   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
22125     .addReg(SPLimitVReg);
22126   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
22127     .addReg(SPLimitVReg);
22128   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22129
22130   // Calls into a routine in libgcc to allocate more space from the heap.
22131   const uint32_t *RegMask =
22132       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
22133   if (IsLP64) {
22134     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
22135       .addReg(sizeVReg);
22136     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22137       .addExternalSymbol("__morestack_allocate_stack_space")
22138       .addRegMask(RegMask)
22139       .addReg(X86::RDI, RegState::Implicit)
22140       .addReg(X86::RAX, RegState::ImplicitDefine);
22141   } else if (Is64Bit) {
22142     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
22143       .addReg(sizeVReg);
22144     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22145       .addExternalSymbol("__morestack_allocate_stack_space")
22146       .addRegMask(RegMask)
22147       .addReg(X86::EDI, RegState::Implicit)
22148       .addReg(X86::EAX, RegState::ImplicitDefine);
22149   } else {
22150     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
22151       .addImm(12);
22152     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
22153     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
22154       .addExternalSymbol("__morestack_allocate_stack_space")
22155       .addRegMask(RegMask)
22156       .addReg(X86::EAX, RegState::ImplicitDefine);
22157   }
22158
22159   if (!Is64Bit)
22160     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
22161       .addImm(16);
22162
22163   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
22164     .addReg(IsLP64 ? X86::RAX : X86::EAX);
22165   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22166
22167   // Set up the CFG correctly.
22168   BB->addSuccessor(bumpMBB);
22169   BB->addSuccessor(mallocMBB);
22170   mallocMBB->addSuccessor(continueMBB);
22171   bumpMBB->addSuccessor(continueMBB);
22172
22173   // Take care of the PHI nodes.
22174   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
22175           MI->getOperand(0).getReg())
22176     .addReg(mallocPtrVReg).addMBB(mallocMBB)
22177     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
22178
22179   // Delete the original pseudo instruction.
22180   MI->eraseFromParent();
22181
22182   // And we're done.
22183   return continueMBB;
22184 }
22185
22186 MachineBasicBlock *
22187 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
22188                                         MachineBasicBlock *BB) const {
22189   assert(!Subtarget->isTargetMachO());
22190   DebugLoc DL = MI->getDebugLoc();
22191   MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
22192       *BB->getParent(), *BB, MI, DL, false);
22193   MachineBasicBlock *ResumeBB = ResumeMI->getParent();
22194   MI->eraseFromParent(); // The pseudo instruction is gone now.
22195   return ResumeBB;
22196 }
22197
22198 MachineBasicBlock *
22199 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
22200                                        MachineBasicBlock *BB) const {
22201   MachineFunction *MF = BB->getParent();
22202   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22203   MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
22204   DebugLoc DL = MI->getDebugLoc();
22205
22206   assert(!isAsynchronousEHPersonality(
22207              classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
22208          "SEH does not use catchret!");
22209
22210   // Only 32-bit EH needs to worry about manually restoring stack pointers.
22211   if (!Subtarget->is32Bit())
22212     return BB;
22213
22214   // C++ EH creates a new target block to hold the restore code, and wires up
22215   // the new block to the return destination with a normal JMP_4.
22216   MachineBasicBlock *RestoreMBB =
22217       MF->CreateMachineBasicBlock(BB->getBasicBlock());
22218   assert(BB->succ_size() == 1);
22219   MF->insert(std::next(BB->getIterator()), RestoreMBB);
22220   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
22221   BB->addSuccessor(RestoreMBB);
22222   MI->getOperand(0).setMBB(RestoreMBB);
22223
22224   auto RestoreMBBI = RestoreMBB->begin();
22225   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
22226   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
22227   return BB;
22228 }
22229
22230 MachineBasicBlock *
22231 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
22232                                        MachineBasicBlock *BB) const {
22233   MachineFunction *MF = BB->getParent();
22234   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
22235   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
22236   // Only 32-bit SEH requires special handling for catchpad.
22237   if (IsSEH && Subtarget->is32Bit()) {
22238     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22239     DebugLoc DL = MI->getDebugLoc();
22240     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
22241   }
22242   MI->eraseFromParent();
22243   return BB;
22244 }
22245
22246 MachineBasicBlock *
22247 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
22248                                       MachineBasicBlock *BB) const {
22249   // This is pretty easy.  We're taking the value that we received from
22250   // our load from the relocation, sticking it in either RDI (x86-64)
22251   // or EAX and doing an indirect call.  The return value will then
22252   // be in the normal return register.
22253   MachineFunction *F = BB->getParent();
22254   const X86InstrInfo *TII = Subtarget->getInstrInfo();
22255   DebugLoc DL = MI->getDebugLoc();
22256
22257   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
22258   assert(MI->getOperand(3).isGlobal() && "This should be a global");
22259
22260   // Get a register mask for the lowered call.
22261   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
22262   // proper register mask.
22263   const uint32_t *RegMask =
22264       Subtarget->is64Bit() ?
22265       Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
22266       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
22267   if (Subtarget->is64Bit()) {
22268     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22269                                       TII->get(X86::MOV64rm), X86::RDI)
22270     .addReg(X86::RIP)
22271     .addImm(0).addReg(0)
22272     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22273                       MI->getOperand(3).getTargetFlags())
22274     .addReg(0);
22275     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
22276     addDirectMem(MIB, X86::RDI);
22277     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
22278   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
22279     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22280                                       TII->get(X86::MOV32rm), X86::EAX)
22281     .addReg(0)
22282     .addImm(0).addReg(0)
22283     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22284                       MI->getOperand(3).getTargetFlags())
22285     .addReg(0);
22286     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22287     addDirectMem(MIB, X86::EAX);
22288     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22289   } else {
22290     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22291                                       TII->get(X86::MOV32rm), X86::EAX)
22292     .addReg(TII->getGlobalBaseReg(F))
22293     .addImm(0).addReg(0)
22294     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22295                       MI->getOperand(3).getTargetFlags())
22296     .addReg(0);
22297     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22298     addDirectMem(MIB, X86::EAX);
22299     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22300   }
22301
22302   MI->eraseFromParent(); // The pseudo instruction is gone now.
22303   return BB;
22304 }
22305
22306 MachineBasicBlock *
22307 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
22308                                     MachineBasicBlock *MBB) const {
22309   DebugLoc DL = MI->getDebugLoc();
22310   MachineFunction *MF = MBB->getParent();
22311   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22312   MachineRegisterInfo &MRI = MF->getRegInfo();
22313
22314   const BasicBlock *BB = MBB->getBasicBlock();
22315   MachineFunction::iterator I = ++MBB->getIterator();
22316
22317   // Memory Reference
22318   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22319   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22320
22321   unsigned DstReg;
22322   unsigned MemOpndSlot = 0;
22323
22324   unsigned CurOp = 0;
22325
22326   DstReg = MI->getOperand(CurOp++).getReg();
22327   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
22328   assert(RC->hasType(MVT::i32) && "Invalid destination!");
22329   unsigned mainDstReg = MRI.createVirtualRegister(RC);
22330   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
22331
22332   MemOpndSlot = CurOp;
22333
22334   MVT PVT = getPointerTy(MF->getDataLayout());
22335   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22336          "Invalid Pointer Size!");
22337
22338   // For v = setjmp(buf), we generate
22339   //
22340   // thisMBB:
22341   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
22342   //  SjLjSetup restoreMBB
22343   //
22344   // mainMBB:
22345   //  v_main = 0
22346   //
22347   // sinkMBB:
22348   //  v = phi(main, restore)
22349   //
22350   // restoreMBB:
22351   //  if base pointer being used, load it from frame
22352   //  v_restore = 1
22353
22354   MachineBasicBlock *thisMBB = MBB;
22355   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22356   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22357   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
22358   MF->insert(I, mainMBB);
22359   MF->insert(I, sinkMBB);
22360   MF->push_back(restoreMBB);
22361   restoreMBB->setHasAddressTaken();
22362
22363   MachineInstrBuilder MIB;
22364
22365   // Transfer the remainder of BB and its successor edges to sinkMBB.
22366   sinkMBB->splice(sinkMBB->begin(), MBB,
22367                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22368   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22369
22370   // thisMBB:
22371   unsigned PtrStoreOpc = 0;
22372   unsigned LabelReg = 0;
22373   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22374   Reloc::Model RM = MF->getTarget().getRelocationModel();
22375   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
22376                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
22377
22378   // Prepare IP either in reg or imm.
22379   if (!UseImmLabel) {
22380     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
22381     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
22382     LabelReg = MRI.createVirtualRegister(PtrRC);
22383     if (Subtarget->is64Bit()) {
22384       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
22385               .addReg(X86::RIP)
22386               .addImm(0)
22387               .addReg(0)
22388               .addMBB(restoreMBB)
22389               .addReg(0);
22390     } else {
22391       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
22392       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
22393               .addReg(XII->getGlobalBaseReg(MF))
22394               .addImm(0)
22395               .addReg(0)
22396               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
22397               .addReg(0);
22398     }
22399   } else
22400     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
22401   // Store IP
22402   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
22403   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22404     if (i == X86::AddrDisp)
22405       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
22406     else
22407       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
22408   }
22409   if (!UseImmLabel)
22410     MIB.addReg(LabelReg);
22411   else
22412     MIB.addMBB(restoreMBB);
22413   MIB.setMemRefs(MMOBegin, MMOEnd);
22414   // Setup
22415   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
22416           .addMBB(restoreMBB);
22417
22418   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22419   MIB.addRegMask(RegInfo->getNoPreservedMask());
22420   thisMBB->addSuccessor(mainMBB);
22421   thisMBB->addSuccessor(restoreMBB);
22422
22423   // mainMBB:
22424   //  EAX = 0
22425   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
22426   mainMBB->addSuccessor(sinkMBB);
22427
22428   // sinkMBB:
22429   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
22430           TII->get(X86::PHI), DstReg)
22431     .addReg(mainDstReg).addMBB(mainMBB)
22432     .addReg(restoreDstReg).addMBB(restoreMBB);
22433
22434   // restoreMBB:
22435   if (RegInfo->hasBasePointer(*MF)) {
22436     const bool Uses64BitFramePtr =
22437         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
22438     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
22439     X86FI->setRestoreBasePointer(MF);
22440     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
22441     unsigned BasePtr = RegInfo->getBaseRegister();
22442     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
22443     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
22444                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
22445       .setMIFlag(MachineInstr::FrameSetup);
22446   }
22447   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
22448   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
22449   restoreMBB->addSuccessor(sinkMBB);
22450
22451   MI->eraseFromParent();
22452   return sinkMBB;
22453 }
22454
22455 MachineBasicBlock *
22456 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22457                                      MachineBasicBlock *MBB) const {
22458   DebugLoc DL = MI->getDebugLoc();
22459   MachineFunction *MF = MBB->getParent();
22460   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22461   MachineRegisterInfo &MRI = MF->getRegInfo();
22462
22463   // Memory Reference
22464   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22465   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22466
22467   MVT PVT = getPointerTy(MF->getDataLayout());
22468   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22469          "Invalid Pointer Size!");
22470
22471   const TargetRegisterClass *RC =
22472     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22473   unsigned Tmp = MRI.createVirtualRegister(RC);
22474   // Since FP is only updated here but NOT referenced, it's treated as GPR.
22475   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22476   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22477   unsigned SP = RegInfo->getStackRegister();
22478
22479   MachineInstrBuilder MIB;
22480
22481   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22482   const int64_t SPOffset = 2 * PVT.getStoreSize();
22483
22484   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22485   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22486
22487   // Reload FP
22488   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22489   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22490     MIB.addOperand(MI->getOperand(i));
22491   MIB.setMemRefs(MMOBegin, MMOEnd);
22492   // Reload IP
22493   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22494   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22495     if (i == X86::AddrDisp)
22496       MIB.addDisp(MI->getOperand(i), LabelOffset);
22497     else
22498       MIB.addOperand(MI->getOperand(i));
22499   }
22500   MIB.setMemRefs(MMOBegin, MMOEnd);
22501   // Reload SP
22502   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22503   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22504     if (i == X86::AddrDisp)
22505       MIB.addDisp(MI->getOperand(i), SPOffset);
22506     else
22507       MIB.addOperand(MI->getOperand(i));
22508   }
22509   MIB.setMemRefs(MMOBegin, MMOEnd);
22510   // Jump
22511   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22512
22513   MI->eraseFromParent();
22514   return MBB;
22515 }
22516
22517 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22518 // accumulator loops. Writing back to the accumulator allows the coalescer
22519 // to remove extra copies in the loop.
22520 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
22521 MachineBasicBlock *
22522 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22523                                  MachineBasicBlock *MBB) const {
22524   MachineOperand &AddendOp = MI->getOperand(3);
22525
22526   // Bail out early if the addend isn't a register - we can't switch these.
22527   if (!AddendOp.isReg())
22528     return MBB;
22529
22530   MachineFunction &MF = *MBB->getParent();
22531   MachineRegisterInfo &MRI = MF.getRegInfo();
22532
22533   // Check whether the addend is defined by a PHI:
22534   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22535   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22536   if (!AddendDef.isPHI())
22537     return MBB;
22538
22539   // Look for the following pattern:
22540   // loop:
22541   //   %addend = phi [%entry, 0], [%loop, %result]
22542   //   ...
22543   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22544
22545   // Replace with:
22546   //   loop:
22547   //   %addend = phi [%entry, 0], [%loop, %result]
22548   //   ...
22549   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22550
22551   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22552     assert(AddendDef.getOperand(i).isReg());
22553     MachineOperand PHISrcOp = AddendDef.getOperand(i);
22554     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22555     if (&PHISrcInst == MI) {
22556       // Found a matching instruction.
22557       unsigned NewFMAOpc = 0;
22558       switch (MI->getOpcode()) {
22559         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22560         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22561         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22562         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22563         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22564         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22565         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22566         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22567         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22568         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22569         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22570         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22571         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22572         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22573         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22574         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22575         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22576         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22577         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22578         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22579
22580         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22581         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22582         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22583         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22584         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22585         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22586         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22587         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22588         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22589         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22590         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22591         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22592         default: llvm_unreachable("Unrecognized FMA variant.");
22593       }
22594
22595       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22596       MachineInstrBuilder MIB =
22597         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22598         .addOperand(MI->getOperand(0))
22599         .addOperand(MI->getOperand(3))
22600         .addOperand(MI->getOperand(2))
22601         .addOperand(MI->getOperand(1));
22602       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22603       MI->eraseFromParent();
22604     }
22605   }
22606
22607   return MBB;
22608 }
22609
22610 MachineBasicBlock *
22611 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22612                                                MachineBasicBlock *BB) const {
22613   switch (MI->getOpcode()) {
22614   default: llvm_unreachable("Unexpected instr type to insert");
22615   case X86::TAILJMPd64:
22616   case X86::TAILJMPr64:
22617   case X86::TAILJMPm64:
22618   case X86::TAILJMPd64_REX:
22619   case X86::TAILJMPr64_REX:
22620   case X86::TAILJMPm64_REX:
22621     llvm_unreachable("TAILJMP64 would not be touched here.");
22622   case X86::TCRETURNdi64:
22623   case X86::TCRETURNri64:
22624   case X86::TCRETURNmi64:
22625     return BB;
22626   case X86::WIN_ALLOCA:
22627     return EmitLoweredWinAlloca(MI, BB);
22628   case X86::CATCHRET:
22629     return EmitLoweredCatchRet(MI, BB);
22630   case X86::CATCHPAD:
22631     return EmitLoweredCatchPad(MI, BB);
22632   case X86::SEG_ALLOCA_32:
22633   case X86::SEG_ALLOCA_64:
22634     return EmitLoweredSegAlloca(MI, BB);
22635   case X86::TLSCall_32:
22636   case X86::TLSCall_64:
22637     return EmitLoweredTLSCall(MI, BB);
22638   case X86::CMOV_FR32:
22639   case X86::CMOV_FR64:
22640   case X86::CMOV_FR128:
22641   case X86::CMOV_GR8:
22642   case X86::CMOV_GR16:
22643   case X86::CMOV_GR32:
22644   case X86::CMOV_RFP32:
22645   case X86::CMOV_RFP64:
22646   case X86::CMOV_RFP80:
22647   case X86::CMOV_V2F64:
22648   case X86::CMOV_V2I64:
22649   case X86::CMOV_V4F32:
22650   case X86::CMOV_V4F64:
22651   case X86::CMOV_V4I64:
22652   case X86::CMOV_V16F32:
22653   case X86::CMOV_V8F32:
22654   case X86::CMOV_V8F64:
22655   case X86::CMOV_V8I64:
22656   case X86::CMOV_V8I1:
22657   case X86::CMOV_V16I1:
22658   case X86::CMOV_V32I1:
22659   case X86::CMOV_V64I1:
22660     return EmitLoweredSelect(MI, BB);
22661
22662   case X86::RDFLAGS32:
22663   case X86::RDFLAGS64: {
22664     DebugLoc DL = MI->getDebugLoc();
22665     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22666     unsigned PushF =
22667         MI->getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
22668     unsigned Pop =
22669         MI->getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
22670     BuildMI(*BB, MI, DL, TII->get(PushF));
22671     BuildMI(*BB, MI, DL, TII->get(Pop), MI->getOperand(0).getReg());
22672
22673     MI->eraseFromParent(); // The pseudo is gone now.
22674     return BB;
22675   }
22676
22677   case X86::WRFLAGS32:
22678   case X86::WRFLAGS64: {
22679     DebugLoc DL = MI->getDebugLoc();
22680     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22681     unsigned Push =
22682         MI->getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
22683     unsigned PopF =
22684         MI->getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
22685     BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI->getOperand(0).getReg());
22686     BuildMI(*BB, MI, DL, TII->get(PopF));
22687
22688     MI->eraseFromParent(); // The pseudo is gone now.
22689     return BB;
22690   }
22691
22692   case X86::RELEASE_FADD32mr:
22693   case X86::RELEASE_FADD64mr:
22694     return EmitLoweredAtomicFP(MI, BB);
22695
22696   case X86::FP32_TO_INT16_IN_MEM:
22697   case X86::FP32_TO_INT32_IN_MEM:
22698   case X86::FP32_TO_INT64_IN_MEM:
22699   case X86::FP64_TO_INT16_IN_MEM:
22700   case X86::FP64_TO_INT32_IN_MEM:
22701   case X86::FP64_TO_INT64_IN_MEM:
22702   case X86::FP80_TO_INT16_IN_MEM:
22703   case X86::FP80_TO_INT32_IN_MEM:
22704   case X86::FP80_TO_INT64_IN_MEM: {
22705     MachineFunction *F = BB->getParent();
22706     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22707     DebugLoc DL = MI->getDebugLoc();
22708
22709     // Change the floating point control register to use "round towards zero"
22710     // mode when truncating to an integer value.
22711     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22712     addFrameReference(BuildMI(*BB, MI, DL,
22713                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
22714
22715     // Load the old value of the high byte of the control word...
22716     unsigned OldCW =
22717       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22718     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22719                       CWFrameIdx);
22720
22721     // Set the high part to be round to zero...
22722     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22723       .addImm(0xC7F);
22724
22725     // Reload the modified control word now...
22726     addFrameReference(BuildMI(*BB, MI, DL,
22727                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22728
22729     // Restore the memory image of control word to original value
22730     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22731       .addReg(OldCW);
22732
22733     // Get the X86 opcode to use.
22734     unsigned Opc;
22735     switch (MI->getOpcode()) {
22736     default: llvm_unreachable("illegal opcode!");
22737     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22738     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22739     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22740     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22741     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22742     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22743     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22744     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22745     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22746     }
22747
22748     X86AddressMode AM;
22749     MachineOperand &Op = MI->getOperand(0);
22750     if (Op.isReg()) {
22751       AM.BaseType = X86AddressMode::RegBase;
22752       AM.Base.Reg = Op.getReg();
22753     } else {
22754       AM.BaseType = X86AddressMode::FrameIndexBase;
22755       AM.Base.FrameIndex = Op.getIndex();
22756     }
22757     Op = MI->getOperand(1);
22758     if (Op.isImm())
22759       AM.Scale = Op.getImm();
22760     Op = MI->getOperand(2);
22761     if (Op.isImm())
22762       AM.IndexReg = Op.getImm();
22763     Op = MI->getOperand(3);
22764     if (Op.isGlobal()) {
22765       AM.GV = Op.getGlobal();
22766     } else {
22767       AM.Disp = Op.getImm();
22768     }
22769     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22770                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22771
22772     // Reload the original control word now.
22773     addFrameReference(BuildMI(*BB, MI, DL,
22774                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22775
22776     MI->eraseFromParent();   // The pseudo instruction is gone now.
22777     return BB;
22778   }
22779     // String/text processing lowering.
22780   case X86::PCMPISTRM128REG:
22781   case X86::VPCMPISTRM128REG:
22782   case X86::PCMPISTRM128MEM:
22783   case X86::VPCMPISTRM128MEM:
22784   case X86::PCMPESTRM128REG:
22785   case X86::VPCMPESTRM128REG:
22786   case X86::PCMPESTRM128MEM:
22787   case X86::VPCMPESTRM128MEM:
22788     assert(Subtarget->hasSSE42() &&
22789            "Target must have SSE4.2 or AVX features enabled");
22790     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22791
22792   // String/text processing lowering.
22793   case X86::PCMPISTRIREG:
22794   case X86::VPCMPISTRIREG:
22795   case X86::PCMPISTRIMEM:
22796   case X86::VPCMPISTRIMEM:
22797   case X86::PCMPESTRIREG:
22798   case X86::VPCMPESTRIREG:
22799   case X86::PCMPESTRIMEM:
22800   case X86::VPCMPESTRIMEM:
22801     assert(Subtarget->hasSSE42() &&
22802            "Target must have SSE4.2 or AVX features enabled");
22803     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22804
22805   // Thread synchronization.
22806   case X86::MONITOR:
22807     return EmitMonitor(MI, BB, Subtarget);
22808   // PKU feature
22809   case X86::WRPKRU:
22810     return EmitWRPKRU(MI, BB, Subtarget);
22811   case X86::RDPKRU:
22812     return EmitRDPKRU(MI, BB, Subtarget);
22813   // xbegin
22814   case X86::XBEGIN:
22815     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22816
22817   case X86::VASTART_SAVE_XMM_REGS:
22818     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22819
22820   case X86::VAARG_64:
22821     return EmitVAARG64WithCustomInserter(MI, BB);
22822
22823   case X86::EH_SjLj_SetJmp32:
22824   case X86::EH_SjLj_SetJmp64:
22825     return emitEHSjLjSetJmp(MI, BB);
22826
22827   case X86::EH_SjLj_LongJmp32:
22828   case X86::EH_SjLj_LongJmp64:
22829     return emitEHSjLjLongJmp(MI, BB);
22830
22831   case TargetOpcode::STATEPOINT:
22832     // As an implementation detail, STATEPOINT shares the STACKMAP format at
22833     // this point in the process.  We diverge later.
22834     return emitPatchPoint(MI, BB);
22835
22836   case TargetOpcode::STACKMAP:
22837   case TargetOpcode::PATCHPOINT:
22838     return emitPatchPoint(MI, BB);
22839
22840   case X86::VFMADDPDr213r:
22841   case X86::VFMADDPSr213r:
22842   case X86::VFMADDSDr213r:
22843   case X86::VFMADDSSr213r:
22844   case X86::VFMSUBPDr213r:
22845   case X86::VFMSUBPSr213r:
22846   case X86::VFMSUBSDr213r:
22847   case X86::VFMSUBSSr213r:
22848   case X86::VFNMADDPDr213r:
22849   case X86::VFNMADDPSr213r:
22850   case X86::VFNMADDSDr213r:
22851   case X86::VFNMADDSSr213r:
22852   case X86::VFNMSUBPDr213r:
22853   case X86::VFNMSUBPSr213r:
22854   case X86::VFNMSUBSDr213r:
22855   case X86::VFNMSUBSSr213r:
22856   case X86::VFMADDSUBPDr213r:
22857   case X86::VFMADDSUBPSr213r:
22858   case X86::VFMSUBADDPDr213r:
22859   case X86::VFMSUBADDPSr213r:
22860   case X86::VFMADDPDr213rY:
22861   case X86::VFMADDPSr213rY:
22862   case X86::VFMSUBPDr213rY:
22863   case X86::VFMSUBPSr213rY:
22864   case X86::VFNMADDPDr213rY:
22865   case X86::VFNMADDPSr213rY:
22866   case X86::VFNMSUBPDr213rY:
22867   case X86::VFNMSUBPSr213rY:
22868   case X86::VFMADDSUBPDr213rY:
22869   case X86::VFMADDSUBPSr213rY:
22870   case X86::VFMSUBADDPDr213rY:
22871   case X86::VFMSUBADDPSr213rY:
22872     return emitFMA3Instr(MI, BB);
22873   }
22874 }
22875
22876 //===----------------------------------------------------------------------===//
22877 //                           X86 Optimization Hooks
22878 //===----------------------------------------------------------------------===//
22879
22880 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22881                                                       APInt &KnownZero,
22882                                                       APInt &KnownOne,
22883                                                       const SelectionDAG &DAG,
22884                                                       unsigned Depth) const {
22885   unsigned BitWidth = KnownZero.getBitWidth();
22886   unsigned Opc = Op.getOpcode();
22887   assert((Opc >= ISD::BUILTIN_OP_END ||
22888           Opc == ISD::INTRINSIC_WO_CHAIN ||
22889           Opc == ISD::INTRINSIC_W_CHAIN ||
22890           Opc == ISD::INTRINSIC_VOID) &&
22891          "Should use MaskedValueIsZero if you don't know whether Op"
22892          " is a target node!");
22893
22894   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
22895   switch (Opc) {
22896   default: break;
22897   case X86ISD::ADD:
22898   case X86ISD::SUB:
22899   case X86ISD::ADC:
22900   case X86ISD::SBB:
22901   case X86ISD::SMUL:
22902   case X86ISD::UMUL:
22903   case X86ISD::INC:
22904   case X86ISD::DEC:
22905   case X86ISD::OR:
22906   case X86ISD::XOR:
22907   case X86ISD::AND:
22908     // These nodes' second result is a boolean.
22909     if (Op.getResNo() == 0)
22910       break;
22911     // Fallthrough
22912   case X86ISD::SETCC:
22913     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22914     break;
22915   case ISD::INTRINSIC_WO_CHAIN: {
22916     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22917     unsigned NumLoBits = 0;
22918     switch (IntId) {
22919     default: break;
22920     case Intrinsic::x86_sse_movmsk_ps:
22921     case Intrinsic::x86_avx_movmsk_ps_256:
22922     case Intrinsic::x86_sse2_movmsk_pd:
22923     case Intrinsic::x86_avx_movmsk_pd_256:
22924     case Intrinsic::x86_mmx_pmovmskb:
22925     case Intrinsic::x86_sse2_pmovmskb_128:
22926     case Intrinsic::x86_avx2_pmovmskb: {
22927       // High bits of movmskp{s|d}, pmovmskb are known zero.
22928       switch (IntId) {
22929         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22930         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22931         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22932         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22933         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22934         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22935         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22936         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22937       }
22938       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22939       break;
22940     }
22941     }
22942     break;
22943   }
22944   }
22945 }
22946
22947 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22948   SDValue Op,
22949   const SelectionDAG &,
22950   unsigned Depth) const {
22951   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22952   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22953     return Op.getValueType().getScalarSizeInBits();
22954
22955   // Fallback case.
22956   return 1;
22957 }
22958
22959 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22960 /// node is a GlobalAddress + offset.
22961 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22962                                        const GlobalValue* &GA,
22963                                        int64_t &Offset) const {
22964   if (N->getOpcode() == X86ISD::Wrapper) {
22965     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22966       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22967       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22968       return true;
22969     }
22970   }
22971   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22972 }
22973
22974 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22975 /// FIXME: This could be expanded to support 512 bit vectors as well.
22976 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22977                                         TargetLowering::DAGCombinerInfo &DCI,
22978                                         const X86Subtarget* Subtarget) {
22979   SDLoc dl(N);
22980   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22981   SDValue V1 = SVOp->getOperand(0);
22982   SDValue V2 = SVOp->getOperand(1);
22983   MVT VT = SVOp->getSimpleValueType(0);
22984   unsigned NumElems = VT.getVectorNumElements();
22985
22986   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22987       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22988     //
22989     //                   0,0,0,...
22990     //                      |
22991     //    V      UNDEF    BUILD_VECTOR    UNDEF
22992     //     \      /           \           /
22993     //  CONCAT_VECTOR         CONCAT_VECTOR
22994     //         \                  /
22995     //          \                /
22996     //          RESULT: V + zero extended
22997     //
22998     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22999         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
23000         V1.getOperand(1).getOpcode() != ISD::UNDEF)
23001       return SDValue();
23002
23003     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
23004       return SDValue();
23005
23006     // To match the shuffle mask, the first half of the mask should
23007     // be exactly the first vector, and all the rest a splat with the
23008     // first element of the second one.
23009     for (unsigned i = 0; i != NumElems/2; ++i)
23010       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
23011           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
23012         return SDValue();
23013
23014     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
23015     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
23016       if (Ld->hasNUsesOfValue(1, 0)) {
23017         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
23018         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
23019         SDValue ResNode =
23020           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
23021                                   Ld->getMemoryVT(),
23022                                   Ld->getPointerInfo(),
23023                                   Ld->getAlignment(),
23024                                   false/*isVolatile*/, true/*ReadMem*/,
23025                                   false/*WriteMem*/);
23026
23027         // Make sure the newly-created LOAD is in the same position as Ld in
23028         // terms of dependency. We create a TokenFactor for Ld and ResNode,
23029         // and update uses of Ld's output chain to use the TokenFactor.
23030         if (Ld->hasAnyUseOfValue(1)) {
23031           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23032                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
23033           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
23034           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
23035                                  SDValue(ResNode.getNode(), 1));
23036         }
23037
23038         return DAG.getBitcast(VT, ResNode);
23039       }
23040     }
23041
23042     // Emit a zeroed vector and insert the desired subvector on its
23043     // first half.
23044     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
23045     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
23046     return DCI.CombineTo(N, InsV);
23047   }
23048
23049   return SDValue();
23050 }
23051
23052 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
23053 /// possible.
23054 ///
23055 /// This is the leaf of the recursive combinine below. When we have found some
23056 /// chain of single-use x86 shuffle instructions and accumulated the combined
23057 /// shuffle mask represented by them, this will try to pattern match that mask
23058 /// into either a single instruction if there is a special purpose instruction
23059 /// for this operation, or into a PSHUFB instruction which is a fully general
23060 /// instruction but should only be used to replace chains over a certain depth.
23061 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
23062                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
23063                                    TargetLowering::DAGCombinerInfo &DCI,
23064                                    const X86Subtarget *Subtarget) {
23065   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
23066
23067   // Find the operand that enters the chain. Note that multiple uses are OK
23068   // here, we're not going to remove the operand we find.
23069   SDValue Input = Op.getOperand(0);
23070   while (Input.getOpcode() == ISD::BITCAST)
23071     Input = Input.getOperand(0);
23072
23073   MVT VT = Input.getSimpleValueType();
23074   MVT RootVT = Root.getSimpleValueType();
23075   SDLoc DL(Root);
23076
23077   if (Mask.size() == 1) {
23078     int Index = Mask[0];
23079     assert((Index >= 0 || Index == SM_SentinelUndef ||
23080             Index == SM_SentinelZero) &&
23081            "Invalid shuffle index found!");
23082
23083     // We may end up with an accumulated mask of size 1 as a result of
23084     // widening of shuffle operands (see function canWidenShuffleElements).
23085     // If the only shuffle index is equal to SM_SentinelZero then propagate
23086     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
23087     // mask, and therefore the entire chain of shuffles can be folded away.
23088     if (Index == SM_SentinelZero)
23089       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
23090     else
23091       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
23092                     /*AddTo*/ true);
23093     return true;
23094   }
23095
23096   // Use the float domain if the operand type is a floating point type.
23097   bool FloatDomain = VT.isFloatingPoint();
23098
23099   // For floating point shuffles, we don't have free copies in the shuffle
23100   // instructions or the ability to load as part of the instruction, so
23101   // canonicalize their shuffles to UNPCK or MOV variants.
23102   //
23103   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
23104   // vectors because it can have a load folded into it that UNPCK cannot. This
23105   // doesn't preclude something switching to the shorter encoding post-RA.
23106   //
23107   // FIXME: Should teach these routines about AVX vector widths.
23108   if (FloatDomain && VT.is128BitVector()) {
23109     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
23110       bool Lo = Mask.equals({0, 0});
23111       unsigned Shuffle;
23112       MVT ShuffleVT;
23113       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
23114       // is no slower than UNPCKLPD but has the option to fold the input operand
23115       // into even an unaligned memory load.
23116       if (Lo && Subtarget->hasSSE3()) {
23117         Shuffle = X86ISD::MOVDDUP;
23118         ShuffleVT = MVT::v2f64;
23119       } else {
23120         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
23121         // than the UNPCK variants.
23122         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
23123         ShuffleVT = MVT::v4f32;
23124       }
23125       if (Depth == 1 && Root->getOpcode() == Shuffle)
23126         return false; // Nothing to do!
23127       Op = DAG.getBitcast(ShuffleVT, Input);
23128       DCI.AddToWorklist(Op.getNode());
23129       if (Shuffle == X86ISD::MOVDDUP)
23130         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23131       else
23132         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23133       DCI.AddToWorklist(Op.getNode());
23134       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23135                     /*AddTo*/ true);
23136       return true;
23137     }
23138     if (Subtarget->hasSSE3() &&
23139         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
23140       bool Lo = Mask.equals({0, 0, 2, 2});
23141       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
23142       MVT ShuffleVT = MVT::v4f32;
23143       if (Depth == 1 && Root->getOpcode() == Shuffle)
23144         return false; // Nothing to do!
23145       Op = DAG.getBitcast(ShuffleVT, Input);
23146       DCI.AddToWorklist(Op.getNode());
23147       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23148       DCI.AddToWorklist(Op.getNode());
23149       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23150                     /*AddTo*/ true);
23151       return true;
23152     }
23153     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
23154       bool Lo = Mask.equals({0, 0, 1, 1});
23155       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23156       MVT ShuffleVT = MVT::v4f32;
23157       if (Depth == 1 && Root->getOpcode() == Shuffle)
23158         return false; // Nothing to do!
23159       Op = DAG.getBitcast(ShuffleVT, Input);
23160       DCI.AddToWorklist(Op.getNode());
23161       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23162       DCI.AddToWorklist(Op.getNode());
23163       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23164                     /*AddTo*/ true);
23165       return true;
23166     }
23167   }
23168
23169   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
23170   // variants as none of these have single-instruction variants that are
23171   // superior to the UNPCK formulation.
23172   if (!FloatDomain && VT.is128BitVector() &&
23173       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23174        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
23175        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
23176        Mask.equals(
23177            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
23178     bool Lo = Mask[0] == 0;
23179     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23180     if (Depth == 1 && Root->getOpcode() == Shuffle)
23181       return false; // Nothing to do!
23182     MVT ShuffleVT;
23183     switch (Mask.size()) {
23184     case 8:
23185       ShuffleVT = MVT::v8i16;
23186       break;
23187     case 16:
23188       ShuffleVT = MVT::v16i8;
23189       break;
23190     default:
23191       llvm_unreachable("Impossible mask size!");
23192     };
23193     Op = DAG.getBitcast(ShuffleVT, Input);
23194     DCI.AddToWorklist(Op.getNode());
23195     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23196     DCI.AddToWorklist(Op.getNode());
23197     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23198                   /*AddTo*/ true);
23199     return true;
23200   }
23201
23202   // Don't try to re-form single instruction chains under any circumstances now
23203   // that we've done encoding canonicalization for them.
23204   if (Depth < 2)
23205     return false;
23206
23207   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
23208   // can replace them with a single PSHUFB instruction profitably. Intel's
23209   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
23210   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
23211   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
23212     SmallVector<SDValue, 16> PSHUFBMask;
23213     int NumBytes = VT.getSizeInBits() / 8;
23214     int Ratio = NumBytes / Mask.size();
23215     for (int i = 0; i < NumBytes; ++i) {
23216       if (Mask[i / Ratio] == SM_SentinelUndef) {
23217         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
23218         continue;
23219       }
23220       int M = Mask[i / Ratio] != SM_SentinelZero
23221                   ? Ratio * Mask[i / Ratio] + i % Ratio
23222                   : 255;
23223       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
23224     }
23225     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
23226     Op = DAG.getBitcast(ByteVT, Input);
23227     DCI.AddToWorklist(Op.getNode());
23228     SDValue PSHUFBMaskOp =
23229         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
23230     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
23231     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
23232     DCI.AddToWorklist(Op.getNode());
23233     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23234                   /*AddTo*/ true);
23235     return true;
23236   }
23237
23238   // Failed to find any combines.
23239   return false;
23240 }
23241
23242 /// \brief Fully generic combining of x86 shuffle instructions.
23243 ///
23244 /// This should be the last combine run over the x86 shuffle instructions. Once
23245 /// they have been fully optimized, this will recursively consider all chains
23246 /// of single-use shuffle instructions, build a generic model of the cumulative
23247 /// shuffle operation, and check for simpler instructions which implement this
23248 /// operation. We use this primarily for two purposes:
23249 ///
23250 /// 1) Collapse generic shuffles to specialized single instructions when
23251 ///    equivalent. In most cases, this is just an encoding size win, but
23252 ///    sometimes we will collapse multiple generic shuffles into a single
23253 ///    special-purpose shuffle.
23254 /// 2) Look for sequences of shuffle instructions with 3 or more total
23255 ///    instructions, and replace them with the slightly more expensive SSSE3
23256 ///    PSHUFB instruction if available. We do this as the last combining step
23257 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
23258 ///    a suitable short sequence of other instructions. The PHUFB will either
23259 ///    use a register or have to read from memory and so is slightly (but only
23260 ///    slightly) more expensive than the other shuffle instructions.
23261 ///
23262 /// Because this is inherently a quadratic operation (for each shuffle in
23263 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
23264 /// This should never be an issue in practice as the shuffle lowering doesn't
23265 /// produce sequences of more than 8 instructions.
23266 ///
23267 /// FIXME: We will currently miss some cases where the redundant shuffling
23268 /// would simplify under the threshold for PSHUFB formation because of
23269 /// combine-ordering. To fix this, we should do the redundant instruction
23270 /// combining in this recursive walk.
23271 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
23272                                           ArrayRef<int> RootMask,
23273                                           int Depth, bool HasPSHUFB,
23274                                           SelectionDAG &DAG,
23275                                           TargetLowering::DAGCombinerInfo &DCI,
23276                                           const X86Subtarget *Subtarget) {
23277   // Bound the depth of our recursive combine because this is ultimately
23278   // quadratic in nature.
23279   if (Depth > 8)
23280     return false;
23281
23282   // Directly rip through bitcasts to find the underlying operand.
23283   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
23284     Op = Op.getOperand(0);
23285
23286   MVT VT = Op.getSimpleValueType();
23287   if (!VT.isVector())
23288     return false; // Bail if we hit a non-vector.
23289
23290   assert(Root.getSimpleValueType().isVector() &&
23291          "Shuffles operate on vector types!");
23292   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
23293          "Can only combine shuffles of the same vector register size.");
23294
23295   if (!isTargetShuffle(Op.getOpcode()))
23296     return false;
23297   SmallVector<int, 16> OpMask;
23298   bool IsUnary;
23299   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, true, OpMask, IsUnary);
23300   // We only can combine unary shuffles which we can decode the mask for.
23301   if (!HaveMask || !IsUnary)
23302     return false;
23303
23304   assert(VT.getVectorNumElements() == OpMask.size() &&
23305          "Different mask size from vector size!");
23306   assert(((RootMask.size() > OpMask.size() &&
23307            RootMask.size() % OpMask.size() == 0) ||
23308           (OpMask.size() > RootMask.size() &&
23309            OpMask.size() % RootMask.size() == 0) ||
23310           OpMask.size() == RootMask.size()) &&
23311          "The smaller number of elements must divide the larger.");
23312   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
23313   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
23314   assert(((RootRatio == 1 && OpRatio == 1) ||
23315           (RootRatio == 1) != (OpRatio == 1)) &&
23316          "Must not have a ratio for both incoming and op masks!");
23317
23318   SmallVector<int, 16> Mask;
23319   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
23320
23321   // Merge this shuffle operation's mask into our accumulated mask. Note that
23322   // this shuffle's mask will be the first applied to the input, followed by the
23323   // root mask to get us all the way to the root value arrangement. The reason
23324   // for this order is that we are recursing up the operation chain.
23325   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
23326     int RootIdx = i / RootRatio;
23327     if (RootMask[RootIdx] < 0) {
23328       // This is a zero or undef lane, we're done.
23329       Mask.push_back(RootMask[RootIdx]);
23330       continue;
23331     }
23332
23333     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
23334     int OpIdx = RootMaskedIdx / OpRatio;
23335     if (OpMask[OpIdx] < 0) {
23336       // The incoming lanes are zero or undef, it doesn't matter which ones we
23337       // are using.
23338       Mask.push_back(OpMask[OpIdx]);
23339       continue;
23340     }
23341
23342     // Ok, we have non-zero lanes, map them through.
23343     Mask.push_back(OpMask[OpIdx] * OpRatio +
23344                    RootMaskedIdx % OpRatio);
23345   }
23346
23347   // See if we can recurse into the operand to combine more things.
23348   switch (Op.getOpcode()) {
23349   case X86ISD::PSHUFB:
23350     HasPSHUFB = true;
23351   case X86ISD::PSHUFD:
23352   case X86ISD::PSHUFHW:
23353   case X86ISD::PSHUFLW:
23354     if (Op.getOperand(0).hasOneUse() &&
23355         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23356                                       HasPSHUFB, DAG, DCI, Subtarget))
23357       return true;
23358     break;
23359
23360   case X86ISD::UNPCKL:
23361   case X86ISD::UNPCKH:
23362     assert(Op.getOperand(0) == Op.getOperand(1) &&
23363            "We only combine unary shuffles!");
23364     // We can't check for single use, we have to check that this shuffle is the
23365     // only user.
23366     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
23367         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23368                                       HasPSHUFB, DAG, DCI, Subtarget))
23369       return true;
23370     break;
23371   }
23372
23373   // Minor canonicalization of the accumulated shuffle mask to make it easier
23374   // to match below. All this does is detect masks with squential pairs of
23375   // elements, and shrink them to the half-width mask. It does this in a loop
23376   // so it will reduce the size of the mask to the minimal width mask which
23377   // performs an equivalent shuffle.
23378   SmallVector<int, 16> WidenedMask;
23379   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
23380     Mask = std::move(WidenedMask);
23381     WidenedMask.clear();
23382   }
23383
23384   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
23385                                 Subtarget);
23386 }
23387
23388 /// \brief Get the PSHUF-style mask from PSHUF node.
23389 ///
23390 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
23391 /// PSHUF-style masks that can be reused with such instructions.
23392 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
23393   MVT VT = N.getSimpleValueType();
23394   SmallVector<int, 4> Mask;
23395   bool IsUnary;
23396   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, false, Mask, IsUnary);
23397   (void)HaveMask;
23398   assert(HaveMask);
23399
23400   // If we have more than 128-bits, only the low 128-bits of shuffle mask
23401   // matter. Check that the upper masks are repeats and remove them.
23402   if (VT.getSizeInBits() > 128) {
23403     int LaneElts = 128 / VT.getScalarSizeInBits();
23404 #ifndef NDEBUG
23405     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
23406       for (int j = 0; j < LaneElts; ++j)
23407         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
23408                "Mask doesn't repeat in high 128-bit lanes!");
23409 #endif
23410     Mask.resize(LaneElts);
23411   }
23412
23413   switch (N.getOpcode()) {
23414   case X86ISD::PSHUFD:
23415     return Mask;
23416   case X86ISD::PSHUFLW:
23417     Mask.resize(4);
23418     return Mask;
23419   case X86ISD::PSHUFHW:
23420     Mask.erase(Mask.begin(), Mask.begin() + 4);
23421     for (int &M : Mask)
23422       M -= 4;
23423     return Mask;
23424   default:
23425     llvm_unreachable("No valid shuffle instruction found!");
23426   }
23427 }
23428
23429 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
23430 ///
23431 /// We walk up the chain and look for a combinable shuffle, skipping over
23432 /// shuffles that we could hoist this shuffle's transformation past without
23433 /// altering anything.
23434 static SDValue
23435 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23436                              SelectionDAG &DAG,
23437                              TargetLowering::DAGCombinerInfo &DCI) {
23438   assert(N.getOpcode() == X86ISD::PSHUFD &&
23439          "Called with something other than an x86 128-bit half shuffle!");
23440   SDLoc DL(N);
23441
23442   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23443   // of the shuffles in the chain so that we can form a fresh chain to replace
23444   // this one.
23445   SmallVector<SDValue, 8> Chain;
23446   SDValue V = N.getOperand(0);
23447   for (; V.hasOneUse(); V = V.getOperand(0)) {
23448     switch (V.getOpcode()) {
23449     default:
23450       return SDValue(); // Nothing combined!
23451
23452     case ISD::BITCAST:
23453       // Skip bitcasts as we always know the type for the target specific
23454       // instructions.
23455       continue;
23456
23457     case X86ISD::PSHUFD:
23458       // Found another dword shuffle.
23459       break;
23460
23461     case X86ISD::PSHUFLW:
23462       // Check that the low words (being shuffled) are the identity in the
23463       // dword shuffle, and the high words are self-contained.
23464       if (Mask[0] != 0 || Mask[1] != 1 ||
23465           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23466         return SDValue();
23467
23468       Chain.push_back(V);
23469       continue;
23470
23471     case X86ISD::PSHUFHW:
23472       // Check that the high words (being shuffled) are the identity in the
23473       // dword shuffle, and the low words are self-contained.
23474       if (Mask[2] != 2 || Mask[3] != 3 ||
23475           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23476         return SDValue();
23477
23478       Chain.push_back(V);
23479       continue;
23480
23481     case X86ISD::UNPCKL:
23482     case X86ISD::UNPCKH:
23483       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23484       // shuffle into a preceding word shuffle.
23485       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23486           V.getSimpleValueType().getVectorElementType() != MVT::i16)
23487         return SDValue();
23488
23489       // Search for a half-shuffle which we can combine with.
23490       unsigned CombineOp =
23491           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23492       if (V.getOperand(0) != V.getOperand(1) ||
23493           !V->isOnlyUserOf(V.getOperand(0).getNode()))
23494         return SDValue();
23495       Chain.push_back(V);
23496       V = V.getOperand(0);
23497       do {
23498         switch (V.getOpcode()) {
23499         default:
23500           return SDValue(); // Nothing to combine.
23501
23502         case X86ISD::PSHUFLW:
23503         case X86ISD::PSHUFHW:
23504           if (V.getOpcode() == CombineOp)
23505             break;
23506
23507           Chain.push_back(V);
23508
23509           // Fallthrough!
23510         case ISD::BITCAST:
23511           V = V.getOperand(0);
23512           continue;
23513         }
23514         break;
23515       } while (V.hasOneUse());
23516       break;
23517     }
23518     // Break out of the loop if we break out of the switch.
23519     break;
23520   }
23521
23522   if (!V.hasOneUse())
23523     // We fell out of the loop without finding a viable combining instruction.
23524     return SDValue();
23525
23526   // Merge this node's mask and our incoming mask.
23527   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23528   for (int &M : Mask)
23529     M = VMask[M];
23530   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23531                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23532
23533   // Rebuild the chain around this new shuffle.
23534   while (!Chain.empty()) {
23535     SDValue W = Chain.pop_back_val();
23536
23537     if (V.getValueType() != W.getOperand(0).getValueType())
23538       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23539
23540     switch (W.getOpcode()) {
23541     default:
23542       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23543
23544     case X86ISD::UNPCKL:
23545     case X86ISD::UNPCKH:
23546       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23547       break;
23548
23549     case X86ISD::PSHUFD:
23550     case X86ISD::PSHUFLW:
23551     case X86ISD::PSHUFHW:
23552       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23553       break;
23554     }
23555   }
23556   if (V.getValueType() != N.getValueType())
23557     V = DAG.getBitcast(N.getValueType(), V);
23558
23559   // Return the new chain to replace N.
23560   return V;
23561 }
23562
23563 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23564 /// pshufhw.
23565 ///
23566 /// We walk up the chain, skipping shuffles of the other half and looking
23567 /// through shuffles which switch halves trying to find a shuffle of the same
23568 /// pair of dwords.
23569 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23570                                         SelectionDAG &DAG,
23571                                         TargetLowering::DAGCombinerInfo &DCI) {
23572   assert(
23573       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23574       "Called with something other than an x86 128-bit half shuffle!");
23575   SDLoc DL(N);
23576   unsigned CombineOpcode = N.getOpcode();
23577
23578   // Walk up a single-use chain looking for a combinable shuffle.
23579   SDValue V = N.getOperand(0);
23580   for (; V.hasOneUse(); V = V.getOperand(0)) {
23581     switch (V.getOpcode()) {
23582     default:
23583       return false; // Nothing combined!
23584
23585     case ISD::BITCAST:
23586       // Skip bitcasts as we always know the type for the target specific
23587       // instructions.
23588       continue;
23589
23590     case X86ISD::PSHUFLW:
23591     case X86ISD::PSHUFHW:
23592       if (V.getOpcode() == CombineOpcode)
23593         break;
23594
23595       // Other-half shuffles are no-ops.
23596       continue;
23597     }
23598     // Break out of the loop if we break out of the switch.
23599     break;
23600   }
23601
23602   if (!V.hasOneUse())
23603     // We fell out of the loop without finding a viable combining instruction.
23604     return false;
23605
23606   // Combine away the bottom node as its shuffle will be accumulated into
23607   // a preceding shuffle.
23608   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23609
23610   // Record the old value.
23611   SDValue Old = V;
23612
23613   // Merge this node's mask and our incoming mask (adjusted to account for all
23614   // the pshufd instructions encountered).
23615   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23616   for (int &M : Mask)
23617     M = VMask[M];
23618   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23619                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23620
23621   // Check that the shuffles didn't cancel each other out. If not, we need to
23622   // combine to the new one.
23623   if (Old != V)
23624     // Replace the combinable shuffle with the combined one, updating all users
23625     // so that we re-evaluate the chain here.
23626     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23627
23628   return true;
23629 }
23630
23631 /// \brief Try to combine x86 target specific shuffles.
23632 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23633                                            TargetLowering::DAGCombinerInfo &DCI,
23634                                            const X86Subtarget *Subtarget) {
23635   SDLoc DL(N);
23636   MVT VT = N.getSimpleValueType();
23637   SmallVector<int, 4> Mask;
23638
23639   switch (N.getOpcode()) {
23640   case X86ISD::PSHUFD:
23641   case X86ISD::PSHUFLW:
23642   case X86ISD::PSHUFHW:
23643     Mask = getPSHUFShuffleMask(N);
23644     assert(Mask.size() == 4);
23645     break;
23646   case X86ISD::UNPCKL: {
23647     // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23648     // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23649     // moves upper half elements into the lower half part. For example:
23650     //
23651     // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23652     //     undef:v16i8
23653     // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23654     //
23655     // will be combined to:
23656     //
23657     // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23658
23659     // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23660     // happen due to advanced instructions.
23661     if (!VT.is128BitVector())
23662       return SDValue();
23663
23664     auto Op0 = N.getOperand(0);
23665     auto Op1 = N.getOperand(1);
23666     if (Op0.getOpcode() == ISD::UNDEF &&
23667         Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23668       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23669
23670       unsigned NumElts = VT.getVectorNumElements();
23671       SmallVector<int, 8> ExpectedMask(NumElts, -1);
23672       std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23673                 NumElts / 2);
23674
23675       auto ShufOp = Op1.getOperand(0);
23676       if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23677         return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23678     }
23679     return SDValue();
23680   }
23681   case X86ISD::BLENDI: {
23682     SDValue V0 = N->getOperand(0);
23683     SDValue V1 = N->getOperand(1);
23684     assert(VT == V0.getSimpleValueType() && VT == V1.getSimpleValueType() &&
23685            "Unexpected input vector types");
23686
23687     // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23688     // operands and changing the mask to 1. This saves us a bunch of
23689     // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23690     // x86InstrInfo knows how to commute this back after instruction selection
23691     // if it would help register allocation.
23692
23693     // TODO: If optimizing for size or a processor that doesn't suffer from
23694     // partial register update stalls, this should be transformed into a MOVSD
23695     // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23696
23697     if (VT == MVT::v2f64)
23698       if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23699         if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23700           SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23701           return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23702         }
23703
23704     return SDValue();
23705   }
23706   default:
23707     return SDValue();
23708   }
23709
23710   // Nuke no-op shuffles that show up after combining.
23711   if (isNoopShuffleMask(Mask))
23712     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23713
23714   // Look for simplifications involving one or two shuffle instructions.
23715   SDValue V = N.getOperand(0);
23716   switch (N.getOpcode()) {
23717   default:
23718     break;
23719   case X86ISD::PSHUFLW:
23720   case X86ISD::PSHUFHW:
23721     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23722
23723     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23724       return SDValue(); // We combined away this shuffle, so we're done.
23725
23726     // See if this reduces to a PSHUFD which is no more expensive and can
23727     // combine with more operations. Note that it has to at least flip the
23728     // dwords as otherwise it would have been removed as a no-op.
23729     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23730       int DMask[] = {0, 1, 2, 3};
23731       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23732       DMask[DOffset + 0] = DOffset + 1;
23733       DMask[DOffset + 1] = DOffset + 0;
23734       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23735       V = DAG.getBitcast(DVT, V);
23736       DCI.AddToWorklist(V.getNode());
23737       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23738                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23739       DCI.AddToWorklist(V.getNode());
23740       return DAG.getBitcast(VT, V);
23741     }
23742
23743     // Look for shuffle patterns which can be implemented as a single unpack.
23744     // FIXME: This doesn't handle the location of the PSHUFD generically, and
23745     // only works when we have a PSHUFD followed by two half-shuffles.
23746     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23747         (V.getOpcode() == X86ISD::PSHUFLW ||
23748          V.getOpcode() == X86ISD::PSHUFHW) &&
23749         V.getOpcode() != N.getOpcode() &&
23750         V.hasOneUse()) {
23751       SDValue D = V.getOperand(0);
23752       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23753         D = D.getOperand(0);
23754       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23755         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23756         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23757         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23758         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23759         int WordMask[8];
23760         for (int i = 0; i < 4; ++i) {
23761           WordMask[i + NOffset] = Mask[i] + NOffset;
23762           WordMask[i + VOffset] = VMask[i] + VOffset;
23763         }
23764         // Map the word mask through the DWord mask.
23765         int MappedMask[8];
23766         for (int i = 0; i < 8; ++i)
23767           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23768         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23769             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23770           // We can replace all three shuffles with an unpack.
23771           V = DAG.getBitcast(VT, D.getOperand(0));
23772           DCI.AddToWorklist(V.getNode());
23773           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23774                                                 : X86ISD::UNPCKH,
23775                              DL, VT, V, V);
23776         }
23777       }
23778     }
23779
23780     break;
23781
23782   case X86ISD::PSHUFD:
23783     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23784       return NewN;
23785
23786     break;
23787   }
23788
23789   return SDValue();
23790 }
23791
23792 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23793 ///
23794 /// We combine this directly on the abstract vector shuffle nodes so it is
23795 /// easier to generically match. We also insert dummy vector shuffle nodes for
23796 /// the operands which explicitly discard the lanes which are unused by this
23797 /// operation to try to flow through the rest of the combiner the fact that
23798 /// they're unused.
23799 static SDValue combineShuffleToAddSub(SDNode *N, const X86Subtarget *Subtarget,
23800                                       SelectionDAG &DAG) {
23801   SDLoc DL(N);
23802   EVT VT = N->getValueType(0);
23803   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
23804       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
23805     return SDValue();
23806
23807   // We only handle target-independent shuffles.
23808   // FIXME: It would be easy and harmless to use the target shuffle mask
23809   // extraction tool to support more.
23810   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23811     return SDValue();
23812
23813   auto *SVN = cast<ShuffleVectorSDNode>(N);
23814   SmallVector<int, 8> Mask;
23815   for (int M : SVN->getMask())
23816     Mask.push_back(M);
23817
23818   SDValue V1 = N->getOperand(0);
23819   SDValue V2 = N->getOperand(1);
23820
23821   // We require the first shuffle operand to be the FSUB node, and the second to
23822   // be the FADD node.
23823   if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23824     ShuffleVectorSDNode::commuteMask(Mask);
23825     std::swap(V1, V2);
23826   } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23827     return SDValue();
23828
23829   // If there are other uses of these operations we can't fold them.
23830   if (!V1->hasOneUse() || !V2->hasOneUse())
23831     return SDValue();
23832
23833   // Ensure that both operations have the same operands. Note that we can
23834   // commute the FADD operands.
23835   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23836   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23837       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23838     return SDValue();
23839
23840   // We're looking for blends between FADD and FSUB nodes. We insist on these
23841   // nodes being lined up in a specific expected pattern.
23842   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23843         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23844         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23845     return SDValue();
23846
23847   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23848 }
23849
23850 /// PerformShuffleCombine - Performs several different shuffle combines.
23851 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23852                                      TargetLowering::DAGCombinerInfo &DCI,
23853                                      const X86Subtarget *Subtarget) {
23854   SDLoc dl(N);
23855   SDValue N0 = N->getOperand(0);
23856   SDValue N1 = N->getOperand(1);
23857   EVT VT = N->getValueType(0);
23858
23859   // Don't create instructions with illegal types after legalize types has run.
23860   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23861   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23862     return SDValue();
23863
23864   // If we have legalized the vector types, look for blends of FADD and FSUB
23865   // nodes that we can fuse into an ADDSUB node.
23866   if (TLI.isTypeLegal(VT))
23867     if (SDValue AddSub = combineShuffleToAddSub(N, Subtarget, DAG))
23868       return AddSub;
23869
23870   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23871   if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23872       N->getOpcode() == ISD::VECTOR_SHUFFLE)
23873     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23874
23875   // During Type Legalization, when promoting illegal vector types,
23876   // the backend might introduce new shuffle dag nodes and bitcasts.
23877   //
23878   // This code performs the following transformation:
23879   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23880   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23881   //
23882   // We do this only if both the bitcast and the BINOP dag nodes have
23883   // one use. Also, perform this transformation only if the new binary
23884   // operation is legal. This is to avoid introducing dag nodes that
23885   // potentially need to be further expanded (or custom lowered) into a
23886   // less optimal sequence of dag nodes.
23887   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23888       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23889       N0.getOpcode() == ISD::BITCAST) {
23890     SDValue BC0 = N0.getOperand(0);
23891     EVT SVT = BC0.getValueType();
23892     unsigned Opcode = BC0.getOpcode();
23893     unsigned NumElts = VT.getVectorNumElements();
23894
23895     if (BC0.hasOneUse() && SVT.isVector() &&
23896         SVT.getVectorNumElements() * 2 == NumElts &&
23897         TLI.isOperationLegal(Opcode, VT)) {
23898       bool CanFold = false;
23899       switch (Opcode) {
23900       default : break;
23901       case ISD::ADD :
23902       case ISD::FADD :
23903       case ISD::SUB :
23904       case ISD::FSUB :
23905       case ISD::MUL :
23906       case ISD::FMUL :
23907         CanFold = true;
23908       }
23909
23910       unsigned SVTNumElts = SVT.getVectorNumElements();
23911       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23912       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23913         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23914       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23915         CanFold = SVOp->getMaskElt(i) < 0;
23916
23917       if (CanFold) {
23918         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23919         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23920         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23921         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23922       }
23923     }
23924   }
23925
23926   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23927   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23928   // consecutive, non-overlapping, and in the right order.
23929   SmallVector<SDValue, 16> Elts;
23930   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23931     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23932
23933   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23934     return LD;
23935
23936   if (isTargetShuffle(N->getOpcode())) {
23937     SDValue Shuffle =
23938         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23939     if (Shuffle.getNode())
23940       return Shuffle;
23941
23942     // Try recursively combining arbitrary sequences of x86 shuffle
23943     // instructions into higher-order shuffles. We do this after combining
23944     // specific PSHUF instruction sequences into their minimal form so that we
23945     // can evaluate how many specialized shuffle instructions are involved in
23946     // a particular chain.
23947     SmallVector<int, 1> NonceMask; // Just a placeholder.
23948     NonceMask.push_back(0);
23949     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23950                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23951                                       DCI, Subtarget))
23952       return SDValue(); // This routine will use CombineTo to replace N.
23953   }
23954
23955   return SDValue();
23956 }
23957
23958 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23959 /// specific shuffle of a load can be folded into a single element load.
23960 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23961 /// shuffles have been custom lowered so we need to handle those here.
23962 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23963                                          TargetLowering::DAGCombinerInfo &DCI) {
23964   if (DCI.isBeforeLegalizeOps())
23965     return SDValue();
23966
23967   SDValue InVec = N->getOperand(0);
23968   SDValue EltNo = N->getOperand(1);
23969   EVT EltVT = N->getValueType(0);
23970
23971   if (!isa<ConstantSDNode>(EltNo))
23972     return SDValue();
23973
23974   EVT OriginalVT = InVec.getValueType();
23975
23976   if (InVec.getOpcode() == ISD::BITCAST) {
23977     // Don't duplicate a load with other uses.
23978     if (!InVec.hasOneUse())
23979       return SDValue();
23980     EVT BCVT = InVec.getOperand(0).getValueType();
23981     if (!BCVT.isVector() ||
23982         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23983       return SDValue();
23984     InVec = InVec.getOperand(0);
23985   }
23986
23987   EVT CurrentVT = InVec.getValueType();
23988
23989   if (!isTargetShuffle(InVec.getOpcode()))
23990     return SDValue();
23991
23992   // Don't duplicate a load with other uses.
23993   if (!InVec.hasOneUse())
23994     return SDValue();
23995
23996   SmallVector<int, 16> ShuffleMask;
23997   bool UnaryShuffle;
23998   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(), true,
23999                             ShuffleMask, UnaryShuffle))
24000     return SDValue();
24001
24002   // Select the input vector, guarding against out of range extract vector.
24003   unsigned NumElems = CurrentVT.getVectorNumElements();
24004   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
24005   int Idx = (Elt > (int)NumElems) ? SM_SentinelUndef : ShuffleMask[Elt];
24006
24007   if (Idx == SM_SentinelZero)
24008     return EltVT.isInteger() ? DAG.getConstant(0, SDLoc(N), EltVT)
24009                              : DAG.getConstantFP(+0.0, SDLoc(N), EltVT);
24010   if (Idx == SM_SentinelUndef)
24011     return DAG.getUNDEF(EltVT);
24012
24013   assert(0 <= Idx && Idx < (int)(2 * NumElems) && "Shuffle index out of range");
24014   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
24015                                          : InVec.getOperand(1);
24016
24017   // If inputs to shuffle are the same for both ops, then allow 2 uses
24018   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
24019                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
24020
24021   if (LdNode.getOpcode() == ISD::BITCAST) {
24022     // Don't duplicate a load with other uses.
24023     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
24024       return SDValue();
24025
24026     AllowedUses = 1; // only allow 1 load use if we have a bitcast
24027     LdNode = LdNode.getOperand(0);
24028   }
24029
24030   if (!ISD::isNormalLoad(LdNode.getNode()))
24031     return SDValue();
24032
24033   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
24034
24035   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
24036     return SDValue();
24037
24038   // If there's a bitcast before the shuffle, check if the load type and
24039   // alignment is valid.
24040   unsigned Align = LN0->getAlignment();
24041   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24042   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
24043       EltVT.getTypeForEVT(*DAG.getContext()));
24044
24045   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
24046     return SDValue();
24047
24048   // All checks match so transform back to vector_shuffle so that DAG combiner
24049   // can finish the job
24050   SDLoc dl(N);
24051
24052   // Create shuffle node taking into account the case that its a unary shuffle
24053   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
24054                                    : InVec.getOperand(1);
24055   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
24056                                  InVec.getOperand(0), Shuffle,
24057                                  &ShuffleMask[0]);
24058   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
24059   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
24060                      EltNo);
24061 }
24062
24063 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
24064                                      const X86Subtarget *Subtarget) {
24065   SDValue N0 = N->getOperand(0);
24066   EVT VT = N->getValueType(0);
24067
24068   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
24069   // special and don't usually play with other vector types, it's better to
24070   // handle them early to be sure we emit efficient code by avoiding
24071   // store-load conversions.
24072   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
24073       N0.getValueType() == MVT::v2i32 &&
24074       isNullConstant(N0.getOperand(1))) {
24075     SDValue N00 = N0->getOperand(0);
24076     if (N00.getValueType() == MVT::i32)
24077       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
24078   }
24079
24080   // Convert a bitcasted integer logic operation that has one bitcasted
24081   // floating-point operand and one constant operand into a floating-point
24082   // logic operation. This may create a load of the constant, but that is
24083   // cheaper than materializing the constant in an integer register and
24084   // transferring it to an SSE register or transferring the SSE operand to
24085   // integer register and back.
24086   unsigned FPOpcode;
24087   switch (N0.getOpcode()) {
24088     case ISD::AND: FPOpcode = X86ISD::FAND; break;
24089     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
24090     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
24091     default: return SDValue();
24092   }
24093   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
24094        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
24095       isa<ConstantSDNode>(N0.getOperand(1)) &&
24096       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
24097       N0.getOperand(0).getOperand(0).getValueType() == VT) {
24098     SDValue N000 = N0.getOperand(0).getOperand(0);
24099     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
24100     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
24101   }
24102
24103   return SDValue();
24104 }
24105
24106 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
24107 /// generation and convert it from being a bunch of shuffles and extracts
24108 /// into a somewhat faster sequence. For i686, the best sequence is apparently
24109 /// storing the value and loading scalars back, while for x64 we should
24110 /// use 64-bit extracts and shifts.
24111 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
24112                                          TargetLowering::DAGCombinerInfo &DCI) {
24113   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
24114     return NewOp;
24115
24116   SDValue InputVector = N->getOperand(0);
24117   SDLoc dl(InputVector);
24118   // Detect mmx to i32 conversion through a v2i32 elt extract.
24119   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
24120       N->getValueType(0) == MVT::i32 &&
24121       InputVector.getValueType() == MVT::v2i32) {
24122
24123     // The bitcast source is a direct mmx result.
24124     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
24125     if (MMXSrc.getValueType() == MVT::x86mmx)
24126       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24127                          N->getValueType(0),
24128                          InputVector.getNode()->getOperand(0));
24129
24130     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
24131     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
24132         MMXSrc.getValueType() == MVT::i64) {
24133       SDValue MMXSrcOp = MMXSrc.getOperand(0);
24134       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
24135           MMXSrcOp.getValueType() == MVT::v1i64 &&
24136           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
24137         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24138                            N->getValueType(0), MMXSrcOp.getOperand(0));
24139     }
24140   }
24141
24142   EVT VT = N->getValueType(0);
24143
24144   if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
24145       InputVector.getOpcode() == ISD::BITCAST &&
24146       isa<ConstantSDNode>(InputVector.getOperand(0))) {
24147     uint64_t ExtractedElt =
24148         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
24149     uint64_t InputValue =
24150         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
24151     uint64_t Res = (InputValue >> ExtractedElt) & 1;
24152     return DAG.getConstant(Res, dl, MVT::i1);
24153   }
24154   // Only operate on vectors of 4 elements, where the alternative shuffling
24155   // gets to be more expensive.
24156   if (InputVector.getValueType() != MVT::v4i32)
24157     return SDValue();
24158
24159   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
24160   // single use which is a sign-extend or zero-extend, and all elements are
24161   // used.
24162   SmallVector<SDNode *, 4> Uses;
24163   unsigned ExtractedElements = 0;
24164   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
24165        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
24166     if (UI.getUse().getResNo() != InputVector.getResNo())
24167       return SDValue();
24168
24169     SDNode *Extract = *UI;
24170     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
24171       return SDValue();
24172
24173     if (Extract->getValueType(0) != MVT::i32)
24174       return SDValue();
24175     if (!Extract->hasOneUse())
24176       return SDValue();
24177     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
24178         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
24179       return SDValue();
24180     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
24181       return SDValue();
24182
24183     // Record which element was extracted.
24184     ExtractedElements |=
24185       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
24186
24187     Uses.push_back(Extract);
24188   }
24189
24190   // If not all the elements were used, this may not be worthwhile.
24191   if (ExtractedElements != 15)
24192     return SDValue();
24193
24194   // Ok, we've now decided to do the transformation.
24195   // If 64-bit shifts are legal, use the extract-shift sequence,
24196   // otherwise bounce the vector off the cache.
24197   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24198   SDValue Vals[4];
24199
24200   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
24201     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
24202     auto &DL = DAG.getDataLayout();
24203     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
24204     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24205       DAG.getConstant(0, dl, VecIdxTy));
24206     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24207       DAG.getConstant(1, dl, VecIdxTy));
24208
24209     SDValue ShAmt = DAG.getConstant(
24210         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
24211     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
24212     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24213       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
24214     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
24215     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24216       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
24217   } else {
24218     // Store the value to a temporary stack slot.
24219     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
24220     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
24221       MachinePointerInfo(), false, false, 0);
24222
24223     EVT ElementType = InputVector.getValueType().getVectorElementType();
24224     unsigned EltSize = ElementType.getSizeInBits() / 8;
24225
24226     // Replace each use (extract) with a load of the appropriate element.
24227     for (unsigned i = 0; i < 4; ++i) {
24228       uint64_t Offset = EltSize * i;
24229       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24230       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
24231
24232       SDValue ScalarAddr =
24233           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
24234
24235       // Load the scalar.
24236       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
24237                             ScalarAddr, MachinePointerInfo(),
24238                             false, false, false, 0);
24239
24240     }
24241   }
24242
24243   // Replace the extracts
24244   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
24245     UE = Uses.end(); UI != UE; ++UI) {
24246     SDNode *Extract = *UI;
24247
24248     SDValue Idx = Extract->getOperand(1);
24249     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
24250     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
24251   }
24252
24253   // The replacement was made in place; don't return anything.
24254   return SDValue();
24255 }
24256
24257 static SDValue
24258 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
24259                                       const X86Subtarget *Subtarget) {
24260   SDLoc dl(N);
24261   SDValue Cond = N->getOperand(0);
24262   SDValue LHS = N->getOperand(1);
24263   SDValue RHS = N->getOperand(2);
24264
24265   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
24266     SDValue CondSrc = Cond->getOperand(0);
24267     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
24268       Cond = CondSrc->getOperand(0);
24269   }
24270
24271   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
24272     return SDValue();
24273
24274   // A vselect where all conditions and data are constants can be optimized into
24275   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
24276   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
24277       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
24278     return SDValue();
24279
24280   unsigned MaskValue = 0;
24281   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
24282     return SDValue();
24283
24284   MVT VT = N->getSimpleValueType(0);
24285   unsigned NumElems = VT.getVectorNumElements();
24286   SmallVector<int, 8> ShuffleMask(NumElems, -1);
24287   for (unsigned i = 0; i < NumElems; ++i) {
24288     // Be sure we emit undef where we can.
24289     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
24290       ShuffleMask[i] = -1;
24291     else
24292       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
24293   }
24294
24295   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24296   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
24297     return SDValue();
24298   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
24299 }
24300
24301 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
24302 /// nodes.
24303 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
24304                                     TargetLowering::DAGCombinerInfo &DCI,
24305                                     const X86Subtarget *Subtarget) {
24306   SDLoc DL(N);
24307   SDValue Cond = N->getOperand(0);
24308   // Get the LHS/RHS of the select.
24309   SDValue LHS = N->getOperand(1);
24310   SDValue RHS = N->getOperand(2);
24311   EVT VT = LHS.getValueType();
24312   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24313
24314   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
24315   // instructions match the semantics of the common C idiom x<y?x:y but not
24316   // x<=y?x:y, because of how they handle negative zero (which can be
24317   // ignored in unsafe-math mode).
24318   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
24319   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
24320       VT != MVT::f80 && VT != MVT::f128 &&
24321       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
24322       (Subtarget->hasSSE2() ||
24323        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
24324     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24325
24326     unsigned Opcode = 0;
24327     // Check for x CC y ? x : y.
24328     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24329         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24330       switch (CC) {
24331       default: break;
24332       case ISD::SETULT:
24333         // Converting this to a min would handle NaNs incorrectly, and swapping
24334         // the operands would cause it to handle comparisons between positive
24335         // and negative zero incorrectly.
24336         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24337           if (!DAG.getTarget().Options.UnsafeFPMath &&
24338               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24339             break;
24340           std::swap(LHS, RHS);
24341         }
24342         Opcode = X86ISD::FMIN;
24343         break;
24344       case ISD::SETOLE:
24345         // Converting this to a min would handle comparisons between positive
24346         // and negative zero incorrectly.
24347         if (!DAG.getTarget().Options.UnsafeFPMath &&
24348             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24349           break;
24350         Opcode = X86ISD::FMIN;
24351         break;
24352       case ISD::SETULE:
24353         // Converting this to a min would handle both negative zeros and NaNs
24354         // incorrectly, but we can swap the operands to fix both.
24355         std::swap(LHS, RHS);
24356       case ISD::SETOLT:
24357       case ISD::SETLT:
24358       case ISD::SETLE:
24359         Opcode = X86ISD::FMIN;
24360         break;
24361
24362       case ISD::SETOGE:
24363         // Converting this to a max would handle comparisons between positive
24364         // and negative zero incorrectly.
24365         if (!DAG.getTarget().Options.UnsafeFPMath &&
24366             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24367           break;
24368         Opcode = X86ISD::FMAX;
24369         break;
24370       case ISD::SETUGT:
24371         // Converting this to a max would handle NaNs incorrectly, and swapping
24372         // the operands would cause it to handle comparisons between positive
24373         // and negative zero incorrectly.
24374         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24375           if (!DAG.getTarget().Options.UnsafeFPMath &&
24376               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24377             break;
24378           std::swap(LHS, RHS);
24379         }
24380         Opcode = X86ISD::FMAX;
24381         break;
24382       case ISD::SETUGE:
24383         // Converting this to a max would handle both negative zeros and NaNs
24384         // incorrectly, but we can swap the operands to fix both.
24385         std::swap(LHS, RHS);
24386       case ISD::SETOGT:
24387       case ISD::SETGT:
24388       case ISD::SETGE:
24389         Opcode = X86ISD::FMAX;
24390         break;
24391       }
24392     // Check for x CC y ? y : x -- a min/max with reversed arms.
24393     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
24394                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
24395       switch (CC) {
24396       default: break;
24397       case ISD::SETOGE:
24398         // Converting this to a min would handle comparisons between positive
24399         // and negative zero incorrectly, and swapping the operands would
24400         // cause it to handle NaNs incorrectly.
24401         if (!DAG.getTarget().Options.UnsafeFPMath &&
24402             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
24403           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24404             break;
24405           std::swap(LHS, RHS);
24406         }
24407         Opcode = X86ISD::FMIN;
24408         break;
24409       case ISD::SETUGT:
24410         // Converting this to a min would handle NaNs incorrectly.
24411         if (!DAG.getTarget().Options.UnsafeFPMath &&
24412             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
24413           break;
24414         Opcode = X86ISD::FMIN;
24415         break;
24416       case ISD::SETUGE:
24417         // Converting this to a min would handle both negative zeros and NaNs
24418         // incorrectly, but we can swap the operands to fix both.
24419         std::swap(LHS, RHS);
24420       case ISD::SETOGT:
24421       case ISD::SETGT:
24422       case ISD::SETGE:
24423         Opcode = X86ISD::FMIN;
24424         break;
24425
24426       case ISD::SETULT:
24427         // Converting this to a max would handle NaNs incorrectly.
24428         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24429           break;
24430         Opcode = X86ISD::FMAX;
24431         break;
24432       case ISD::SETOLE:
24433         // Converting this to a max would handle comparisons between positive
24434         // and negative zero incorrectly, and swapping the operands would
24435         // cause it to handle NaNs incorrectly.
24436         if (!DAG.getTarget().Options.UnsafeFPMath &&
24437             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
24438           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24439             break;
24440           std::swap(LHS, RHS);
24441         }
24442         Opcode = X86ISD::FMAX;
24443         break;
24444       case ISD::SETULE:
24445         // Converting this to a max would handle both negative zeros and NaNs
24446         // incorrectly, but we can swap the operands to fix both.
24447         std::swap(LHS, RHS);
24448       case ISD::SETOLT:
24449       case ISD::SETLT:
24450       case ISD::SETLE:
24451         Opcode = X86ISD::FMAX;
24452         break;
24453       }
24454     }
24455
24456     if (Opcode)
24457       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
24458   }
24459
24460   EVT CondVT = Cond.getValueType();
24461   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
24462       CondVT.getVectorElementType() == MVT::i1) {
24463     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
24464     // lowering on KNL. In this case we convert it to
24465     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24466     // The same situation for all 128 and 256-bit vectors of i8 and i16.
24467     // Since SKX these selects have a proper lowering.
24468     EVT OpVT = LHS.getValueType();
24469     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24470         (OpVT.getVectorElementType() == MVT::i8 ||
24471          OpVT.getVectorElementType() == MVT::i16) &&
24472         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24473       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24474       DCI.AddToWorklist(Cond.getNode());
24475       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24476     }
24477   }
24478   // If this is a select between two integer constants, try to do some
24479   // optimizations.
24480   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24481     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24482       // Don't do this for crazy integer types.
24483       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24484         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24485         // so that TrueC (the true value) is larger than FalseC.
24486         bool NeedsCondInvert = false;
24487
24488         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24489             // Efficiently invertible.
24490             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
24491              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
24492               isa<ConstantSDNode>(Cond.getOperand(1))))) {
24493           NeedsCondInvert = true;
24494           std::swap(TrueC, FalseC);
24495         }
24496
24497         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
24498         if (FalseC->getAPIntValue() == 0 &&
24499             TrueC->getAPIntValue().isPowerOf2()) {
24500           if (NeedsCondInvert) // Invert the condition if needed.
24501             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24502                                DAG.getConstant(1, DL, Cond.getValueType()));
24503
24504           // Zero extend the condition if needed.
24505           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
24506
24507           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24508           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24509                              DAG.getConstant(ShAmt, DL, MVT::i8));
24510         }
24511
24512         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24513         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24514           if (NeedsCondInvert) // Invert the condition if needed.
24515             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24516                                DAG.getConstant(1, DL, Cond.getValueType()));
24517
24518           // Zero extend the condition if needed.
24519           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24520                              FalseC->getValueType(0), Cond);
24521           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24522                              SDValue(FalseC, 0));
24523         }
24524
24525         // Optimize cases that will turn into an LEA instruction.  This requires
24526         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24527         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24528           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24529           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24530
24531           bool isFastMultiplier = false;
24532           if (Diff < 10) {
24533             switch ((unsigned char)Diff) {
24534               default: break;
24535               case 1:  // result = add base, cond
24536               case 2:  // result = lea base(    , cond*2)
24537               case 3:  // result = lea base(cond, cond*2)
24538               case 4:  // result = lea base(    , cond*4)
24539               case 5:  // result = lea base(cond, cond*4)
24540               case 8:  // result = lea base(    , cond*8)
24541               case 9:  // result = lea base(cond, cond*8)
24542                 isFastMultiplier = true;
24543                 break;
24544             }
24545           }
24546
24547           if (isFastMultiplier) {
24548             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24549             if (NeedsCondInvert) // Invert the condition if needed.
24550               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24551                                  DAG.getConstant(1, DL, Cond.getValueType()));
24552
24553             // Zero extend the condition if needed.
24554             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24555                                Cond);
24556             // Scale the condition by the difference.
24557             if (Diff != 1)
24558               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24559                                  DAG.getConstant(Diff, DL,
24560                                                  Cond.getValueType()));
24561
24562             // Add the base if non-zero.
24563             if (FalseC->getAPIntValue() != 0)
24564               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24565                                  SDValue(FalseC, 0));
24566             return Cond;
24567           }
24568         }
24569       }
24570   }
24571
24572   // Canonicalize max and min:
24573   // (x > y) ? x : y -> (x >= y) ? x : y
24574   // (x < y) ? x : y -> (x <= y) ? x : y
24575   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24576   // the need for an extra compare
24577   // against zero. e.g.
24578   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24579   // subl   %esi, %edi
24580   // testl  %edi, %edi
24581   // movl   $0, %eax
24582   // cmovgl %edi, %eax
24583   // =>
24584   // xorl   %eax, %eax
24585   // subl   %esi, $edi
24586   // cmovsl %eax, %edi
24587   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24588       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24589       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24590     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24591     switch (CC) {
24592     default: break;
24593     case ISD::SETLT:
24594     case ISD::SETGT: {
24595       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24596       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24597                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
24598       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24599     }
24600     }
24601   }
24602
24603   // Early exit check
24604   if (!TLI.isTypeLegal(VT))
24605     return SDValue();
24606
24607   // Match VSELECTs into subs with unsigned saturation.
24608   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24609       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24610       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24611        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24612     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24613
24614     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24615     // left side invert the predicate to simplify logic below.
24616     SDValue Other;
24617     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24618       Other = RHS;
24619       CC = ISD::getSetCCInverse(CC, true);
24620     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24621       Other = LHS;
24622     }
24623
24624     if (Other.getNode() && Other->getNumOperands() == 2 &&
24625         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24626       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24627       SDValue CondRHS = Cond->getOperand(1);
24628
24629       // Look for a general sub with unsigned saturation first.
24630       // x >= y ? x-y : 0 --> subus x, y
24631       // x >  y ? x-y : 0 --> subus x, y
24632       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24633           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24634         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24635
24636       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24637         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24638           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24639             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24640               // If the RHS is a constant we have to reverse the const
24641               // canonicalization.
24642               // x > C-1 ? x+-C : 0 --> subus x, C
24643               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24644                   CondRHSConst->getAPIntValue() ==
24645                       (-OpRHSConst->getAPIntValue() - 1))
24646                 return DAG.getNode(
24647                     X86ISD::SUBUS, DL, VT, OpLHS,
24648                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24649
24650           // Another special case: If C was a sign bit, the sub has been
24651           // canonicalized into a xor.
24652           // FIXME: Would it be better to use computeKnownBits to determine
24653           //        whether it's safe to decanonicalize the xor?
24654           // x s< 0 ? x^C : 0 --> subus x, C
24655           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24656               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24657               OpRHSConst->getAPIntValue().isSignBit())
24658             // Note that we have to rebuild the RHS constant here to ensure we
24659             // don't rely on particular values of undef lanes.
24660             return DAG.getNode(
24661                 X86ISD::SUBUS, DL, VT, OpLHS,
24662                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24663         }
24664     }
24665   }
24666
24667   // Simplify vector selection if condition value type matches vselect
24668   // operand type
24669   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24670     assert(Cond.getValueType().isVector() &&
24671            "vector select expects a vector selector!");
24672
24673     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24674     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24675
24676     // Try invert the condition if true value is not all 1s and false value
24677     // is not all 0s.
24678     if (!TValIsAllOnes && !FValIsAllZeros &&
24679         // Check if the selector will be produced by CMPP*/PCMP*
24680         Cond.getOpcode() == ISD::SETCC &&
24681         // Check if SETCC has already been promoted
24682         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24683             CondVT) {
24684       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24685       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24686
24687       if (TValIsAllZeros || FValIsAllOnes) {
24688         SDValue CC = Cond.getOperand(2);
24689         ISD::CondCode NewCC =
24690           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24691                                Cond.getOperand(0).getValueType().isInteger());
24692         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24693         std::swap(LHS, RHS);
24694         TValIsAllOnes = FValIsAllOnes;
24695         FValIsAllZeros = TValIsAllZeros;
24696       }
24697     }
24698
24699     if (TValIsAllOnes || FValIsAllZeros) {
24700       SDValue Ret;
24701
24702       if (TValIsAllOnes && FValIsAllZeros)
24703         Ret = Cond;
24704       else if (TValIsAllOnes)
24705         Ret =
24706             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24707       else if (FValIsAllZeros)
24708         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24709                           DAG.getBitcast(CondVT, LHS));
24710
24711       return DAG.getBitcast(VT, Ret);
24712     }
24713   }
24714
24715   // We should generate an X86ISD::BLENDI from a vselect if its argument
24716   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24717   // constants. This specific pattern gets generated when we split a
24718   // selector for a 512 bit vector in a machine without AVX512 (but with
24719   // 256-bit vectors), during legalization:
24720   //
24721   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24722   //
24723   // Iff we find this pattern and the build_vectors are built from
24724   // constants, we translate the vselect into a shuffle_vector that we
24725   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24726   if ((N->getOpcode() == ISD::VSELECT ||
24727        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24728       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24729     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24730     if (Shuffle.getNode())
24731       return Shuffle;
24732   }
24733
24734   // If this is a *dynamic* select (non-constant condition) and we can match
24735   // this node with one of the variable blend instructions, restructure the
24736   // condition so that the blends can use the high bit of each element and use
24737   // SimplifyDemandedBits to simplify the condition operand.
24738   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24739       !DCI.isBeforeLegalize() &&
24740       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24741     unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24742
24743     // Don't optimize vector selects that map to mask-registers.
24744     if (BitWidth == 1)
24745       return SDValue();
24746
24747     // We can only handle the cases where VSELECT is directly legal on the
24748     // subtarget. We custom lower VSELECT nodes with constant conditions and
24749     // this makes it hard to see whether a dynamic VSELECT will correctly
24750     // lower, so we both check the operation's status and explicitly handle the
24751     // cases where a *dynamic* blend will fail even though a constant-condition
24752     // blend could be custom lowered.
24753     // FIXME: We should find a better way to handle this class of problems.
24754     // Potentially, we should combine constant-condition vselect nodes
24755     // pre-legalization into shuffles and not mark as many types as custom
24756     // lowered.
24757     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24758       return SDValue();
24759     // FIXME: We don't support i16-element blends currently. We could and
24760     // should support them by making *all* the bits in the condition be set
24761     // rather than just the high bit and using an i8-element blend.
24762     if (VT.getVectorElementType() == MVT::i16)
24763       return SDValue();
24764     // Dynamic blending was only available from SSE4.1 onward.
24765     if (VT.is128BitVector() && !Subtarget->hasSSE41())
24766       return SDValue();
24767     // Byte blends are only available in AVX2
24768     if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24769       return SDValue();
24770
24771     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24772     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24773
24774     APInt KnownZero, KnownOne;
24775     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24776                                           DCI.isBeforeLegalizeOps());
24777     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24778         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24779                                  TLO)) {
24780       // If we changed the computation somewhere in the DAG, this change
24781       // will affect all users of Cond.
24782       // Make sure it is fine and update all the nodes so that we do not
24783       // use the generic VSELECT anymore. Otherwise, we may perform
24784       // wrong optimizations as we messed up with the actual expectation
24785       // for the vector boolean values.
24786       if (Cond != TLO.Old) {
24787         // Check all uses of that condition operand to check whether it will be
24788         // consumed by non-BLEND instructions, which may depend on all bits are
24789         // set properly.
24790         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24791              I != E; ++I)
24792           if (I->getOpcode() != ISD::VSELECT)
24793             // TODO: Add other opcodes eventually lowered into BLEND.
24794             return SDValue();
24795
24796         // Update all the users of the condition, before committing the change,
24797         // so that the VSELECT optimizations that expect the correct vector
24798         // boolean value will not be triggered.
24799         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24800              I != E; ++I)
24801           DAG.ReplaceAllUsesOfValueWith(
24802               SDValue(*I, 0),
24803               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24804                           Cond, I->getOperand(1), I->getOperand(2)));
24805         DCI.CommitTargetLoweringOpt(TLO);
24806         return SDValue();
24807       }
24808       // At this point, only Cond is changed. Change the condition
24809       // just for N to keep the opportunity to optimize all other
24810       // users their own way.
24811       DAG.ReplaceAllUsesOfValueWith(
24812           SDValue(N, 0),
24813           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24814                       TLO.New, N->getOperand(1), N->getOperand(2)));
24815       return SDValue();
24816     }
24817   }
24818
24819   return SDValue();
24820 }
24821
24822 // Check whether a boolean test is testing a boolean value generated by
24823 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24824 // code.
24825 //
24826 // Simplify the following patterns:
24827 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24828 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24829 // to (Op EFLAGS Cond)
24830 //
24831 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24832 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24833 // to (Op EFLAGS !Cond)
24834 //
24835 // where Op could be BRCOND or CMOV.
24836 //
24837 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24838   // Quit if not CMP and SUB with its value result used.
24839   if (Cmp.getOpcode() != X86ISD::CMP &&
24840       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24841       return SDValue();
24842
24843   // Quit if not used as a boolean value.
24844   if (CC != X86::COND_E && CC != X86::COND_NE)
24845     return SDValue();
24846
24847   // Check CMP operands. One of them should be 0 or 1 and the other should be
24848   // an SetCC or extended from it.
24849   SDValue Op1 = Cmp.getOperand(0);
24850   SDValue Op2 = Cmp.getOperand(1);
24851
24852   SDValue SetCC;
24853   const ConstantSDNode* C = nullptr;
24854   bool needOppositeCond = (CC == X86::COND_E);
24855   bool checkAgainstTrue = false; // Is it a comparison against 1?
24856
24857   if ((C = dyn_cast<ConstantSDNode>(Op1)))
24858     SetCC = Op2;
24859   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24860     SetCC = Op1;
24861   else // Quit if all operands are not constants.
24862     return SDValue();
24863
24864   if (C->getZExtValue() == 1) {
24865     needOppositeCond = !needOppositeCond;
24866     checkAgainstTrue = true;
24867   } else if (C->getZExtValue() != 0)
24868     // Quit if the constant is neither 0 or 1.
24869     return SDValue();
24870
24871   bool truncatedToBoolWithAnd = false;
24872   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24873   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24874          SetCC.getOpcode() == ISD::TRUNCATE ||
24875          SetCC.getOpcode() == ISD::AND) {
24876     if (SetCC.getOpcode() == ISD::AND) {
24877       int OpIdx = -1;
24878       if (isOneConstant(SetCC.getOperand(0)))
24879         OpIdx = 1;
24880       if (isOneConstant(SetCC.getOperand(1)))
24881         OpIdx = 0;
24882       if (OpIdx == -1)
24883         break;
24884       SetCC = SetCC.getOperand(OpIdx);
24885       truncatedToBoolWithAnd = true;
24886     } else
24887       SetCC = SetCC.getOperand(0);
24888   }
24889
24890   switch (SetCC.getOpcode()) {
24891   case X86ISD::SETCC_CARRY:
24892     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24893     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24894     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24895     // truncated to i1 using 'and'.
24896     if (checkAgainstTrue && !truncatedToBoolWithAnd)
24897       break;
24898     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24899            "Invalid use of SETCC_CARRY!");
24900     // FALL THROUGH
24901   case X86ISD::SETCC:
24902     // Set the condition code or opposite one if necessary.
24903     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24904     if (needOppositeCond)
24905       CC = X86::GetOppositeBranchCondition(CC);
24906     return SetCC.getOperand(1);
24907   case X86ISD::CMOV: {
24908     // Check whether false/true value has canonical one, i.e. 0 or 1.
24909     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24910     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24911     // Quit if true value is not a constant.
24912     if (!TVal)
24913       return SDValue();
24914     // Quit if false value is not a constant.
24915     if (!FVal) {
24916       SDValue Op = SetCC.getOperand(0);
24917       // Skip 'zext' or 'trunc' node.
24918       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24919           Op.getOpcode() == ISD::TRUNCATE)
24920         Op = Op.getOperand(0);
24921       // A special case for rdrand/rdseed, where 0 is set if false cond is
24922       // found.
24923       if ((Op.getOpcode() != X86ISD::RDRAND &&
24924            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24925         return SDValue();
24926     }
24927     // Quit if false value is not the constant 0 or 1.
24928     bool FValIsFalse = true;
24929     if (FVal && FVal->getZExtValue() != 0) {
24930       if (FVal->getZExtValue() != 1)
24931         return SDValue();
24932       // If FVal is 1, opposite cond is needed.
24933       needOppositeCond = !needOppositeCond;
24934       FValIsFalse = false;
24935     }
24936     // Quit if TVal is not the constant opposite of FVal.
24937     if (FValIsFalse && TVal->getZExtValue() != 1)
24938       return SDValue();
24939     if (!FValIsFalse && TVal->getZExtValue() != 0)
24940       return SDValue();
24941     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24942     if (needOppositeCond)
24943       CC = X86::GetOppositeBranchCondition(CC);
24944     return SetCC.getOperand(3);
24945   }
24946   }
24947
24948   return SDValue();
24949 }
24950
24951 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24952 /// Match:
24953 ///   (X86or (X86setcc) (X86setcc))
24954 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24955 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24956                                            X86::CondCode &CC1, SDValue &Flags,
24957                                            bool &isAnd) {
24958   if (Cond->getOpcode() == X86ISD::CMP) {
24959     if (!isNullConstant(Cond->getOperand(1)))
24960       return false;
24961
24962     Cond = Cond->getOperand(0);
24963   }
24964
24965   isAnd = false;
24966
24967   SDValue SetCC0, SetCC1;
24968   switch (Cond->getOpcode()) {
24969   default: return false;
24970   case ISD::AND:
24971   case X86ISD::AND:
24972     isAnd = true;
24973     // fallthru
24974   case ISD::OR:
24975   case X86ISD::OR:
24976     SetCC0 = Cond->getOperand(0);
24977     SetCC1 = Cond->getOperand(1);
24978     break;
24979   };
24980
24981   // Make sure we have SETCC nodes, using the same flags value.
24982   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24983       SetCC1.getOpcode() != X86ISD::SETCC ||
24984       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24985     return false;
24986
24987   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24988   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24989   Flags = SetCC0->getOperand(1);
24990   return true;
24991 }
24992
24993 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24994 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24995                                   TargetLowering::DAGCombinerInfo &DCI,
24996                                   const X86Subtarget *Subtarget) {
24997   SDLoc DL(N);
24998
24999   // If the flag operand isn't dead, don't touch this CMOV.
25000   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
25001     return SDValue();
25002
25003   SDValue FalseOp = N->getOperand(0);
25004   SDValue TrueOp = N->getOperand(1);
25005   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
25006   SDValue Cond = N->getOperand(3);
25007
25008   if (CC == X86::COND_E || CC == X86::COND_NE) {
25009     switch (Cond.getOpcode()) {
25010     default: break;
25011     case X86ISD::BSR:
25012     case X86ISD::BSF:
25013       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
25014       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
25015         return (CC == X86::COND_E) ? FalseOp : TrueOp;
25016     }
25017   }
25018
25019   SDValue Flags;
25020
25021   Flags = checkBoolTestSetCCCombine(Cond, CC);
25022   if (Flags.getNode() &&
25023       // Extra check as FCMOV only supports a subset of X86 cond.
25024       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
25025     SDValue Ops[] = { FalseOp, TrueOp,
25026                       DAG.getConstant(CC, DL, MVT::i8), Flags };
25027     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25028   }
25029
25030   // If this is a select between two integer constants, try to do some
25031   // optimizations.  Note that the operands are ordered the opposite of SELECT
25032   // operands.
25033   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
25034     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
25035       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
25036       // larger than FalseC (the false value).
25037       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
25038         CC = X86::GetOppositeBranchCondition(CC);
25039         std::swap(TrueC, FalseC);
25040         std::swap(TrueOp, FalseOp);
25041       }
25042
25043       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
25044       // This is efficient for any integer data type (including i8/i16) and
25045       // shift amount.
25046       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
25047         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25048                            DAG.getConstant(CC, DL, MVT::i8), Cond);
25049
25050         // Zero extend the condition if needed.
25051         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
25052
25053         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
25054         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
25055                            DAG.getConstant(ShAmt, DL, MVT::i8));
25056         if (N->getNumValues() == 2)  // Dead flag value?
25057           return DCI.CombineTo(N, Cond, SDValue());
25058         return Cond;
25059       }
25060
25061       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
25062       // for any integer data type, including i8/i16.
25063       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
25064         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25065                            DAG.getConstant(CC, DL, MVT::i8), Cond);
25066
25067         // Zero extend the condition if needed.
25068         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
25069                            FalseC->getValueType(0), Cond);
25070         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25071                            SDValue(FalseC, 0));
25072
25073         if (N->getNumValues() == 2)  // Dead flag value?
25074           return DCI.CombineTo(N, Cond, SDValue());
25075         return Cond;
25076       }
25077
25078       // Optimize cases that will turn into an LEA instruction.  This requires
25079       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
25080       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
25081         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
25082         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
25083
25084         bool isFastMultiplier = false;
25085         if (Diff < 10) {
25086           switch ((unsigned char)Diff) {
25087           default: break;
25088           case 1:  // result = add base, cond
25089           case 2:  // result = lea base(    , cond*2)
25090           case 3:  // result = lea base(cond, cond*2)
25091           case 4:  // result = lea base(    , cond*4)
25092           case 5:  // result = lea base(cond, cond*4)
25093           case 8:  // result = lea base(    , cond*8)
25094           case 9:  // result = lea base(cond, cond*8)
25095             isFastMultiplier = true;
25096             break;
25097           }
25098         }
25099
25100         if (isFastMultiplier) {
25101           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
25102           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25103                              DAG.getConstant(CC, DL, MVT::i8), Cond);
25104           // Zero extend the condition if needed.
25105           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
25106                              Cond);
25107           // Scale the condition by the difference.
25108           if (Diff != 1)
25109             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
25110                                DAG.getConstant(Diff, DL, Cond.getValueType()));
25111
25112           // Add the base if non-zero.
25113           if (FalseC->getAPIntValue() != 0)
25114             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25115                                SDValue(FalseC, 0));
25116           if (N->getNumValues() == 2)  // Dead flag value?
25117             return DCI.CombineTo(N, Cond, SDValue());
25118           return Cond;
25119         }
25120       }
25121     }
25122   }
25123
25124   // Handle these cases:
25125   //   (select (x != c), e, c) -> select (x != c), e, x),
25126   //   (select (x == c), c, e) -> select (x == c), x, e)
25127   // where the c is an integer constant, and the "select" is the combination
25128   // of CMOV and CMP.
25129   //
25130   // The rationale for this change is that the conditional-move from a constant
25131   // needs two instructions, however, conditional-move from a register needs
25132   // only one instruction.
25133   //
25134   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
25135   //  some instruction-combining opportunities. This opt needs to be
25136   //  postponed as late as possible.
25137   //
25138   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
25139     // the DCI.xxxx conditions are provided to postpone the optimization as
25140     // late as possible.
25141
25142     ConstantSDNode *CmpAgainst = nullptr;
25143     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
25144         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
25145         !isa<ConstantSDNode>(Cond.getOperand(0))) {
25146
25147       if (CC == X86::COND_NE &&
25148           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
25149         CC = X86::GetOppositeBranchCondition(CC);
25150         std::swap(TrueOp, FalseOp);
25151       }
25152
25153       if (CC == X86::COND_E &&
25154           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
25155         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
25156                           DAG.getConstant(CC, DL, MVT::i8), Cond };
25157         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
25158       }
25159     }
25160   }
25161
25162   // Fold and/or of setcc's to double CMOV:
25163   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
25164   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
25165   //
25166   // This combine lets us generate:
25167   //   cmovcc1 (jcc1 if we don't have CMOV)
25168   //   cmovcc2 (same)
25169   // instead of:
25170   //   setcc1
25171   //   setcc2
25172   //   and/or
25173   //   cmovne (jne if we don't have CMOV)
25174   // When we can't use the CMOV instruction, it might increase branch
25175   // mispredicts.
25176   // When we can use CMOV, or when there is no mispredict, this improves
25177   // throughput and reduces register pressure.
25178   //
25179   if (CC == X86::COND_NE) {
25180     SDValue Flags;
25181     X86::CondCode CC0, CC1;
25182     bool isAndSetCC;
25183     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
25184       if (isAndSetCC) {
25185         std::swap(FalseOp, TrueOp);
25186         CC0 = X86::GetOppositeBranchCondition(CC0);
25187         CC1 = X86::GetOppositeBranchCondition(CC1);
25188       }
25189
25190       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
25191         Flags};
25192       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
25193       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
25194       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25195       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
25196       return CMOV;
25197     }
25198   }
25199
25200   return SDValue();
25201 }
25202
25203 /// PerformMulCombine - Optimize a single multiply with constant into two
25204 /// in order to implement it with two cheaper instructions, e.g.
25205 /// LEA + SHL, LEA + LEA.
25206 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
25207                                  TargetLowering::DAGCombinerInfo &DCI) {
25208   // An imul is usually smaller than the alternative sequence.
25209   if (DAG.getMachineFunction().getFunction()->optForMinSize())
25210     return SDValue();
25211
25212   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
25213     return SDValue();
25214
25215   EVT VT = N->getValueType(0);
25216   if (VT != MVT::i64 && VT != MVT::i32)
25217     return SDValue();
25218
25219   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
25220   if (!C)
25221     return SDValue();
25222   uint64_t MulAmt = C->getZExtValue();
25223   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
25224     return SDValue();
25225
25226   uint64_t MulAmt1 = 0;
25227   uint64_t MulAmt2 = 0;
25228   if ((MulAmt % 9) == 0) {
25229     MulAmt1 = 9;
25230     MulAmt2 = MulAmt / 9;
25231   } else if ((MulAmt % 5) == 0) {
25232     MulAmt1 = 5;
25233     MulAmt2 = MulAmt / 5;
25234   } else if ((MulAmt % 3) == 0) {
25235     MulAmt1 = 3;
25236     MulAmt2 = MulAmt / 3;
25237   }
25238
25239   SDLoc DL(N);
25240   SDValue NewMul;
25241   if (MulAmt2 &&
25242       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
25243
25244     if (isPowerOf2_64(MulAmt2) &&
25245         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
25246       // If second multiplifer is pow2, issue it first. We want the multiply by
25247       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
25248       // is an add.
25249       std::swap(MulAmt1, MulAmt2);
25250
25251     if (isPowerOf2_64(MulAmt1))
25252       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25253                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
25254     else
25255       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
25256                            DAG.getConstant(MulAmt1, DL, VT));
25257
25258     if (isPowerOf2_64(MulAmt2))
25259       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
25260                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
25261     else
25262       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
25263                            DAG.getConstant(MulAmt2, DL, VT));
25264   }
25265
25266   if (!NewMul) {
25267     assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
25268            && "Both cases that could cause potential overflows should have "
25269               "already been handled.");
25270     if (isPowerOf2_64(MulAmt - 1))
25271       // (mul x, 2^N + 1) => (add (shl x, N), x)
25272       NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
25273                                 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25274                                 DAG.getConstant(Log2_64(MulAmt - 1), DL,
25275                                 MVT::i8)));
25276
25277     else if (isPowerOf2_64(MulAmt + 1))
25278       // (mul x, 2^N - 1) => (sub (shl x, N), x)
25279       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
25280                                 N->getOperand(0),
25281                                 DAG.getConstant(Log2_64(MulAmt + 1),
25282                                 DL, MVT::i8)), N->getOperand(0));
25283   }
25284
25285   if (NewMul)
25286     // Do not add new nodes to DAG combiner worklist.
25287     DCI.CombineTo(N, NewMul, false);
25288
25289   return SDValue();
25290 }
25291
25292 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
25293   SDValue N0 = N->getOperand(0);
25294   SDValue N1 = N->getOperand(1);
25295   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
25296   EVT VT = N0.getValueType();
25297
25298   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
25299   // since the result of setcc_c is all zero's or all ones.
25300   if (VT.isInteger() && !VT.isVector() &&
25301       N1C && N0.getOpcode() == ISD::AND &&
25302       N0.getOperand(1).getOpcode() == ISD::Constant) {
25303     SDValue N00 = N0.getOperand(0);
25304     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
25305     APInt ShAmt = N1C->getAPIntValue();
25306     Mask = Mask.shl(ShAmt);
25307     bool MaskOK = false;
25308     // We can handle cases concerning bit-widening nodes containing setcc_c if
25309     // we carefully interrogate the mask to make sure we are semantics
25310     // preserving.
25311     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
25312     // of the underlying setcc_c operation if the setcc_c was zero extended.
25313     // Consider the following example:
25314     //   zext(setcc_c)                 -> i32 0x0000FFFF
25315     //   c1                            -> i32 0x0000FFFF
25316     //   c2                            -> i32 0x00000001
25317     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
25318     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
25319     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25320       MaskOK = true;
25321     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
25322                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25323       MaskOK = true;
25324     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
25325                 N00.getOpcode() == ISD::ANY_EXTEND) &&
25326                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25327       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
25328     }
25329     if (MaskOK && Mask != 0) {
25330       SDLoc DL(N);
25331       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
25332     }
25333   }
25334
25335   // Hardware support for vector shifts is sparse which makes us scalarize the
25336   // vector operations in many cases. Also, on sandybridge ADD is faster than
25337   // shl.
25338   // (shl V, 1) -> add V,V
25339   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
25340     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
25341       assert(N0.getValueType().isVector() && "Invalid vector shift type");
25342       // We shift all of the values by one. In many cases we do not have
25343       // hardware support for this operation. This is better expressed as an ADD
25344       // of two values.
25345       if (N1SplatC->getAPIntValue() == 1)
25346         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
25347     }
25348
25349   return SDValue();
25350 }
25351
25352 static SDValue PerformSRACombine(SDNode *N, SelectionDAG &DAG) {
25353   SDValue N0 = N->getOperand(0);
25354   SDValue N1 = N->getOperand(1);
25355   EVT VT = N0.getValueType();
25356   unsigned Size = VT.getSizeInBits();
25357
25358   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
25359   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
25360   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
25361   // depending on sign of (SarConst - [56,48,32,24,16])
25362
25363   // sexts in X86 are MOVs. The MOVs have the same code size
25364   // as above SHIFTs (only SHIFT on 1 has lower code size).
25365   // However the MOVs have 2 advantages to a SHIFT:
25366   // 1. MOVs can write to a register that differs from source
25367   // 2. MOVs accept memory operands
25368
25369   if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
25370       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
25371       N0.getOperand(1).getOpcode() != ISD::Constant)
25372     return SDValue();
25373
25374   SDValue N00 = N0.getOperand(0);
25375   SDValue N01 = N0.getOperand(1);
25376   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
25377   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
25378   EVT CVT = N1.getValueType();
25379
25380   if (SarConst.isNegative())
25381     return SDValue();
25382
25383   for (MVT SVT : MVT::integer_valuetypes()) {
25384     unsigned ShiftSize = SVT.getSizeInBits();
25385     // skipping types without corresponding sext/zext and
25386     // ShlConst that is not one of [56,48,32,24,16]
25387     if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
25388       continue;
25389     SDLoc DL(N);
25390     SDValue NN =
25391         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
25392     SarConst = SarConst - (Size - ShiftSize);
25393     if (SarConst == 0)
25394       return NN;
25395     else if (SarConst.isNegative())
25396       return DAG.getNode(ISD::SHL, DL, VT, NN,
25397                          DAG.getConstant(-SarConst, DL, CVT));
25398     else
25399       return DAG.getNode(ISD::SRA, DL, VT, NN,
25400                          DAG.getConstant(SarConst, DL, CVT));
25401   }
25402   return SDValue();
25403 }
25404
25405 /// \brief Returns a vector of 0s if the node in input is a vector logical
25406 /// shift by a constant amount which is known to be bigger than or equal
25407 /// to the vector element size in bits.
25408 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
25409                                       const X86Subtarget *Subtarget) {
25410   EVT VT = N->getValueType(0);
25411
25412   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
25413       (!Subtarget->hasInt256() ||
25414        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
25415     return SDValue();
25416
25417   SDValue Amt = N->getOperand(1);
25418   SDLoc DL(N);
25419   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
25420     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
25421       APInt ShiftAmt = AmtSplat->getAPIntValue();
25422       unsigned MaxAmount =
25423         VT.getSimpleVT().getVectorElementType().getSizeInBits();
25424
25425       // SSE2/AVX2 logical shifts always return a vector of 0s
25426       // if the shift amount is bigger than or equal to
25427       // the element size. The constant shift amount will be
25428       // encoded as a 8-bit immediate.
25429       if (ShiftAmt.trunc(8).uge(MaxAmount))
25430         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
25431     }
25432
25433   return SDValue();
25434 }
25435
25436 /// PerformShiftCombine - Combine shifts.
25437 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
25438                                    TargetLowering::DAGCombinerInfo &DCI,
25439                                    const X86Subtarget *Subtarget) {
25440   if (N->getOpcode() == ISD::SHL)
25441     if (SDValue V = PerformSHLCombine(N, DAG))
25442       return V;
25443
25444   if (N->getOpcode() == ISD::SRA)
25445     if (SDValue V = PerformSRACombine(N, DAG))
25446       return V;
25447
25448   // Try to fold this logical shift into a zero vector.
25449   if (N->getOpcode() != ISD::SRA)
25450     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
25451       return V;
25452
25453   return SDValue();
25454 }
25455
25456 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
25457 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
25458 // and friends.  Likewise for OR -> CMPNEQSS.
25459 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
25460                             TargetLowering::DAGCombinerInfo &DCI,
25461                             const X86Subtarget *Subtarget) {
25462   unsigned opcode;
25463
25464   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
25465   // we're requiring SSE2 for both.
25466   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
25467     SDValue N0 = N->getOperand(0);
25468     SDValue N1 = N->getOperand(1);
25469     SDValue CMP0 = N0->getOperand(1);
25470     SDValue CMP1 = N1->getOperand(1);
25471     SDLoc DL(N);
25472
25473     // The SETCCs should both refer to the same CMP.
25474     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
25475       return SDValue();
25476
25477     SDValue CMP00 = CMP0->getOperand(0);
25478     SDValue CMP01 = CMP0->getOperand(1);
25479     EVT     VT    = CMP00.getValueType();
25480
25481     if (VT == MVT::f32 || VT == MVT::f64) {
25482       bool ExpectingFlags = false;
25483       // Check for any users that want flags:
25484       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
25485            !ExpectingFlags && UI != UE; ++UI)
25486         switch (UI->getOpcode()) {
25487         default:
25488         case ISD::BR_CC:
25489         case ISD::BRCOND:
25490         case ISD::SELECT:
25491           ExpectingFlags = true;
25492           break;
25493         case ISD::CopyToReg:
25494         case ISD::SIGN_EXTEND:
25495         case ISD::ZERO_EXTEND:
25496         case ISD::ANY_EXTEND:
25497           break;
25498         }
25499
25500       if (!ExpectingFlags) {
25501         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
25502         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
25503
25504         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
25505           X86::CondCode tmp = cc0;
25506           cc0 = cc1;
25507           cc1 = tmp;
25508         }
25509
25510         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
25511             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
25512           // FIXME: need symbolic constants for these magic numbers.
25513           // See X86ATTInstPrinter.cpp:printSSECC().
25514           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
25515           if (Subtarget->hasAVX512()) {
25516             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
25517                                          CMP01,
25518                                          DAG.getConstant(x86cc, DL, MVT::i8));
25519             if (N->getValueType(0) != MVT::i1)
25520               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25521                                  FSetCC);
25522             return FSetCC;
25523           }
25524           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25525                                               CMP00.getValueType(), CMP00, CMP01,
25526                                               DAG.getConstant(x86cc, DL,
25527                                                               MVT::i8));
25528
25529           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25530           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25531
25532           if (is64BitFP && !Subtarget->is64Bit()) {
25533             // On a 32-bit target, we cannot bitcast the 64-bit float to a
25534             // 64-bit integer, since that's not a legal type. Since
25535             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25536             // bits, but can do this little dance to extract the lowest 32 bits
25537             // and work with those going forward.
25538             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25539                                            OnesOrZeroesF);
25540             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25541             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25542                                         Vector32, DAG.getIntPtrConstant(0, DL));
25543             IntVT = MVT::i32;
25544           }
25545
25546           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25547           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25548                                       DAG.getConstant(1, DL, IntVT));
25549           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25550                                               ANDed);
25551           return OneBitOfTruth;
25552         }
25553       }
25554     }
25555   }
25556   return SDValue();
25557 }
25558
25559 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25560 /// so it can be folded inside ANDNP.
25561 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25562   EVT VT = N->getValueType(0);
25563
25564   // Match direct AllOnes for 128 and 256-bit vectors
25565   if (ISD::isBuildVectorAllOnes(N))
25566     return true;
25567
25568   // Look through a bit convert.
25569   if (N->getOpcode() == ISD::BITCAST)
25570     N = N->getOperand(0).getNode();
25571
25572   // Sometimes the operand may come from a insert_subvector building a 256-bit
25573   // allones vector
25574   if (VT.is256BitVector() &&
25575       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25576     SDValue V1 = N->getOperand(0);
25577     SDValue V2 = N->getOperand(1);
25578
25579     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25580         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25581         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25582         ISD::isBuildVectorAllOnes(V2.getNode()))
25583       return true;
25584   }
25585
25586   return false;
25587 }
25588
25589 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25590 // register. In most cases we actually compare or select YMM-sized registers
25591 // and mixing the two types creates horrible code. This method optimizes
25592 // some of the transition sequences.
25593 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25594                                  TargetLowering::DAGCombinerInfo &DCI,
25595                                  const X86Subtarget *Subtarget) {
25596   EVT VT = N->getValueType(0);
25597   if (!VT.is256BitVector())
25598     return SDValue();
25599
25600   assert((N->getOpcode() == ISD::ANY_EXTEND ||
25601           N->getOpcode() == ISD::ZERO_EXTEND ||
25602           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25603
25604   SDValue Narrow = N->getOperand(0);
25605   EVT NarrowVT = Narrow->getValueType(0);
25606   if (!NarrowVT.is128BitVector())
25607     return SDValue();
25608
25609   if (Narrow->getOpcode() != ISD::XOR &&
25610       Narrow->getOpcode() != ISD::AND &&
25611       Narrow->getOpcode() != ISD::OR)
25612     return SDValue();
25613
25614   SDValue N0  = Narrow->getOperand(0);
25615   SDValue N1  = Narrow->getOperand(1);
25616   SDLoc DL(Narrow);
25617
25618   // The Left side has to be a trunc.
25619   if (N0.getOpcode() != ISD::TRUNCATE)
25620     return SDValue();
25621
25622   // The type of the truncated inputs.
25623   EVT WideVT = N0->getOperand(0)->getValueType(0);
25624   if (WideVT != VT)
25625     return SDValue();
25626
25627   // The right side has to be a 'trunc' or a constant vector.
25628   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25629   ConstantSDNode *RHSConstSplat = nullptr;
25630   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25631     RHSConstSplat = RHSBV->getConstantSplatNode();
25632   if (!RHSTrunc && !RHSConstSplat)
25633     return SDValue();
25634
25635   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25636
25637   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25638     return SDValue();
25639
25640   // Set N0 and N1 to hold the inputs to the new wide operation.
25641   N0 = N0->getOperand(0);
25642   if (RHSConstSplat) {
25643     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25644                      SDValue(RHSConstSplat, 0));
25645     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25646     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25647   } else if (RHSTrunc) {
25648     N1 = N1->getOperand(0);
25649   }
25650
25651   // Generate the wide operation.
25652   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25653   unsigned Opcode = N->getOpcode();
25654   switch (Opcode) {
25655   case ISD::ANY_EXTEND:
25656     return Op;
25657   case ISD::ZERO_EXTEND: {
25658     unsigned InBits = NarrowVT.getScalarSizeInBits();
25659     APInt Mask = APInt::getAllOnesValue(InBits);
25660     Mask = Mask.zext(VT.getScalarSizeInBits());
25661     return DAG.getNode(ISD::AND, DL, VT,
25662                        Op, DAG.getConstant(Mask, DL, VT));
25663   }
25664   case ISD::SIGN_EXTEND:
25665     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25666                        Op, DAG.getValueType(NarrowVT));
25667   default:
25668     llvm_unreachable("Unexpected opcode");
25669   }
25670 }
25671
25672 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25673                                  TargetLowering::DAGCombinerInfo &DCI,
25674                                  const X86Subtarget *Subtarget) {
25675   SDValue N0 = N->getOperand(0);
25676   SDValue N1 = N->getOperand(1);
25677   SDLoc DL(N);
25678
25679   // A vector zext_in_reg may be represented as a shuffle,
25680   // feeding into a bitcast (this represents anyext) feeding into
25681   // an and with a mask.
25682   // We'd like to try to combine that into a shuffle with zero
25683   // plus a bitcast, removing the and.
25684   if (N0.getOpcode() != ISD::BITCAST ||
25685       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25686     return SDValue();
25687
25688   // The other side of the AND should be a splat of 2^C, where C
25689   // is the number of bits in the source type.
25690   if (N1.getOpcode() == ISD::BITCAST)
25691     N1 = N1.getOperand(0);
25692   if (N1.getOpcode() != ISD::BUILD_VECTOR)
25693     return SDValue();
25694   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25695
25696   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25697   EVT SrcType = Shuffle->getValueType(0);
25698
25699   // We expect a single-source shuffle
25700   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25701     return SDValue();
25702
25703   unsigned SrcSize = SrcType.getScalarSizeInBits();
25704
25705   APInt SplatValue, SplatUndef;
25706   unsigned SplatBitSize;
25707   bool HasAnyUndefs;
25708   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25709                                 SplatBitSize, HasAnyUndefs))
25710     return SDValue();
25711
25712   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25713   // Make sure the splat matches the mask we expect
25714   if (SplatBitSize > ResSize ||
25715       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25716     return SDValue();
25717
25718   // Make sure the input and output size make sense
25719   if (SrcSize >= ResSize || ResSize % SrcSize)
25720     return SDValue();
25721
25722   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25723   // The number of u's between each two values depends on the ratio between
25724   // the source and dest type.
25725   unsigned ZextRatio = ResSize / SrcSize;
25726   bool IsZext = true;
25727   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25728     if (i % ZextRatio) {
25729       if (Shuffle->getMaskElt(i) > 0) {
25730         // Expected undef
25731         IsZext = false;
25732         break;
25733       }
25734     } else {
25735       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25736         // Expected element number
25737         IsZext = false;
25738         break;
25739       }
25740     }
25741   }
25742
25743   if (!IsZext)
25744     return SDValue();
25745
25746   // Ok, perform the transformation - replace the shuffle with
25747   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25748   // (instead of undef) where the k elements come from the zero vector.
25749   SmallVector<int, 8> Mask;
25750   unsigned NumElems = SrcType.getVectorNumElements();
25751   for (unsigned i = 0; i < NumElems; ++i)
25752     if (i % ZextRatio)
25753       Mask.push_back(NumElems);
25754     else
25755       Mask.push_back(i / ZextRatio);
25756
25757   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25758     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25759   return DAG.getBitcast(N0.getValueType(), NewShuffle);
25760 }
25761
25762 /// If both input operands of a logic op are being cast from floating point
25763 /// types, try to convert this into a floating point logic node to avoid
25764 /// unnecessary moves from SSE to integer registers.
25765 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25766                                         const X86Subtarget *Subtarget) {
25767   unsigned FPOpcode = ISD::DELETED_NODE;
25768   if (N->getOpcode() == ISD::AND)
25769     FPOpcode = X86ISD::FAND;
25770   else if (N->getOpcode() == ISD::OR)
25771     FPOpcode = X86ISD::FOR;
25772   else if (N->getOpcode() == ISD::XOR)
25773     FPOpcode = X86ISD::FXOR;
25774
25775   assert(FPOpcode != ISD::DELETED_NODE &&
25776          "Unexpected input node for FP logic conversion");
25777
25778   EVT VT = N->getValueType(0);
25779   SDValue N0 = N->getOperand(0);
25780   SDValue N1 = N->getOperand(1);
25781   SDLoc DL(N);
25782   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25783       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25784        (Subtarget->hasSSE2() && VT == MVT::i64))) {
25785     SDValue N00 = N0.getOperand(0);
25786     SDValue N10 = N1.getOperand(0);
25787     EVT N00Type = N00.getValueType();
25788     EVT N10Type = N10.getValueType();
25789     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25790       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25791       return DAG.getBitcast(VT, FPLogic);
25792     }
25793   }
25794   return SDValue();
25795 }
25796
25797 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25798                                  TargetLowering::DAGCombinerInfo &DCI,
25799                                  const X86Subtarget *Subtarget) {
25800   if (DCI.isBeforeLegalizeOps())
25801     return SDValue();
25802
25803   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25804     return Zext;
25805
25806   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25807     return R;
25808
25809   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25810     return FPLogic;
25811
25812   EVT VT = N->getValueType(0);
25813   SDValue N0 = N->getOperand(0);
25814   SDValue N1 = N->getOperand(1);
25815   SDLoc DL(N);
25816
25817   // Create BEXTR instructions
25818   // BEXTR is ((X >> imm) & (2**size-1))
25819   if (VT == MVT::i32 || VT == MVT::i64) {
25820     // Check for BEXTR.
25821     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25822         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25823       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25824       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25825       if (MaskNode && ShiftNode) {
25826         uint64_t Mask = MaskNode->getZExtValue();
25827         uint64_t Shift = ShiftNode->getZExtValue();
25828         if (isMask_64(Mask)) {
25829           uint64_t MaskSize = countPopulation(Mask);
25830           if (Shift + MaskSize <= VT.getSizeInBits())
25831             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25832                                DAG.getConstant(Shift | (MaskSize << 8), DL,
25833                                                VT));
25834         }
25835       }
25836     } // BEXTR
25837
25838     return SDValue();
25839   }
25840
25841   // Want to form ANDNP nodes:
25842   // 1) In the hopes of then easily combining them with OR and AND nodes
25843   //    to form PBLEND/PSIGN.
25844   // 2) To match ANDN packed intrinsics
25845   if (VT != MVT::v2i64 && VT != MVT::v4i64)
25846     return SDValue();
25847
25848   // Check LHS for vnot
25849   if (N0.getOpcode() == ISD::XOR &&
25850       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25851       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25852     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25853
25854   // Check RHS for vnot
25855   if (N1.getOpcode() == ISD::XOR &&
25856       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25857       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25858     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25859
25860   return SDValue();
25861 }
25862
25863 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25864                                 TargetLowering::DAGCombinerInfo &DCI,
25865                                 const X86Subtarget *Subtarget) {
25866   if (DCI.isBeforeLegalizeOps())
25867     return SDValue();
25868
25869   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25870     return R;
25871
25872   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25873     return FPLogic;
25874
25875   SDValue N0 = N->getOperand(0);
25876   SDValue N1 = N->getOperand(1);
25877   EVT VT = N->getValueType(0);
25878
25879   // look for psign/blend
25880   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25881     if (!Subtarget->hasSSSE3() ||
25882         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25883       return SDValue();
25884
25885     // Canonicalize pandn to RHS
25886     if (N0.getOpcode() == X86ISD::ANDNP)
25887       std::swap(N0, N1);
25888     // or (and (m, y), (pandn m, x))
25889     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25890       SDValue Mask = N1.getOperand(0);
25891       SDValue X    = N1.getOperand(1);
25892       SDValue Y;
25893       if (N0.getOperand(0) == Mask)
25894         Y = N0.getOperand(1);
25895       if (N0.getOperand(1) == Mask)
25896         Y = N0.getOperand(0);
25897
25898       // Check to see if the mask appeared in both the AND and ANDNP and
25899       if (!Y.getNode())
25900         return SDValue();
25901
25902       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25903       // Look through mask bitcast.
25904       if (Mask.getOpcode() == ISD::BITCAST)
25905         Mask = Mask.getOperand(0);
25906       if (X.getOpcode() == ISD::BITCAST)
25907         X = X.getOperand(0);
25908       if (Y.getOpcode() == ISD::BITCAST)
25909         Y = Y.getOperand(0);
25910
25911       EVT MaskVT = Mask.getValueType();
25912
25913       // Validate that the Mask operand is a vector sra node.
25914       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25915       // there is no psrai.b
25916       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25917       unsigned SraAmt = ~0;
25918       if (Mask.getOpcode() == ISD::SRA) {
25919         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25920           if (auto *AmtConst = AmtBV->getConstantSplatNode())
25921             SraAmt = AmtConst->getZExtValue();
25922       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25923         SDValue SraC = Mask.getOperand(1);
25924         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
25925       }
25926       if ((SraAmt + 1) != EltBits)
25927         return SDValue();
25928
25929       SDLoc DL(N);
25930
25931       // Now we know we at least have a plendvb with the mask val.  See if
25932       // we can form a psignb/w/d.
25933       // psign = x.type == y.type == mask.type && y = sub(0, x);
25934       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25935           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25936           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25937         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25938                "Unsupported VT for PSIGN");
25939         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25940         return DAG.getBitcast(VT, Mask);
25941       }
25942       // PBLENDVB only available on SSE 4.1
25943       if (!Subtarget->hasSSE41())
25944         return SDValue();
25945
25946       MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25947
25948       X = DAG.getBitcast(BlendVT, X);
25949       Y = DAG.getBitcast(BlendVT, Y);
25950       Mask = DAG.getBitcast(BlendVT, Mask);
25951       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25952       return DAG.getBitcast(VT, Mask);
25953     }
25954   }
25955
25956   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25957     return SDValue();
25958
25959   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25960   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25961
25962   // SHLD/SHRD instructions have lower register pressure, but on some
25963   // platforms they have higher latency than the equivalent
25964   // series of shifts/or that would otherwise be generated.
25965   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25966   // have higher latencies and we are not optimizing for size.
25967   if (!OptForSize && Subtarget->isSHLDSlow())
25968     return SDValue();
25969
25970   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25971     std::swap(N0, N1);
25972   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25973     return SDValue();
25974   if (!N0.hasOneUse() || !N1.hasOneUse())
25975     return SDValue();
25976
25977   SDValue ShAmt0 = N0.getOperand(1);
25978   if (ShAmt0.getValueType() != MVT::i8)
25979     return SDValue();
25980   SDValue ShAmt1 = N1.getOperand(1);
25981   if (ShAmt1.getValueType() != MVT::i8)
25982     return SDValue();
25983   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25984     ShAmt0 = ShAmt0.getOperand(0);
25985   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25986     ShAmt1 = ShAmt1.getOperand(0);
25987
25988   SDLoc DL(N);
25989   unsigned Opc = X86ISD::SHLD;
25990   SDValue Op0 = N0.getOperand(0);
25991   SDValue Op1 = N1.getOperand(0);
25992   if (ShAmt0.getOpcode() == ISD::SUB) {
25993     Opc = X86ISD::SHRD;
25994     std::swap(Op0, Op1);
25995     std::swap(ShAmt0, ShAmt1);
25996   }
25997
25998   unsigned Bits = VT.getSizeInBits();
25999   if (ShAmt1.getOpcode() == ISD::SUB) {
26000     SDValue Sum = ShAmt1.getOperand(0);
26001     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
26002       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
26003       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
26004         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
26005       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
26006         return DAG.getNode(Opc, DL, VT,
26007                            Op0, Op1,
26008                            DAG.getNode(ISD::TRUNCATE, DL,
26009                                        MVT::i8, ShAmt0));
26010     }
26011   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
26012     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
26013     if (ShAmt0C &&
26014         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
26015       return DAG.getNode(Opc, DL, VT,
26016                          N0.getOperand(0), N1.getOperand(0),
26017                          DAG.getNode(ISD::TRUNCATE, DL,
26018                                        MVT::i8, ShAmt0));
26019   }
26020
26021   return SDValue();
26022 }
26023
26024 // Generate NEG and CMOV for integer abs.
26025 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
26026   EVT VT = N->getValueType(0);
26027
26028   // Since X86 does not have CMOV for 8-bit integer, we don't convert
26029   // 8-bit integer abs to NEG and CMOV.
26030   if (VT.isInteger() && VT.getSizeInBits() == 8)
26031     return SDValue();
26032
26033   SDValue N0 = N->getOperand(0);
26034   SDValue N1 = N->getOperand(1);
26035   SDLoc DL(N);
26036
26037   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
26038   // and change it to SUB and CMOV.
26039   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
26040       N0.getOpcode() == ISD::ADD &&
26041       N0.getOperand(1) == N1 &&
26042       N1.getOpcode() == ISD::SRA &&
26043       N1.getOperand(0) == N0.getOperand(0))
26044     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
26045       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
26046         // Generate SUB & CMOV.
26047         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
26048                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
26049
26050         SDValue Ops[] = { N0.getOperand(0), Neg,
26051                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
26052                           SDValue(Neg.getNode(), 1) };
26053         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
26054       }
26055   return SDValue();
26056 }
26057
26058 // Try to turn tests against the signbit in the form of:
26059 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
26060 // into:
26061 //   SETGT(X, -1)
26062 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
26063   // This is only worth doing if the output type is i8.
26064   if (N->getValueType(0) != MVT::i8)
26065     return SDValue();
26066
26067   SDValue N0 = N->getOperand(0);
26068   SDValue N1 = N->getOperand(1);
26069
26070   // We should be performing an xor against a truncated shift.
26071   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
26072     return SDValue();
26073
26074   // Make sure we are performing an xor against one.
26075   if (!isOneConstant(N1))
26076     return SDValue();
26077
26078   // SetCC on x86 zero extends so only act on this if it's a logical shift.
26079   SDValue Shift = N0.getOperand(0);
26080   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
26081     return SDValue();
26082
26083   // Make sure we are truncating from one of i16, i32 or i64.
26084   EVT ShiftTy = Shift.getValueType();
26085   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
26086     return SDValue();
26087
26088   // Make sure the shift amount extracts the sign bit.
26089   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
26090       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
26091     return SDValue();
26092
26093   // Create a greater-than comparison against -1.
26094   // N.B. Using SETGE against 0 works but we want a canonical looking
26095   // comparison, using SETGT matches up with what TranslateX86CC.
26096   SDLoc DL(N);
26097   SDValue ShiftOp = Shift.getOperand(0);
26098   EVT ShiftOpTy = ShiftOp.getValueType();
26099   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
26100                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
26101   return Cond;
26102 }
26103
26104 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
26105                                  TargetLowering::DAGCombinerInfo &DCI,
26106                                  const X86Subtarget *Subtarget) {
26107   if (DCI.isBeforeLegalizeOps())
26108     return SDValue();
26109
26110   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
26111     return RV;
26112
26113   if (Subtarget->hasCMov())
26114     if (SDValue RV = performIntegerAbsCombine(N, DAG))
26115       return RV;
26116
26117   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
26118     return FPLogic;
26119
26120   return SDValue();
26121 }
26122
26123 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
26124 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
26125 /// X86ISD::AVG instruction.
26126 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
26127                                 const X86Subtarget *Subtarget, SDLoc DL) {
26128   if (!VT.isVector() || !VT.isSimple())
26129     return SDValue();
26130   EVT InVT = In.getValueType();
26131   unsigned NumElems = VT.getVectorNumElements();
26132
26133   EVT ScalarVT = VT.getVectorElementType();
26134   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
26135         isPowerOf2_32(NumElems)))
26136     return SDValue();
26137
26138   // InScalarVT is the intermediate type in AVG pattern and it should be greater
26139   // than the original input type (i8/i16).
26140   EVT InScalarVT = InVT.getVectorElementType();
26141   if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
26142     return SDValue();
26143
26144   if (Subtarget->hasAVX512()) {
26145     if (VT.getSizeInBits() > 512)
26146       return SDValue();
26147   } else if (Subtarget->hasAVX2()) {
26148     if (VT.getSizeInBits() > 256)
26149       return SDValue();
26150   } else {
26151     if (VT.getSizeInBits() > 128)
26152       return SDValue();
26153   }
26154
26155   // Detect the following pattern:
26156   //
26157   //   %1 = zext <N x i8> %a to <N x i32>
26158   //   %2 = zext <N x i8> %b to <N x i32>
26159   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
26160   //   %4 = add nuw nsw <N x i32> %3, %2
26161   //   %5 = lshr <N x i32> %N, <i32 1 x N>
26162   //   %6 = trunc <N x i32> %5 to <N x i8>
26163   //
26164   // In AVX512, the last instruction can also be a trunc store.
26165
26166   if (In.getOpcode() != ISD::SRL)
26167     return SDValue();
26168
26169   // A lambda checking the given SDValue is a constant vector and each element
26170   // is in the range [Min, Max].
26171   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
26172     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
26173     if (!BV || !BV->isConstant())
26174       return false;
26175     for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
26176       ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
26177       if (!C)
26178         return false;
26179       uint64_t Val = C->getZExtValue();
26180       if (Val < Min || Val > Max)
26181         return false;
26182     }
26183     return true;
26184   };
26185
26186   // Check if each element of the vector is left-shifted by one.
26187   auto LHS = In.getOperand(0);
26188   auto RHS = In.getOperand(1);
26189   if (!IsConstVectorInRange(RHS, 1, 1))
26190     return SDValue();
26191   if (LHS.getOpcode() != ISD::ADD)
26192     return SDValue();
26193
26194   // Detect a pattern of a + b + 1 where the order doesn't matter.
26195   SDValue Operands[3];
26196   Operands[0] = LHS.getOperand(0);
26197   Operands[1] = LHS.getOperand(1);
26198
26199   // Take care of the case when one of the operands is a constant vector whose
26200   // element is in the range [1, 256].
26201   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
26202       Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
26203       Operands[0].getOperand(0).getValueType() == VT) {
26204     // The pattern is detected. Subtract one from the constant vector, then
26205     // demote it and emit X86ISD::AVG instruction.
26206     SDValue One = DAG.getConstant(1, DL, InScalarVT);
26207     SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
26208                                SmallVector<SDValue, 8>(NumElems, One));
26209     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
26210     Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
26211     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26212                        Operands[1]);
26213   }
26214
26215   if (Operands[0].getOpcode() == ISD::ADD)
26216     std::swap(Operands[0], Operands[1]);
26217   else if (Operands[1].getOpcode() != ISD::ADD)
26218     return SDValue();
26219   Operands[2] = Operands[1].getOperand(0);
26220   Operands[1] = Operands[1].getOperand(1);
26221
26222   // Now we have three operands of two additions. Check that one of them is a
26223   // constant vector with ones, and the other two are promoted from i8/i16.
26224   for (int i = 0; i < 3; ++i) {
26225     if (!IsConstVectorInRange(Operands[i], 1, 1))
26226       continue;
26227     std::swap(Operands[i], Operands[2]);
26228
26229     // Check if Operands[0] and Operands[1] are results of type promotion.
26230     for (int j = 0; j < 2; ++j)
26231       if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
26232           Operands[j].getOperand(0).getValueType() != VT)
26233         return SDValue();
26234
26235     // The pattern is detected, emit X86ISD::AVG instruction.
26236     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26237                        Operands[1].getOperand(0));
26238   }
26239
26240   return SDValue();
26241 }
26242
26243 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
26244 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
26245                                   TargetLowering::DAGCombinerInfo &DCI,
26246                                   const X86Subtarget *Subtarget) {
26247   LoadSDNode *Ld = cast<LoadSDNode>(N);
26248   EVT RegVT = Ld->getValueType(0);
26249   EVT MemVT = Ld->getMemoryVT();
26250   SDLoc dl(Ld);
26251   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26252
26253   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
26254   // into two 16-byte operations.
26255   ISD::LoadExtType Ext = Ld->getExtensionType();
26256   bool Fast;
26257   unsigned AddressSpace = Ld->getAddressSpace();
26258   unsigned Alignment = Ld->getAlignment();
26259   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
26260       Ext == ISD::NON_EXTLOAD &&
26261       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
26262                              AddressSpace, Alignment, &Fast) && !Fast) {
26263     unsigned NumElems = RegVT.getVectorNumElements();
26264     if (NumElems < 2)
26265       return SDValue();
26266
26267     SDValue Ptr = Ld->getBasePtr();
26268     SDValue Increment =
26269         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26270
26271     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
26272                                   NumElems/2);
26273     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26274                                 Ld->getPointerInfo(), Ld->isVolatile(),
26275                                 Ld->isNonTemporal(), Ld->isInvariant(),
26276                                 Alignment);
26277     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26278     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26279                                 Ld->getPointerInfo(), Ld->isVolatile(),
26280                                 Ld->isNonTemporal(), Ld->isInvariant(),
26281                                 std::min(16U, Alignment));
26282     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
26283                              Load1.getValue(1),
26284                              Load2.getValue(1));
26285
26286     SDValue NewVec = DAG.getUNDEF(RegVT);
26287     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
26288     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
26289     return DCI.CombineTo(N, NewVec, TF, true);
26290   }
26291
26292   return SDValue();
26293 }
26294
26295 /// PerformMLOADCombine - Resolve extending loads
26296 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
26297                                    TargetLowering::DAGCombinerInfo &DCI,
26298                                    const X86Subtarget *Subtarget) {
26299   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
26300   if (Mld->getExtensionType() != ISD::SEXTLOAD)
26301     return SDValue();
26302
26303   EVT VT = Mld->getValueType(0);
26304   unsigned NumElems = VT.getVectorNumElements();
26305   EVT LdVT = Mld->getMemoryVT();
26306   SDLoc dl(Mld);
26307
26308   assert(LdVT != VT && "Cannot extend to the same type");
26309   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
26310   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
26311   // From, To sizes and ElemCount must be pow of two
26312   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26313     "Unexpected size for extending masked load");
26314
26315   unsigned SizeRatio  = ToSz / FromSz;
26316   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
26317
26318   // Create a type on which we perform the shuffle
26319   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26320           LdVT.getScalarType(), NumElems*SizeRatio);
26321   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26322
26323   // Convert Src0 value
26324   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
26325   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
26326     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26327     for (unsigned i = 0; i != NumElems; ++i)
26328       ShuffleVec[i] = i * SizeRatio;
26329
26330     // Can't shuffle using an illegal type.
26331     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26332            "WideVecVT should be legal");
26333     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
26334                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
26335   }
26336   // Prepare the new mask
26337   SDValue NewMask;
26338   SDValue Mask = Mld->getMask();
26339   if (Mask.getValueType() == VT) {
26340     // Mask and original value have the same type
26341     NewMask = DAG.getBitcast(WideVecVT, Mask);
26342     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26343     for (unsigned i = 0; i != NumElems; ++i)
26344       ShuffleVec[i] = i * SizeRatio;
26345     for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
26346       ShuffleVec[i] = NumElems * SizeRatio;
26347     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26348                                    DAG.getConstant(0, dl, WideVecVT),
26349                                    &ShuffleVec[0]);
26350   }
26351   else {
26352     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26353     unsigned WidenNumElts = NumElems*SizeRatio;
26354     unsigned MaskNumElts = VT.getVectorNumElements();
26355     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26356                                      WidenNumElts);
26357
26358     unsigned NumConcat = WidenNumElts / MaskNumElts;
26359     SmallVector<SDValue, 16> Ops(NumConcat);
26360     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26361     Ops[0] = Mask;
26362     for (unsigned i = 1; i != NumConcat; ++i)
26363       Ops[i] = ZeroVal;
26364
26365     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26366   }
26367
26368   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
26369                                      Mld->getBasePtr(), NewMask, WideSrc0,
26370                                      Mld->getMemoryVT(), Mld->getMemOperand(),
26371                                      ISD::NON_EXTLOAD);
26372   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
26373   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
26374 }
26375 /// PerformMSTORECombine - Resolve truncating stores
26376 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
26377                                     const X86Subtarget *Subtarget) {
26378   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
26379   if (!Mst->isTruncatingStore())
26380     return SDValue();
26381
26382   EVT VT = Mst->getValue().getValueType();
26383   unsigned NumElems = VT.getVectorNumElements();
26384   EVT StVT = Mst->getMemoryVT();
26385   SDLoc dl(Mst);
26386
26387   assert(StVT != VT && "Cannot truncate to the same type");
26388   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26389   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26390
26391   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26392
26393   // The truncating store is legal in some cases. For example
26394   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26395   // are designated for truncate store.
26396   // In this case we don't need any further transformations.
26397   if (TLI.isTruncStoreLegal(VT, StVT))
26398     return SDValue();
26399
26400   // From, To sizes and ElemCount must be pow of two
26401   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26402     "Unexpected size for truncating masked store");
26403   // We are going to use the original vector elt for storing.
26404   // Accumulated smaller vector elements must be a multiple of the store size.
26405   assert (((NumElems * FromSz) % ToSz) == 0 &&
26406           "Unexpected ratio for truncating masked store");
26407
26408   unsigned SizeRatio  = FromSz / ToSz;
26409   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26410
26411   // Create a type on which we perform the shuffle
26412   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26413           StVT.getScalarType(), NumElems*SizeRatio);
26414
26415   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26416
26417   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
26418   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26419   for (unsigned i = 0; i != NumElems; ++i)
26420     ShuffleVec[i] = i * SizeRatio;
26421
26422   // Can't shuffle using an illegal type.
26423   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26424          "WideVecVT should be legal");
26425
26426   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26427                                               DAG.getUNDEF(WideVecVT),
26428                                               &ShuffleVec[0]);
26429
26430   SDValue NewMask;
26431   SDValue Mask = Mst->getMask();
26432   if (Mask.getValueType() == VT) {
26433     // Mask and original value have the same type
26434     NewMask = DAG.getBitcast(WideVecVT, Mask);
26435     for (unsigned i = 0; i != NumElems; ++i)
26436       ShuffleVec[i] = i * SizeRatio;
26437     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
26438       ShuffleVec[i] = NumElems*SizeRatio;
26439     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26440                                    DAG.getConstant(0, dl, WideVecVT),
26441                                    &ShuffleVec[0]);
26442   }
26443   else {
26444     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26445     unsigned WidenNumElts = NumElems*SizeRatio;
26446     unsigned MaskNumElts = VT.getVectorNumElements();
26447     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26448                                      WidenNumElts);
26449
26450     unsigned NumConcat = WidenNumElts / MaskNumElts;
26451     SmallVector<SDValue, 16> Ops(NumConcat);
26452     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26453     Ops[0] = Mask;
26454     for (unsigned i = 1; i != NumConcat; ++i)
26455       Ops[i] = ZeroVal;
26456
26457     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26458   }
26459
26460   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
26461                             Mst->getBasePtr(), NewMask, StVT,
26462                             Mst->getMemOperand(), false);
26463 }
26464 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
26465 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
26466                                    const X86Subtarget *Subtarget) {
26467   StoreSDNode *St = cast<StoreSDNode>(N);
26468   EVT VT = St->getValue().getValueType();
26469   EVT StVT = St->getMemoryVT();
26470   SDLoc dl(St);
26471   SDValue StoredVal = St->getOperand(1);
26472   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26473
26474   // If we are saving a concatenation of two XMM registers and 32-byte stores
26475   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
26476   bool Fast;
26477   unsigned AddressSpace = St->getAddressSpace();
26478   unsigned Alignment = St->getAlignment();
26479   if (VT.is256BitVector() && StVT == VT &&
26480       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
26481                              AddressSpace, Alignment, &Fast) && !Fast) {
26482     unsigned NumElems = VT.getVectorNumElements();
26483     if (NumElems < 2)
26484       return SDValue();
26485
26486     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
26487     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
26488
26489     SDValue Stride =
26490         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26491     SDValue Ptr0 = St->getBasePtr();
26492     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
26493
26494     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
26495                                 St->getPointerInfo(), St->isVolatile(),
26496                                 St->isNonTemporal(), Alignment);
26497     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
26498                                 St->getPointerInfo(), St->isVolatile(),
26499                                 St->isNonTemporal(),
26500                                 std::min(16U, Alignment));
26501     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
26502   }
26503
26504   // Optimize trunc store (of multiple scalars) to shuffle and store.
26505   // First, pack all of the elements in one place. Next, store to memory
26506   // in fewer chunks.
26507   if (St->isTruncatingStore() && VT.isVector()) {
26508     // Check if we can detect an AVG pattern from the truncation. If yes,
26509     // replace the trunc store by a normal store with the result of X86ISD::AVG
26510     // instruction.
26511     SDValue Avg =
26512         detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
26513     if (Avg.getNode())
26514       return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
26515                           St->getPointerInfo(), St->isVolatile(),
26516                           St->isNonTemporal(), St->getAlignment());
26517
26518     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26519     unsigned NumElems = VT.getVectorNumElements();
26520     assert(StVT != VT && "Cannot truncate to the same type");
26521     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26522     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26523
26524     // The truncating store is legal in some cases. For example
26525     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26526     // are designated for truncate store.
26527     // In this case we don't need any further transformations.
26528     if (TLI.isTruncStoreLegal(VT, StVT))
26529       return SDValue();
26530
26531     // From, To sizes and ElemCount must be pow of two
26532     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26533     // We are going to use the original vector elt for storing.
26534     // Accumulated smaller vector elements must be a multiple of the store size.
26535     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26536
26537     unsigned SizeRatio  = FromSz / ToSz;
26538
26539     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26540
26541     // Create a type on which we perform the shuffle
26542     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26543             StVT.getScalarType(), NumElems*SizeRatio);
26544
26545     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26546
26547     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26548     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26549     for (unsigned i = 0; i != NumElems; ++i)
26550       ShuffleVec[i] = i * SizeRatio;
26551
26552     // Can't shuffle using an illegal type.
26553     if (!TLI.isTypeLegal(WideVecVT))
26554       return SDValue();
26555
26556     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26557                                          DAG.getUNDEF(WideVecVT),
26558                                          &ShuffleVec[0]);
26559     // At this point all of the data is stored at the bottom of the
26560     // register. We now need to save it to mem.
26561
26562     // Find the largest store unit
26563     MVT StoreType = MVT::i8;
26564     for (MVT Tp : MVT::integer_valuetypes()) {
26565       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26566         StoreType = Tp;
26567     }
26568
26569     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26570     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26571         (64 <= NumElems * ToSz))
26572       StoreType = MVT::f64;
26573
26574     // Bitcast the original vector into a vector of store-size units
26575     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26576             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26577     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26578     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26579     SmallVector<SDValue, 8> Chains;
26580     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26581                                         TLI.getPointerTy(DAG.getDataLayout()));
26582     SDValue Ptr = St->getBasePtr();
26583
26584     // Perform one or more big stores into memory.
26585     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26586       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26587                                    StoreType, ShuffWide,
26588                                    DAG.getIntPtrConstant(i, dl));
26589       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26590                                 St->getPointerInfo(), St->isVolatile(),
26591                                 St->isNonTemporal(), St->getAlignment());
26592       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26593       Chains.push_back(Ch);
26594     }
26595
26596     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26597   }
26598
26599   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
26600   // the FP state in cases where an emms may be missing.
26601   // A preferable solution to the general problem is to figure out the right
26602   // places to insert EMMS.  This qualifies as a quick hack.
26603
26604   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26605   if (VT.getSizeInBits() != 64)
26606     return SDValue();
26607
26608   const Function *F = DAG.getMachineFunction().getFunction();
26609   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26610   bool F64IsLegal =
26611       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26612   if ((VT.isVector() ||
26613        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26614       isa<LoadSDNode>(St->getValue()) &&
26615       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26616       St->getChain().hasOneUse() && !St->isVolatile()) {
26617     SDNode* LdVal = St->getValue().getNode();
26618     LoadSDNode *Ld = nullptr;
26619     int TokenFactorIndex = -1;
26620     SmallVector<SDValue, 8> Ops;
26621     SDNode* ChainVal = St->getChain().getNode();
26622     // Must be a store of a load.  We currently handle two cases:  the load
26623     // is a direct child, and it's under an intervening TokenFactor.  It is
26624     // possible to dig deeper under nested TokenFactors.
26625     if (ChainVal == LdVal)
26626       Ld = cast<LoadSDNode>(St->getChain());
26627     else if (St->getValue().hasOneUse() &&
26628              ChainVal->getOpcode() == ISD::TokenFactor) {
26629       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26630         if (ChainVal->getOperand(i).getNode() == LdVal) {
26631           TokenFactorIndex = i;
26632           Ld = cast<LoadSDNode>(St->getValue());
26633         } else
26634           Ops.push_back(ChainVal->getOperand(i));
26635       }
26636     }
26637
26638     if (!Ld || !ISD::isNormalLoad(Ld))
26639       return SDValue();
26640
26641     // If this is not the MMX case, i.e. we are just turning i64 load/store
26642     // into f64 load/store, avoid the transformation if there are multiple
26643     // uses of the loaded value.
26644     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26645       return SDValue();
26646
26647     SDLoc LdDL(Ld);
26648     SDLoc StDL(N);
26649     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26650     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26651     // pair instead.
26652     if (Subtarget->is64Bit() || F64IsLegal) {
26653       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26654       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26655                                   Ld->getPointerInfo(), Ld->isVolatile(),
26656                                   Ld->isNonTemporal(), Ld->isInvariant(),
26657                                   Ld->getAlignment());
26658       SDValue NewChain = NewLd.getValue(1);
26659       if (TokenFactorIndex != -1) {
26660         Ops.push_back(NewChain);
26661         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26662       }
26663       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26664                           St->getPointerInfo(),
26665                           St->isVolatile(), St->isNonTemporal(),
26666                           St->getAlignment());
26667     }
26668
26669     // Otherwise, lower to two pairs of 32-bit loads / stores.
26670     SDValue LoAddr = Ld->getBasePtr();
26671     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26672                                  DAG.getConstant(4, LdDL, MVT::i32));
26673
26674     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26675                                Ld->getPointerInfo(),
26676                                Ld->isVolatile(), Ld->isNonTemporal(),
26677                                Ld->isInvariant(), Ld->getAlignment());
26678     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26679                                Ld->getPointerInfo().getWithOffset(4),
26680                                Ld->isVolatile(), Ld->isNonTemporal(),
26681                                Ld->isInvariant(),
26682                                MinAlign(Ld->getAlignment(), 4));
26683
26684     SDValue NewChain = LoLd.getValue(1);
26685     if (TokenFactorIndex != -1) {
26686       Ops.push_back(LoLd);
26687       Ops.push_back(HiLd);
26688       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26689     }
26690
26691     LoAddr = St->getBasePtr();
26692     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26693                          DAG.getConstant(4, StDL, MVT::i32));
26694
26695     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26696                                 St->getPointerInfo(),
26697                                 St->isVolatile(), St->isNonTemporal(),
26698                                 St->getAlignment());
26699     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26700                                 St->getPointerInfo().getWithOffset(4),
26701                                 St->isVolatile(),
26702                                 St->isNonTemporal(),
26703                                 MinAlign(St->getAlignment(), 4));
26704     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26705   }
26706
26707   // This is similar to the above case, but here we handle a scalar 64-bit
26708   // integer store that is extracted from a vector on a 32-bit target.
26709   // If we have SSE2, then we can treat it like a floating-point double
26710   // to get past legalization. The execution dependencies fixup pass will
26711   // choose the optimal machine instruction for the store if this really is
26712   // an integer or v2f32 rather than an f64.
26713   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26714       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26715     SDValue OldExtract = St->getOperand(1);
26716     SDValue ExtOp0 = OldExtract.getOperand(0);
26717     unsigned VecSize = ExtOp0.getValueSizeInBits();
26718     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26719     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26720     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26721                                      BitCast, OldExtract.getOperand(1));
26722     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26723                         St->getPointerInfo(), St->isVolatile(),
26724                         St->isNonTemporal(), St->getAlignment());
26725   }
26726
26727   return SDValue();
26728 }
26729
26730 /// Return 'true' if this vector operation is "horizontal"
26731 /// and return the operands for the horizontal operation in LHS and RHS.  A
26732 /// horizontal operation performs the binary operation on successive elements
26733 /// of its first operand, then on successive elements of its second operand,
26734 /// returning the resulting values in a vector.  For example, if
26735 ///   A = < float a0, float a1, float a2, float a3 >
26736 /// and
26737 ///   B = < float b0, float b1, float b2, float b3 >
26738 /// then the result of doing a horizontal operation on A and B is
26739 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26740 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26741 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26742 /// set to A, RHS to B, and the routine returns 'true'.
26743 /// Note that the binary operation should have the property that if one of the
26744 /// operands is UNDEF then the result is UNDEF.
26745 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26746   // Look for the following pattern: if
26747   //   A = < float a0, float a1, float a2, float a3 >
26748   //   B = < float b0, float b1, float b2, float b3 >
26749   // and
26750   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26751   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26752   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26753   // which is A horizontal-op B.
26754
26755   // At least one of the operands should be a vector shuffle.
26756   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26757       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26758     return false;
26759
26760   MVT VT = LHS.getSimpleValueType();
26761
26762   assert((VT.is128BitVector() || VT.is256BitVector()) &&
26763          "Unsupported vector type for horizontal add/sub");
26764
26765   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26766   // operate independently on 128-bit lanes.
26767   unsigned NumElts = VT.getVectorNumElements();
26768   unsigned NumLanes = VT.getSizeInBits()/128;
26769   unsigned NumLaneElts = NumElts / NumLanes;
26770   assert((NumLaneElts % 2 == 0) &&
26771          "Vector type should have an even number of elements in each lane");
26772   unsigned HalfLaneElts = NumLaneElts/2;
26773
26774   // View LHS in the form
26775   //   LHS = VECTOR_SHUFFLE A, B, LMask
26776   // If LHS is not a shuffle then pretend it is the shuffle
26777   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26778   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26779   // type VT.
26780   SDValue A, B;
26781   SmallVector<int, 16> LMask(NumElts);
26782   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26783     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26784       A = LHS.getOperand(0);
26785     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26786       B = LHS.getOperand(1);
26787     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26788     std::copy(Mask.begin(), Mask.end(), LMask.begin());
26789   } else {
26790     if (LHS.getOpcode() != ISD::UNDEF)
26791       A = LHS;
26792     for (unsigned i = 0; i != NumElts; ++i)
26793       LMask[i] = i;
26794   }
26795
26796   // Likewise, view RHS in the form
26797   //   RHS = VECTOR_SHUFFLE C, D, RMask
26798   SDValue C, D;
26799   SmallVector<int, 16> RMask(NumElts);
26800   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26801     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26802       C = RHS.getOperand(0);
26803     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26804       D = RHS.getOperand(1);
26805     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26806     std::copy(Mask.begin(), Mask.end(), RMask.begin());
26807   } else {
26808     if (RHS.getOpcode() != ISD::UNDEF)
26809       C = RHS;
26810     for (unsigned i = 0; i != NumElts; ++i)
26811       RMask[i] = i;
26812   }
26813
26814   // Check that the shuffles are both shuffling the same vectors.
26815   if (!(A == C && B == D) && !(A == D && B == C))
26816     return false;
26817
26818   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26819   if (!A.getNode() && !B.getNode())
26820     return false;
26821
26822   // If A and B occur in reverse order in RHS, then "swap" them (which means
26823   // rewriting the mask).
26824   if (A != C)
26825     ShuffleVectorSDNode::commuteMask(RMask);
26826
26827   // At this point LHS and RHS are equivalent to
26828   //   LHS = VECTOR_SHUFFLE A, B, LMask
26829   //   RHS = VECTOR_SHUFFLE A, B, RMask
26830   // Check that the masks correspond to performing a horizontal operation.
26831   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26832     for (unsigned i = 0; i != NumLaneElts; ++i) {
26833       int LIdx = LMask[i+l], RIdx = RMask[i+l];
26834
26835       // Ignore any UNDEF components.
26836       if (LIdx < 0 || RIdx < 0 ||
26837           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26838           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26839         continue;
26840
26841       // Check that successive elements are being operated on.  If not, this is
26842       // not a horizontal operation.
26843       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26844       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26845       if (!(LIdx == Index && RIdx == Index + 1) &&
26846           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26847         return false;
26848     }
26849   }
26850
26851   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26852   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26853   return true;
26854 }
26855
26856 /// Do target-specific dag combines on floating point adds.
26857 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26858                                   const X86Subtarget *Subtarget) {
26859   EVT VT = N->getValueType(0);
26860   SDValue LHS = N->getOperand(0);
26861   SDValue RHS = N->getOperand(1);
26862
26863   // Try to synthesize horizontal adds from adds of shuffles.
26864   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26865        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26866       isHorizontalBinOp(LHS, RHS, true))
26867     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26868   return SDValue();
26869 }
26870
26871 /// Do target-specific dag combines on floating point subs.
26872 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26873                                   const X86Subtarget *Subtarget) {
26874   EVT VT = N->getValueType(0);
26875   SDValue LHS = N->getOperand(0);
26876   SDValue RHS = N->getOperand(1);
26877
26878   // Try to synthesize horizontal subs from subs of shuffles.
26879   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26880        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26881       isHorizontalBinOp(LHS, RHS, false))
26882     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26883   return SDValue();
26884 }
26885
26886 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
26887 static SDValue
26888 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
26889                                   SmallVector<SDValue, 8> &Regs) {
26890   assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
26891                              Regs[0].getValueType() == MVT::v2i64));
26892   EVT OutVT = N->getValueType(0);
26893   EVT OutSVT = OutVT.getVectorElementType();
26894   EVT InVT = Regs[0].getValueType();
26895   EVT InSVT = InVT.getVectorElementType();
26896   SDLoc DL(N);
26897
26898   // First, use mask to unset all bits that won't appear in the result.
26899   assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
26900          "OutSVT can only be either i8 or i16.");
26901   SDValue MaskVal =
26902       DAG.getConstant(OutSVT == MVT::i8 ? 0xFF : 0xFFFF, DL, InSVT);
26903   SDValue MaskVec = DAG.getNode(
26904       ISD::BUILD_VECTOR, DL, InVT,
26905       SmallVector<SDValue, 8>(InVT.getVectorNumElements(), MaskVal));
26906   for (auto &Reg : Regs)
26907     Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVec, Reg);
26908
26909   MVT UnpackedVT, PackedVT;
26910   if (OutSVT == MVT::i8) {
26911     UnpackedVT = MVT::v8i16;
26912     PackedVT = MVT::v16i8;
26913   } else {
26914     UnpackedVT = MVT::v4i32;
26915     PackedVT = MVT::v8i16;
26916   }
26917
26918   // In each iteration, truncate the type by a half size.
26919   auto RegNum = Regs.size();
26920   for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
26921        j < e; j *= 2, RegNum /= 2) {
26922     for (unsigned i = 0; i < RegNum; i++)
26923       Regs[i] = DAG.getNode(ISD::BITCAST, DL, UnpackedVT, Regs[i]);
26924     for (unsigned i = 0; i < RegNum / 2; i++)
26925       Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
26926                             Regs[i * 2 + 1]);
26927   }
26928
26929   // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
26930   // then extract a subvector as the result since v8i8 is not a legal type.
26931   if (OutVT == MVT::v8i8) {
26932     Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
26933     Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
26934                           DAG.getIntPtrConstant(0, DL));
26935     return Regs[0];
26936   } else if (RegNum > 1) {
26937     Regs.resize(RegNum);
26938     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26939   } else
26940     return Regs[0];
26941 }
26942
26943 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
26944 static SDValue
26945 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
26946                                   SmallVector<SDValue, 8> &Regs) {
26947   assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
26948   EVT OutVT = N->getValueType(0);
26949   SDLoc DL(N);
26950
26951   // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
26952   SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
26953   for (auto &Reg : Regs) {
26954     Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26955     Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26956   }
26957
26958   for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
26959     Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
26960                           Regs[i * 2 + 1]);
26961
26962   if (Regs.size() > 2) {
26963     Regs.resize(Regs.size() / 2);
26964     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26965   } else
26966     return Regs[0];
26967 }
26968
26969 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
26970 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
26971 /// legalization the truncation will be translated into a BUILD_VECTOR with each
26972 /// element that is extracted from a vector and then truncated, and it is
26973 /// diffcult to do this optimization based on them.
26974 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
26975                                        const X86Subtarget *Subtarget) {
26976   EVT OutVT = N->getValueType(0);
26977   if (!OutVT.isVector())
26978     return SDValue();
26979
26980   SDValue In = N->getOperand(0);
26981   if (!In.getValueType().isSimple())
26982     return SDValue();
26983
26984   EVT InVT = In.getValueType();
26985   unsigned NumElems = OutVT.getVectorNumElements();
26986
26987   // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
26988   // SSE2, and we need to take care of it specially.
26989   // AVX512 provides vpmovdb.
26990   if (!Subtarget->hasSSE2() || Subtarget->hasAVX2())
26991     return SDValue();
26992
26993   EVT OutSVT = OutVT.getVectorElementType();
26994   EVT InSVT = InVT.getVectorElementType();
26995   if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
26996         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
26997         NumElems >= 8))
26998     return SDValue();
26999
27000   // SSSE3's pshufb results in less instructions in the cases below.
27001   if (Subtarget->hasSSSE3() && NumElems == 8 &&
27002       ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
27003        (InSVT == MVT::i32 && OutSVT == MVT::i16)))
27004     return SDValue();
27005
27006   SDLoc DL(N);
27007
27008   // Split a long vector into vectors of legal type.
27009   unsigned RegNum = InVT.getSizeInBits() / 128;
27010   SmallVector<SDValue, 8> SubVec(RegNum);
27011   if (InSVT == MVT::i32) {
27012     for (unsigned i = 0; i < RegNum; i++)
27013       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
27014                               DAG.getIntPtrConstant(i * 4, DL));
27015   } else {
27016     for (unsigned i = 0; i < RegNum; i++)
27017       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
27018                               DAG.getIntPtrConstant(i * 2, DL));
27019   }
27020
27021   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PAKCUS
27022   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
27023   // truncate 2 x v4i32 to v8i16.
27024   if (Subtarget->hasSSE41() || OutSVT == MVT::i8)
27025     return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
27026   else if (InSVT == MVT::i32)
27027     return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
27028   else
27029     return SDValue();
27030 }
27031
27032 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
27033                                       const X86Subtarget *Subtarget) {
27034   // Try to detect AVG pattern first.
27035   SDValue Avg = detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG,
27036                                  Subtarget, SDLoc(N));
27037   if (Avg.getNode())
27038     return Avg;
27039
27040   return combineVectorTruncation(N, DAG, Subtarget);
27041 }
27042
27043 /// Do target-specific dag combines on floating point negations.
27044 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
27045                                   const X86Subtarget *Subtarget) {
27046   EVT VT = N->getValueType(0);
27047   EVT SVT = VT.getScalarType();
27048   SDValue Arg = N->getOperand(0);
27049   SDLoc DL(N);
27050
27051   // Let legalize expand this if it isn't a legal type yet.
27052   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27053     return SDValue();
27054
27055   // If we're negating a FMUL node on a target with FMA, then we can avoid the
27056   // use of a constant by performing (-0 - A*B) instead.
27057   // FIXME: Check rounding control flags as well once it becomes available.
27058   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
27059       Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
27060     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
27061     return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
27062                        Arg.getOperand(1), Zero);
27063   }
27064
27065   // If we're negating a FMA node, then we can adjust the
27066   // instruction to include the extra negation.
27067   if (Arg.hasOneUse()) {
27068     switch (Arg.getOpcode()) {
27069     case X86ISD::FMADD:
27070       return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
27071                          Arg.getOperand(1), Arg.getOperand(2));
27072     case X86ISD::FMSUB:
27073       return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
27074                          Arg.getOperand(1), Arg.getOperand(2));
27075     case X86ISD::FNMADD:
27076       return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
27077                          Arg.getOperand(1), Arg.getOperand(2));
27078     case X86ISD::FNMSUB:
27079       return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
27080                          Arg.getOperand(1), Arg.getOperand(2));
27081     }
27082   }
27083   return SDValue();
27084 }
27085
27086 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
27087                               const X86Subtarget *Subtarget) {
27088   EVT VT = N->getValueType(0);
27089   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
27090     // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
27091     // These logic operations may be executed in the integer domain.
27092     SDLoc dl(N);
27093     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
27094     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
27095
27096     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
27097     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
27098     unsigned IntOpcode = 0;
27099     switch (N->getOpcode()) {
27100       default: llvm_unreachable("Unexpected FP logic op");
27101       case X86ISD::FOR: IntOpcode = ISD::OR; break;
27102       case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
27103       case X86ISD::FAND: IntOpcode = ISD::AND; break;
27104       case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
27105     }
27106     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
27107     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
27108   }
27109   return SDValue();
27110 }
27111 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
27112 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
27113                                  const X86Subtarget *Subtarget) {
27114   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
27115
27116   // F[X]OR(0.0, x) -> x
27117   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27118     if (C->getValueAPF().isPosZero())
27119       return N->getOperand(1);
27120
27121   // F[X]OR(x, 0.0) -> x
27122   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27123     if (C->getValueAPF().isPosZero())
27124       return N->getOperand(0);
27125
27126   return lowerX86FPLogicOp(N, DAG, Subtarget);
27127 }
27128
27129 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
27130 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
27131   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
27132
27133   // Only perform optimizations if UnsafeMath is used.
27134   if (!DAG.getTarget().Options.UnsafeFPMath)
27135     return SDValue();
27136
27137   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
27138   // into FMINC and FMAXC, which are Commutative operations.
27139   unsigned NewOp = 0;
27140   switch (N->getOpcode()) {
27141     default: llvm_unreachable("unknown opcode");
27142     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
27143     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
27144   }
27145
27146   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
27147                      N->getOperand(0), N->getOperand(1));
27148 }
27149
27150 static SDValue performFMinNumFMaxNumCombine(SDNode *N, SelectionDAG &DAG,
27151                                             const X86Subtarget *Subtarget) {
27152   if (Subtarget->useSoftFloat())
27153     return SDValue();
27154
27155   // TODO: Check for global or instruction-level "nnan". In that case, we
27156   //       should be able to lower to FMAX/FMIN alone.
27157   // TODO: If an operand is already known to be a NaN or not a NaN, this
27158   //       should be an optional swap and FMAX/FMIN.
27159
27160   EVT VT = N->getValueType(0);
27161   if (!((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
27162         (Subtarget->hasSSE2() && (VT == MVT::f64 || VT == MVT::v2f64)) ||
27163         (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))))
27164     return SDValue();
27165
27166   // This takes at least 3 instructions, so favor a library call when operating
27167   // on a scalar and minimizing code size.
27168   if (!VT.isVector() && DAG.getMachineFunction().getFunction()->optForMinSize())
27169     return SDValue();
27170
27171   SDValue Op0 = N->getOperand(0);
27172   SDValue Op1 = N->getOperand(1);
27173   SDLoc DL(N);
27174   EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
27175       DAG.getDataLayout(), *DAG.getContext(), VT);
27176
27177   // There are 4 possibilities involving NaN inputs, and these are the required
27178   // outputs:
27179   //                   Op1
27180   //               Num     NaN
27181   //            ----------------
27182   //       Num  |  Max  |  Op0 |
27183   // Op0        ----------------
27184   //       NaN  |  Op1  |  NaN |
27185   //            ----------------
27186   //
27187   // The SSE FP max/min instructions were not designed for this case, but rather
27188   // to implement:
27189   //   Min = Op1 < Op0 ? Op1 : Op0
27190   //   Max = Op1 > Op0 ? Op1 : Op0
27191   //
27192   // So they always return Op0 if either input is a NaN. However, we can still
27193   // use those instructions for fmaxnum by selecting away a NaN input.
27194
27195   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
27196   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
27197   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
27198   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
27199
27200   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
27201   // are NaN, the NaN value of Op1 is the result.
27202   auto SelectOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
27203   return DAG.getNode(SelectOpcode, DL, VT, IsOp0Nan, Op1, MinOrMax);
27204 }
27205
27206 /// Do target-specific dag combines on X86ISD::FAND nodes.
27207 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
27208                                   const X86Subtarget *Subtarget) {
27209   // FAND(0.0, x) -> 0.0
27210   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27211     if (C->getValueAPF().isPosZero())
27212       return N->getOperand(0);
27213
27214   // FAND(x, 0.0) -> 0.0
27215   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27216     if (C->getValueAPF().isPosZero())
27217       return N->getOperand(1);
27218
27219   return lowerX86FPLogicOp(N, DAG, Subtarget);
27220 }
27221
27222 /// Do target-specific dag combines on X86ISD::FANDN nodes
27223 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
27224                                    const X86Subtarget *Subtarget) {
27225   // FANDN(0.0, x) -> x
27226   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27227     if (C->getValueAPF().isPosZero())
27228       return N->getOperand(1);
27229
27230   // FANDN(x, 0.0) -> 0.0
27231   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27232     if (C->getValueAPF().isPosZero())
27233       return N->getOperand(1);
27234
27235   return lowerX86FPLogicOp(N, DAG, Subtarget);
27236 }
27237
27238 static SDValue PerformBTCombine(SDNode *N,
27239                                 SelectionDAG &DAG,
27240                                 TargetLowering::DAGCombinerInfo &DCI) {
27241   // BT ignores high bits in the bit index operand.
27242   SDValue Op1 = N->getOperand(1);
27243   if (Op1.hasOneUse()) {
27244     unsigned BitWidth = Op1.getValueSizeInBits();
27245     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
27246     APInt KnownZero, KnownOne;
27247     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
27248                                           !DCI.isBeforeLegalizeOps());
27249     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27250     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
27251         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
27252       DCI.CommitTargetLoweringOpt(TLO);
27253   }
27254   return SDValue();
27255 }
27256
27257 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
27258   SDValue Op = N->getOperand(0);
27259   if (Op.getOpcode() == ISD::BITCAST)
27260     Op = Op.getOperand(0);
27261   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
27262   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
27263       VT.getVectorElementType().getSizeInBits() ==
27264       OpVT.getVectorElementType().getSizeInBits()) {
27265     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
27266   }
27267   return SDValue();
27268 }
27269
27270 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
27271                                                const X86Subtarget *Subtarget) {
27272   EVT VT = N->getValueType(0);
27273   if (!VT.isVector())
27274     return SDValue();
27275
27276   SDValue N0 = N->getOperand(0);
27277   SDValue N1 = N->getOperand(1);
27278   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
27279   SDLoc dl(N);
27280
27281   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
27282   // both SSE and AVX2 since there is no sign-extended shift right
27283   // operation on a vector with 64-bit elements.
27284   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
27285   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
27286   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
27287       N0.getOpcode() == ISD::SIGN_EXTEND)) {
27288     SDValue N00 = N0.getOperand(0);
27289
27290     // EXTLOAD has a better solution on AVX2,
27291     // it may be replaced with X86ISD::VSEXT node.
27292     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
27293       if (!ISD::isNormalLoad(N00.getNode()))
27294         return SDValue();
27295
27296     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
27297         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
27298                                   N00, N1);
27299       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
27300     }
27301   }
27302   return SDValue();
27303 }
27304
27305 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
27306 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
27307 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
27308 /// eliminate extend, add, and shift instructions.
27309 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
27310                                        const X86Subtarget *Subtarget) {
27311   // TODO: This should be valid for other integer types.
27312   EVT VT = Sext->getValueType(0);
27313   if (VT != MVT::i64)
27314     return SDValue();
27315
27316   // We need an 'add nsw' feeding into the 'sext'.
27317   SDValue Add = Sext->getOperand(0);
27318   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
27319     return SDValue();
27320
27321   // Having a constant operand to the 'add' ensures that we are not increasing
27322   // the instruction count because the constant is extended for free below.
27323   // A constant operand can also become the displacement field of an LEA.
27324   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
27325   if (!AddOp1)
27326     return SDValue();
27327
27328   // Don't make the 'add' bigger if there's no hope of combining it with some
27329   // other 'add' or 'shl' instruction.
27330   // TODO: It may be profitable to generate simpler LEA instructions in place
27331   // of single 'add' instructions, but the cost model for selecting an LEA
27332   // currently has a high threshold.
27333   bool HasLEAPotential = false;
27334   for (auto *User : Sext->uses()) {
27335     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
27336       HasLEAPotential = true;
27337       break;
27338     }
27339   }
27340   if (!HasLEAPotential)
27341     return SDValue();
27342
27343   // Everything looks good, so pull the 'sext' ahead of the 'add'.
27344   int64_t AddConstant = AddOp1->getSExtValue();
27345   SDValue AddOp0 = Add.getOperand(0);
27346   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
27347   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
27348
27349   // The wider add is guaranteed to not wrap because both operands are
27350   // sign-extended.
27351   SDNodeFlags Flags;
27352   Flags.setNoSignedWrap(true);
27353   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
27354 }
27355
27356 /// (i8,i32 {s/z}ext ({s/u}divrem (i8 x, i8 y)) ->
27357 /// (i8,i32 ({s/u}divrem_sext_hreg (i8 x, i8 y)
27358 /// This exposes the {s/z}ext to the sdivrem lowering, so that it directly
27359 /// extends from AH (which we otherwise need to do contortions to access).
27360 static SDValue getDivRem8(SDNode *N, SelectionDAG &DAG) {
27361   SDValue N0 = N->getOperand(0);
27362   auto OpcodeN = N->getOpcode();
27363   auto OpcodeN0 = N0.getOpcode();
27364   if (!((OpcodeN == ISD::SIGN_EXTEND && OpcodeN0 == ISD::SDIVREM) ||
27365         (OpcodeN == ISD::ZERO_EXTEND && OpcodeN0 == ISD::UDIVREM)))
27366     return SDValue();
27367
27368   EVT VT = N->getValueType(0);
27369   EVT InVT = N0.getValueType();
27370   if (N0.getResNo() != 1 || InVT != MVT::i8 || VT != MVT::i32)
27371     return SDValue();
27372
27373   SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27374   auto DivRemOpcode = OpcodeN0 == ISD::SDIVREM ? X86ISD::SDIVREM8_SEXT_HREG
27375                                                : X86ISD::UDIVREM8_ZEXT_HREG;
27376   SDValue R = DAG.getNode(DivRemOpcode, SDLoc(N), NodeTys, N0.getOperand(0),
27377                           N0.getOperand(1));
27378   DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27379   return R.getValue(1);
27380 }
27381
27382 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
27383                                   TargetLowering::DAGCombinerInfo &DCI,
27384                                   const X86Subtarget *Subtarget) {
27385   SDValue N0 = N->getOperand(0);
27386   EVT VT = N->getValueType(0);
27387   EVT SVT = VT.getScalarType();
27388   EVT InVT = N0.getValueType();
27389   EVT InSVT = InVT.getScalarType();
27390   SDLoc DL(N);
27391
27392   if (SDValue DivRem8 = getDivRem8(N, DAG))
27393     return DivRem8;
27394
27395   if (!DCI.isBeforeLegalizeOps()) {
27396     if (InVT == MVT::i1) {
27397       SDValue Zero = DAG.getConstant(0, DL, VT);
27398       SDValue AllOnes =
27399         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
27400       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
27401     }
27402     return SDValue();
27403   }
27404
27405   if (VT.isVector() && Subtarget->hasSSE2()) {
27406     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
27407       EVT InVT = N.getValueType();
27408       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
27409                                    Size / InVT.getScalarSizeInBits());
27410       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
27411                                     DAG.getUNDEF(InVT));
27412       Opnds[0] = N;
27413       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
27414     };
27415
27416     // If target-size is less than 128-bits, extend to a type that would extend
27417     // to 128 bits, extend that and extract the original target vector.
27418     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
27419         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27420         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27421       unsigned Scale = 128 / VT.getSizeInBits();
27422       EVT ExVT =
27423           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
27424       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
27425       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
27426       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
27427                          DAG.getIntPtrConstant(0, DL));
27428     }
27429
27430     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
27431     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
27432     if (VT.getSizeInBits() == 128 &&
27433         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27434         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27435       SDValue ExOp = ExtendVecSize(DL, N0, 128);
27436       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
27437     }
27438
27439     // On pre-AVX2 targets, split into 128-bit nodes of
27440     // ISD::SIGN_EXTEND_VECTOR_INREG.
27441     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
27442         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27443         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27444       unsigned NumVecs = VT.getSizeInBits() / 128;
27445       unsigned NumSubElts = 128 / SVT.getSizeInBits();
27446       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
27447       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
27448
27449       SmallVector<SDValue, 8> Opnds;
27450       for (unsigned i = 0, Offset = 0; i != NumVecs;
27451            ++i, Offset += NumSubElts) {
27452         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
27453                                      DAG.getIntPtrConstant(Offset, DL));
27454         SrcVec = ExtendVecSize(DL, SrcVec, 128);
27455         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
27456         Opnds.push_back(SrcVec);
27457       }
27458       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
27459     }
27460   }
27461
27462   if (Subtarget->hasAVX() && VT.is256BitVector())
27463     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27464       return R;
27465
27466   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
27467     return NewAdd;
27468
27469   return SDValue();
27470 }
27471
27472 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
27473                                  const X86Subtarget* Subtarget) {
27474   SDLoc dl(N);
27475   EVT VT = N->getValueType(0);
27476
27477   // Let legalize expand this if it isn't a legal type yet.
27478   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27479     return SDValue();
27480
27481   EVT ScalarVT = VT.getScalarType();
27482   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
27483     return SDValue();
27484
27485   SDValue A = N->getOperand(0);
27486   SDValue B = N->getOperand(1);
27487   SDValue C = N->getOperand(2);
27488
27489   bool NegA = (A.getOpcode() == ISD::FNEG);
27490   bool NegB = (B.getOpcode() == ISD::FNEG);
27491   bool NegC = (C.getOpcode() == ISD::FNEG);
27492
27493   // Negative multiplication when NegA xor NegB
27494   bool NegMul = (NegA != NegB);
27495   if (NegA)
27496     A = A.getOperand(0);
27497   if (NegB)
27498     B = B.getOperand(0);
27499   if (NegC)
27500     C = C.getOperand(0);
27501
27502   unsigned Opcode;
27503   if (!NegMul)
27504     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
27505   else
27506     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
27507
27508   return DAG.getNode(Opcode, dl, VT, A, B, C);
27509 }
27510
27511 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
27512                                   TargetLowering::DAGCombinerInfo &DCI,
27513                                   const X86Subtarget *Subtarget) {
27514   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
27515   //           (and (i32 x86isd::setcc_carry), 1)
27516   // This eliminates the zext. This transformation is necessary because
27517   // ISD::SETCC is always legalized to i8.
27518   SDLoc dl(N);
27519   SDValue N0 = N->getOperand(0);
27520   EVT VT = N->getValueType(0);
27521
27522   if (N0.getOpcode() == ISD::AND &&
27523       N0.hasOneUse() &&
27524       N0.getOperand(0).hasOneUse()) {
27525     SDValue N00 = N0.getOperand(0);
27526     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27527       if (!isOneConstant(N0.getOperand(1)))
27528         return SDValue();
27529       return DAG.getNode(ISD::AND, dl, VT,
27530                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27531                                      N00.getOperand(0), N00.getOperand(1)),
27532                          DAG.getConstant(1, dl, VT));
27533     }
27534   }
27535
27536   if (N0.getOpcode() == ISD::TRUNCATE &&
27537       N0.hasOneUse() &&
27538       N0.getOperand(0).hasOneUse()) {
27539     SDValue N00 = N0.getOperand(0);
27540     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27541       return DAG.getNode(ISD::AND, dl, VT,
27542                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27543                                      N00.getOperand(0), N00.getOperand(1)),
27544                          DAG.getConstant(1, dl, VT));
27545     }
27546   }
27547
27548   if (VT.is256BitVector())
27549     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27550       return R;
27551
27552   if (SDValue DivRem8 = getDivRem8(N, DAG))
27553     return DivRem8;
27554
27555   return SDValue();
27556 }
27557
27558 // Optimize x == -y --> x+y == 0
27559 //          x != -y --> x+y != 0
27560 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
27561                                       const X86Subtarget* Subtarget) {
27562   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
27563   SDValue LHS = N->getOperand(0);
27564   SDValue RHS = N->getOperand(1);
27565   EVT VT = N->getValueType(0);
27566   SDLoc DL(N);
27567
27568   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
27569     if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
27570       SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
27571                                  LHS.getOperand(1));
27572       return DAG.getSetCC(DL, N->getValueType(0), addV,
27573                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27574     }
27575   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
27576     if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
27577       SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
27578                                  RHS.getOperand(1));
27579       return DAG.getSetCC(DL, N->getValueType(0), addV,
27580                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27581     }
27582
27583   if (VT.getScalarType() == MVT::i1 &&
27584       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
27585     bool IsSEXT0 =
27586         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27587         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27588     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27589
27590     if (!IsSEXT0 || !IsVZero1) {
27591       // Swap the operands and update the condition code.
27592       std::swap(LHS, RHS);
27593       CC = ISD::getSetCCSwappedOperands(CC);
27594
27595       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27596                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27597       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27598     }
27599
27600     if (IsSEXT0 && IsVZero1) {
27601       assert(VT == LHS.getOperand(0).getValueType() &&
27602              "Uexpected operand type");
27603       if (CC == ISD::SETGT)
27604         return DAG.getConstant(0, DL, VT);
27605       if (CC == ISD::SETLE)
27606         return DAG.getConstant(1, DL, VT);
27607       if (CC == ISD::SETEQ || CC == ISD::SETGE)
27608         return DAG.getNOT(DL, LHS.getOperand(0), VT);
27609
27610       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
27611              "Unexpected condition code!");
27612       return LHS.getOperand(0);
27613     }
27614   }
27615
27616   return SDValue();
27617 }
27618
27619 static SDValue PerformGatherScatterCombine(SDNode *N, SelectionDAG &DAG) {
27620   SDLoc DL(N);
27621   // Gather and Scatter instructions use k-registers for masks. The type of
27622   // the masks is v*i1. So the mask will be truncated anyway.
27623   // The SIGN_EXTEND_INREG my be dropped.
27624   SDValue Mask = N->getOperand(2);
27625   if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
27626     SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
27627     NewOps[2] = Mask.getOperand(0);
27628     DAG.UpdateNodeOperands(N, NewOps);
27629   }
27630   return SDValue();
27631 }
27632
27633 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
27634 // as "sbb reg,reg", since it can be extended without zext and produces
27635 // an all-ones bit which is more useful than 0/1 in some cases.
27636 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
27637                                MVT VT) {
27638   if (VT == MVT::i8)
27639     return DAG.getNode(ISD::AND, DL, VT,
27640                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27641                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
27642                                    EFLAGS),
27643                        DAG.getConstant(1, DL, VT));
27644   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
27645   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
27646                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27647                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
27648                                  EFLAGS));
27649 }
27650
27651 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
27652 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
27653                                    TargetLowering::DAGCombinerInfo &DCI,
27654                                    const X86Subtarget *Subtarget) {
27655   SDLoc DL(N);
27656   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
27657   SDValue EFLAGS = N->getOperand(1);
27658
27659   if (CC == X86::COND_A) {
27660     // Try to convert COND_A into COND_B in an attempt to facilitate
27661     // materializing "setb reg".
27662     //
27663     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
27664     // cannot take an immediate as its first operand.
27665     //
27666     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
27667         EFLAGS.getValueType().isInteger() &&
27668         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
27669       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
27670                                    EFLAGS.getNode()->getVTList(),
27671                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
27672       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
27673       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
27674     }
27675   }
27676
27677   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
27678   // a zext and produces an all-ones bit which is more useful than 0/1 in some
27679   // cases.
27680   if (CC == X86::COND_B)
27681     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
27682
27683   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27684     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27685     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
27686   }
27687
27688   return SDValue();
27689 }
27690
27691 // Optimize branch condition evaluation.
27692 //
27693 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
27694                                     TargetLowering::DAGCombinerInfo &DCI,
27695                                     const X86Subtarget *Subtarget) {
27696   SDLoc DL(N);
27697   SDValue Chain = N->getOperand(0);
27698   SDValue Dest = N->getOperand(1);
27699   SDValue EFLAGS = N->getOperand(3);
27700   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
27701
27702   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27703     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27704     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
27705                        Flags);
27706   }
27707
27708   return SDValue();
27709 }
27710
27711 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
27712                                                          SelectionDAG &DAG) {
27713   // Take advantage of vector comparisons producing 0 or -1 in each lane to
27714   // optimize away operation when it's from a constant.
27715   //
27716   // The general transformation is:
27717   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
27718   //       AND(VECTOR_CMP(x,y), constant2)
27719   //    constant2 = UNARYOP(constant)
27720
27721   // Early exit if this isn't a vector operation, the operand of the
27722   // unary operation isn't a bitwise AND, or if the sizes of the operations
27723   // aren't the same.
27724   EVT VT = N->getValueType(0);
27725   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27726       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27727       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27728     return SDValue();
27729
27730   // Now check that the other operand of the AND is a constant. We could
27731   // make the transformation for non-constant splats as well, but it's unclear
27732   // that would be a benefit as it would not eliminate any operations, just
27733   // perform one more step in scalar code before moving to the vector unit.
27734   if (BuildVectorSDNode *BV =
27735           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27736     // Bail out if the vector isn't a constant.
27737     if (!BV->isConstant())
27738       return SDValue();
27739
27740     // Everything checks out. Build up the new and improved node.
27741     SDLoc DL(N);
27742     EVT IntVT = BV->getValueType(0);
27743     // Create a new constant of the appropriate type for the transformed
27744     // DAG.
27745     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27746     // The AND node needs bitcasts to/from an integer vector type around it.
27747     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27748     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27749                                  N->getOperand(0)->getOperand(0), MaskConst);
27750     SDValue Res = DAG.getBitcast(VT, NewAnd);
27751     return Res;
27752   }
27753
27754   return SDValue();
27755 }
27756
27757 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27758                                         const X86Subtarget *Subtarget) {
27759   SDValue Op0 = N->getOperand(0);
27760   EVT VT = N->getValueType(0);
27761   EVT InVT = Op0.getValueType();
27762   EVT InSVT = InVT.getScalarType();
27763   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27764
27765   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27766   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27767   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27768     SDLoc dl(N);
27769     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27770                                  InVT.getVectorNumElements());
27771     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27772
27773     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27774       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27775
27776     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27777   }
27778
27779   return SDValue();
27780 }
27781
27782 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27783                                         const X86Subtarget *Subtarget) {
27784   // First try to optimize away the conversion entirely when it's
27785   // conditionally from a constant. Vectors only.
27786   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27787     return Res;
27788
27789   // Now move on to more general possibilities.
27790   SDValue Op0 = N->getOperand(0);
27791   EVT VT = N->getValueType(0);
27792   EVT InVT = Op0.getValueType();
27793   EVT InSVT = InVT.getScalarType();
27794
27795   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27796   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27797   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27798     SDLoc dl(N);
27799     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27800                                  InVT.getVectorNumElements());
27801     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27802     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27803   }
27804
27805   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27806   // a 32-bit target where SSE doesn't support i64->FP operations.
27807   if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27808     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27809     EVT LdVT = Ld->getValueType(0);
27810
27811     // This transformation is not supported if the result type is f16
27812     if (VT == MVT::f16)
27813       return SDValue();
27814
27815     if (!Ld->isVolatile() && !VT.isVector() &&
27816         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27817         !Subtarget->is64Bit() && LdVT == MVT::i64) {
27818       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27819           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27820       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27821       return FILDChain;
27822     }
27823   }
27824   return SDValue();
27825 }
27826
27827 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27828 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27829                                  X86TargetLowering::DAGCombinerInfo &DCI) {
27830   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27831   // the result is either zero or one (depending on the input carry bit).
27832   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27833   if (X86::isZeroNode(N->getOperand(0)) &&
27834       X86::isZeroNode(N->getOperand(1)) &&
27835       // We don't have a good way to replace an EFLAGS use, so only do this when
27836       // dead right now.
27837       SDValue(N, 1).use_empty()) {
27838     SDLoc DL(N);
27839     EVT VT = N->getValueType(0);
27840     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27841     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27842                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27843                                            DAG.getConstant(X86::COND_B, DL,
27844                                                            MVT::i8),
27845                                            N->getOperand(2)),
27846                                DAG.getConstant(1, DL, VT));
27847     return DCI.CombineTo(N, Res1, CarryOut);
27848   }
27849
27850   return SDValue();
27851 }
27852
27853 // fold (add Y, (sete  X, 0)) -> adc  0, Y
27854 //      (add Y, (setne X, 0)) -> sbb -1, Y
27855 //      (sub (sete  X, 0), Y) -> sbb  0, Y
27856 //      (sub (setne X, 0), Y) -> adc -1, Y
27857 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27858   SDLoc DL(N);
27859
27860   // Look through ZExts.
27861   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27862   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27863     return SDValue();
27864
27865   SDValue SetCC = Ext.getOperand(0);
27866   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27867     return SDValue();
27868
27869   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27870   if (CC != X86::COND_E && CC != X86::COND_NE)
27871     return SDValue();
27872
27873   SDValue Cmp = SetCC.getOperand(1);
27874   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27875       !X86::isZeroNode(Cmp.getOperand(1)) ||
27876       !Cmp.getOperand(0).getValueType().isInteger())
27877     return SDValue();
27878
27879   SDValue CmpOp0 = Cmp.getOperand(0);
27880   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27881                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
27882
27883   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27884   if (CC == X86::COND_NE)
27885     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27886                        DL, OtherVal.getValueType(), OtherVal,
27887                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27888                        NewCmp);
27889   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27890                      DL, OtherVal.getValueType(), OtherVal,
27891                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27892 }
27893
27894 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27895 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27896                                  const X86Subtarget *Subtarget) {
27897   EVT VT = N->getValueType(0);
27898   SDValue Op0 = N->getOperand(0);
27899   SDValue Op1 = N->getOperand(1);
27900
27901   // Try to synthesize horizontal adds from adds of shuffles.
27902   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27903        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27904       isHorizontalBinOp(Op0, Op1, true))
27905     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27906
27907   return OptimizeConditionalInDecrement(N, DAG);
27908 }
27909
27910 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27911                                  const X86Subtarget *Subtarget) {
27912   SDValue Op0 = N->getOperand(0);
27913   SDValue Op1 = N->getOperand(1);
27914
27915   // X86 can't encode an immediate LHS of a sub. See if we can push the
27916   // negation into a preceding instruction.
27917   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27918     // If the RHS of the sub is a XOR with one use and a constant, invert the
27919     // immediate. Then add one to the LHS of the sub so we can turn
27920     // X-Y -> X+~Y+1, saving one register.
27921     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27922         isa<ConstantSDNode>(Op1.getOperand(1))) {
27923       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27924       EVT VT = Op0.getValueType();
27925       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27926                                    Op1.getOperand(0),
27927                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
27928       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27929                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27930     }
27931   }
27932
27933   // Try to synthesize horizontal adds from adds of shuffles.
27934   EVT VT = N->getValueType(0);
27935   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27936        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27937       isHorizontalBinOp(Op0, Op1, true))
27938     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27939
27940   return OptimizeConditionalInDecrement(N, DAG);
27941 }
27942
27943 /// performVZEXTCombine - Performs build vector combines
27944 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27945                                    TargetLowering::DAGCombinerInfo &DCI,
27946                                    const X86Subtarget *Subtarget) {
27947   SDLoc DL(N);
27948   MVT VT = N->getSimpleValueType(0);
27949   SDValue Op = N->getOperand(0);
27950   MVT OpVT = Op.getSimpleValueType();
27951   MVT OpEltVT = OpVT.getVectorElementType();
27952   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27953
27954   // (vzext (bitcast (vzext (x)) -> (vzext x)
27955   SDValue V = Op;
27956   while (V.getOpcode() == ISD::BITCAST)
27957     V = V.getOperand(0);
27958
27959   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27960     MVT InnerVT = V.getSimpleValueType();
27961     MVT InnerEltVT = InnerVT.getVectorElementType();
27962
27963     // If the element sizes match exactly, we can just do one larger vzext. This
27964     // is always an exact type match as vzext operates on integer types.
27965     if (OpEltVT == InnerEltVT) {
27966       assert(OpVT == InnerVT && "Types must match for vzext!");
27967       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27968     }
27969
27970     // The only other way we can combine them is if only a single element of the
27971     // inner vzext is used in the input to the outer vzext.
27972     if (InnerEltVT.getSizeInBits() < InputBits)
27973       return SDValue();
27974
27975     // In this case, the inner vzext is completely dead because we're going to
27976     // only look at bits inside of the low element. Just do the outer vzext on
27977     // a bitcast of the input to the inner.
27978     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27979   }
27980
27981   // Check if we can bypass extracting and re-inserting an element of an input
27982   // vector. Essentially:
27983   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27984   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27985       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27986       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27987     SDValue ExtractedV = V.getOperand(0);
27988     SDValue OrigV = ExtractedV.getOperand(0);
27989     if (isNullConstant(ExtractedV.getOperand(1))) {
27990         MVT OrigVT = OrigV.getSimpleValueType();
27991         // Extract a subvector if necessary...
27992         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27993           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27994           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
27995                                     OrigVT.getVectorNumElements() / Ratio);
27996           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
27997                               DAG.getIntPtrConstant(0, DL));
27998         }
27999         Op = DAG.getBitcast(OpVT, OrigV);
28000         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
28001       }
28002   }
28003
28004   return SDValue();
28005 }
28006
28007 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
28008                                              DAGCombinerInfo &DCI) const {
28009   SelectionDAG &DAG = DCI.DAG;
28010   switch (N->getOpcode()) {
28011   default: break;
28012   case ISD::EXTRACT_VECTOR_ELT:
28013     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
28014   case ISD::VSELECT:
28015   case ISD::SELECT:
28016   case X86ISD::SHRUNKBLEND:
28017     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
28018   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
28019   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
28020   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
28021   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
28022   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
28023   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
28024   case ISD::SHL:
28025   case ISD::SRA:
28026   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
28027   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
28028   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
28029   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
28030   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
28031   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
28032   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
28033   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
28034   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
28035   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
28036   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
28037   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
28038   case ISD::FNEG:           return PerformFNEGCombine(N, DAG, Subtarget);
28039   case ISD::TRUNCATE:       return PerformTRUNCATECombine(N, DAG, Subtarget);
28040   case X86ISD::FXOR:
28041   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
28042   case X86ISD::FMIN:
28043   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
28044   case ISD::FMINNUM:
28045   case ISD::FMAXNUM:        return performFMinNumFMaxNumCombine(N, DAG,
28046                                                                 Subtarget);
28047   case X86ISD::FAND:        return PerformFANDCombine(N, DAG, Subtarget);
28048   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG, Subtarget);
28049   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
28050   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
28051   case ISD::ANY_EXTEND:
28052   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
28053   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
28054   case ISD::SIGN_EXTEND_INREG:
28055     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
28056   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
28057   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
28058   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
28059   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
28060   case X86ISD::SHUFP:       // Handle all target specific shuffles
28061   case X86ISD::PALIGNR:
28062   case X86ISD::BLENDI:
28063   case X86ISD::UNPCKH:
28064   case X86ISD::UNPCKL:
28065   case X86ISD::MOVHLPS:
28066   case X86ISD::MOVLHPS:
28067   case X86ISD::PSHUFB:
28068   case X86ISD::PSHUFD:
28069   case X86ISD::PSHUFHW:
28070   case X86ISD::PSHUFLW:
28071   case X86ISD::MOVSS:
28072   case X86ISD::MOVSD:
28073   case X86ISD::VPERMILPI:
28074   case X86ISD::VPERM2X128:
28075   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
28076   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
28077   case ISD::MGATHER:
28078   case ISD::MSCATTER:       return PerformGatherScatterCombine(N, DAG);
28079   }
28080
28081   return SDValue();
28082 }
28083
28084 /// isTypeDesirableForOp - Return true if the target has native support for
28085 /// the specified value type and it is 'desirable' to use the type for the
28086 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
28087 /// instruction encodings are longer and some i16 instructions are slow.
28088 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
28089   if (!isTypeLegal(VT))
28090     return false;
28091   if (VT != MVT::i16)
28092     return true;
28093
28094   switch (Opc) {
28095   default:
28096     return true;
28097   case ISD::LOAD:
28098   case ISD::SIGN_EXTEND:
28099   case ISD::ZERO_EXTEND:
28100   case ISD::ANY_EXTEND:
28101   case ISD::SHL:
28102   case ISD::SRL:
28103   case ISD::SUB:
28104   case ISD::ADD:
28105   case ISD::MUL:
28106   case ISD::AND:
28107   case ISD::OR:
28108   case ISD::XOR:
28109     return false;
28110   }
28111 }
28112
28113 /// This function checks if any of the users of EFLAGS copies the EFLAGS. We
28114 /// know that the code that lowers COPY of EFLAGS has to use the stack, and if
28115 /// we don't adjust the stack we clobber the first frame index.
28116 /// See X86InstrInfo::copyPhysReg.
28117 bool X86TargetLowering::hasCopyImplyingStackAdjustment(
28118     MachineFunction *MF) const {
28119   const MachineRegisterInfo &MRI = MF->getRegInfo();
28120
28121   return any_of(MRI.reg_instructions(X86::EFLAGS),
28122                 [](const MachineInstr &RI) { return RI.isCopy(); });
28123 }
28124
28125 /// IsDesirableToPromoteOp - This method query the target whether it is
28126 /// beneficial for dag combiner to promote the specified node. If true, it
28127 /// should return the desired promotion type by reference.
28128 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
28129   EVT VT = Op.getValueType();
28130   if (VT != MVT::i16)
28131     return false;
28132
28133   bool Promote = false;
28134   bool Commute = false;
28135   switch (Op.getOpcode()) {
28136   default: break;
28137   case ISD::LOAD: {
28138     LoadSDNode *LD = cast<LoadSDNode>(Op);
28139     // If the non-extending load has a single use and it's not live out, then it
28140     // might be folded.
28141     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
28142                                                      Op.hasOneUse()*/) {
28143       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
28144              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
28145         // The only case where we'd want to promote LOAD (rather then it being
28146         // promoted as an operand is when it's only use is liveout.
28147         if (UI->getOpcode() != ISD::CopyToReg)
28148           return false;
28149       }
28150     }
28151     Promote = true;
28152     break;
28153   }
28154   case ISD::SIGN_EXTEND:
28155   case ISD::ZERO_EXTEND:
28156   case ISD::ANY_EXTEND:
28157     Promote = true;
28158     break;
28159   case ISD::SHL:
28160   case ISD::SRL: {
28161     SDValue N0 = Op.getOperand(0);
28162     // Look out for (store (shl (load), x)).
28163     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
28164       return false;
28165     Promote = true;
28166     break;
28167   }
28168   case ISD::ADD:
28169   case ISD::MUL:
28170   case ISD::AND:
28171   case ISD::OR:
28172   case ISD::XOR:
28173     Commute = true;
28174     // fallthrough
28175   case ISD::SUB: {
28176     SDValue N0 = Op.getOperand(0);
28177     SDValue N1 = Op.getOperand(1);
28178     if (!Commute && MayFoldLoad(N1))
28179       return false;
28180     // Avoid disabling potential load folding opportunities.
28181     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
28182       return false;
28183     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
28184       return false;
28185     Promote = true;
28186   }
28187   }
28188
28189   PVT = MVT::i32;
28190   return Promote;
28191 }
28192
28193 //===----------------------------------------------------------------------===//
28194 //                           X86 Inline Assembly Support
28195 //===----------------------------------------------------------------------===//
28196
28197 // Helper to match a string separated by whitespace.
28198 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
28199   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
28200
28201   for (StringRef Piece : Pieces) {
28202     if (!S.startswith(Piece)) // Check if the piece matches.
28203       return false;
28204
28205     S = S.substr(Piece.size());
28206     StringRef::size_type Pos = S.find_first_not_of(" \t");
28207     if (Pos == 0) // We matched a prefix.
28208       return false;
28209
28210     S = S.substr(Pos);
28211   }
28212
28213   return S.empty();
28214 }
28215
28216 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
28217
28218   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
28219     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
28220         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
28221         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
28222
28223       if (AsmPieces.size() == 3)
28224         return true;
28225       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
28226         return true;
28227     }
28228   }
28229   return false;
28230 }
28231
28232 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
28233   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
28234
28235   std::string AsmStr = IA->getAsmString();
28236
28237   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
28238   if (!Ty || Ty->getBitWidth() % 16 != 0)
28239     return false;
28240
28241   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
28242   SmallVector<StringRef, 4> AsmPieces;
28243   SplitString(AsmStr, AsmPieces, ";\n");
28244
28245   switch (AsmPieces.size()) {
28246   default: return false;
28247   case 1:
28248     // FIXME: this should verify that we are targeting a 486 or better.  If not,
28249     // we will turn this bswap into something that will be lowered to logical
28250     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
28251     // lower so don't worry about this.
28252     // bswap $0
28253     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
28254         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
28255         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
28256         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
28257         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
28258         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
28259       // No need to check constraints, nothing other than the equivalent of
28260       // "=r,0" would be valid here.
28261       return IntrinsicLowering::LowerToByteSwap(CI);
28262     }
28263
28264     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
28265     if (CI->getType()->isIntegerTy(16) &&
28266         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28267         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
28268          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
28269       AsmPieces.clear();
28270       StringRef ConstraintsStr = IA->getConstraintString();
28271       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28272       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28273       if (clobbersFlagRegisters(AsmPieces))
28274         return IntrinsicLowering::LowerToByteSwap(CI);
28275     }
28276     break;
28277   case 3:
28278     if (CI->getType()->isIntegerTy(32) &&
28279         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28280         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
28281         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
28282         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
28283       AsmPieces.clear();
28284       StringRef ConstraintsStr = IA->getConstraintString();
28285       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28286       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28287       if (clobbersFlagRegisters(AsmPieces))
28288         return IntrinsicLowering::LowerToByteSwap(CI);
28289     }
28290
28291     if (CI->getType()->isIntegerTy(64)) {
28292       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
28293       if (Constraints.size() >= 2 &&
28294           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
28295           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
28296         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
28297         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
28298             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
28299             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
28300           return IntrinsicLowering::LowerToByteSwap(CI);
28301       }
28302     }
28303     break;
28304   }
28305   return false;
28306 }
28307
28308 /// getConstraintType - Given a constraint letter, return the type of
28309 /// constraint it is for this target.
28310 X86TargetLowering::ConstraintType
28311 X86TargetLowering::getConstraintType(StringRef Constraint) const {
28312   if (Constraint.size() == 1) {
28313     switch (Constraint[0]) {
28314     case 'R':
28315     case 'q':
28316     case 'Q':
28317     case 'f':
28318     case 't':
28319     case 'u':
28320     case 'y':
28321     case 'x':
28322     case 'Y':
28323     case 'l':
28324       return C_RegisterClass;
28325     case 'a':
28326     case 'b':
28327     case 'c':
28328     case 'd':
28329     case 'S':
28330     case 'D':
28331     case 'A':
28332       return C_Register;
28333     case 'I':
28334     case 'J':
28335     case 'K':
28336     case 'L':
28337     case 'M':
28338     case 'N':
28339     case 'G':
28340     case 'C':
28341     case 'e':
28342     case 'Z':
28343       return C_Other;
28344     default:
28345       break;
28346     }
28347   }
28348   return TargetLowering::getConstraintType(Constraint);
28349 }
28350
28351 /// Examine constraint type and operand type and determine a weight value.
28352 /// This object must already have been set up with the operand type
28353 /// and the current alternative constraint selected.
28354 TargetLowering::ConstraintWeight
28355   X86TargetLowering::getSingleConstraintMatchWeight(
28356     AsmOperandInfo &info, const char *constraint) const {
28357   ConstraintWeight weight = CW_Invalid;
28358   Value *CallOperandVal = info.CallOperandVal;
28359     // If we don't have a value, we can't do a match,
28360     // but allow it at the lowest weight.
28361   if (!CallOperandVal)
28362     return CW_Default;
28363   Type *type = CallOperandVal->getType();
28364   // Look at the constraint type.
28365   switch (*constraint) {
28366   default:
28367     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
28368   case 'R':
28369   case 'q':
28370   case 'Q':
28371   case 'a':
28372   case 'b':
28373   case 'c':
28374   case 'd':
28375   case 'S':
28376   case 'D':
28377   case 'A':
28378     if (CallOperandVal->getType()->isIntegerTy())
28379       weight = CW_SpecificReg;
28380     break;
28381   case 'f':
28382   case 't':
28383   case 'u':
28384     if (type->isFloatingPointTy())
28385       weight = CW_SpecificReg;
28386     break;
28387   case 'y':
28388     if (type->isX86_MMXTy() && Subtarget->hasMMX())
28389       weight = CW_SpecificReg;
28390     break;
28391   case 'x':
28392   case 'Y':
28393     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
28394         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
28395       weight = CW_Register;
28396     break;
28397   case 'I':
28398     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
28399       if (C->getZExtValue() <= 31)
28400         weight = CW_Constant;
28401     }
28402     break;
28403   case 'J':
28404     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28405       if (C->getZExtValue() <= 63)
28406         weight = CW_Constant;
28407     }
28408     break;
28409   case 'K':
28410     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28411       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
28412         weight = CW_Constant;
28413     }
28414     break;
28415   case 'L':
28416     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28417       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
28418         weight = CW_Constant;
28419     }
28420     break;
28421   case 'M':
28422     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28423       if (C->getZExtValue() <= 3)
28424         weight = CW_Constant;
28425     }
28426     break;
28427   case 'N':
28428     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28429       if (C->getZExtValue() <= 0xff)
28430         weight = CW_Constant;
28431     }
28432     break;
28433   case 'G':
28434   case 'C':
28435     if (isa<ConstantFP>(CallOperandVal)) {
28436       weight = CW_Constant;
28437     }
28438     break;
28439   case 'e':
28440     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28441       if ((C->getSExtValue() >= -0x80000000LL) &&
28442           (C->getSExtValue() <= 0x7fffffffLL))
28443         weight = CW_Constant;
28444     }
28445     break;
28446   case 'Z':
28447     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28448       if (C->getZExtValue() <= 0xffffffff)
28449         weight = CW_Constant;
28450     }
28451     break;
28452   }
28453   return weight;
28454 }
28455
28456 /// LowerXConstraint - try to replace an X constraint, which matches anything,
28457 /// with another that has more specific requirements based on the type of the
28458 /// corresponding operand.
28459 const char *X86TargetLowering::
28460 LowerXConstraint(EVT ConstraintVT) const {
28461   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
28462   // 'f' like normal targets.
28463   if (ConstraintVT.isFloatingPoint()) {
28464     if (Subtarget->hasSSE2())
28465       return "Y";
28466     if (Subtarget->hasSSE1())
28467       return "x";
28468   }
28469
28470   return TargetLowering::LowerXConstraint(ConstraintVT);
28471 }
28472
28473 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
28474 /// vector.  If it is invalid, don't add anything to Ops.
28475 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
28476                                                      std::string &Constraint,
28477                                                      std::vector<SDValue>&Ops,
28478                                                      SelectionDAG &DAG) const {
28479   SDValue Result;
28480
28481   // Only support length 1 constraints for now.
28482   if (Constraint.length() > 1) return;
28483
28484   char ConstraintLetter = Constraint[0];
28485   switch (ConstraintLetter) {
28486   default: break;
28487   case 'I':
28488     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28489       if (C->getZExtValue() <= 31) {
28490         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28491                                        Op.getValueType());
28492         break;
28493       }
28494     }
28495     return;
28496   case 'J':
28497     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28498       if (C->getZExtValue() <= 63) {
28499         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28500                                        Op.getValueType());
28501         break;
28502       }
28503     }
28504     return;
28505   case 'K':
28506     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28507       if (isInt<8>(C->getSExtValue())) {
28508         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28509                                        Op.getValueType());
28510         break;
28511       }
28512     }
28513     return;
28514   case 'L':
28515     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28516       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
28517           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
28518         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
28519                                        Op.getValueType());
28520         break;
28521       }
28522     }
28523     return;
28524   case 'M':
28525     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28526       if (C->getZExtValue() <= 3) {
28527         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28528                                        Op.getValueType());
28529         break;
28530       }
28531     }
28532     return;
28533   case 'N':
28534     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28535       if (C->getZExtValue() <= 255) {
28536         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28537                                        Op.getValueType());
28538         break;
28539       }
28540     }
28541     return;
28542   case 'O':
28543     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28544       if (C->getZExtValue() <= 127) {
28545         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28546                                        Op.getValueType());
28547         break;
28548       }
28549     }
28550     return;
28551   case 'e': {
28552     // 32-bit signed value
28553     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28554       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28555                                            C->getSExtValue())) {
28556         // Widen to 64 bits here to get it sign extended.
28557         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
28558         break;
28559       }
28560     // FIXME gcc accepts some relocatable values here too, but only in certain
28561     // memory models; it's complicated.
28562     }
28563     return;
28564   }
28565   case 'Z': {
28566     // 32-bit unsigned value
28567     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28568       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28569                                            C->getZExtValue())) {
28570         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28571                                        Op.getValueType());
28572         break;
28573       }
28574     }
28575     // FIXME gcc accepts some relocatable values here too, but only in certain
28576     // memory models; it's complicated.
28577     return;
28578   }
28579   case 'i': {
28580     // Literal immediates are always ok.
28581     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
28582       // Widen to 64 bits here to get it sign extended.
28583       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
28584       break;
28585     }
28586
28587     // In any sort of PIC mode addresses need to be computed at runtime by
28588     // adding in a register or some sort of table lookup.  These can't
28589     // be used as immediates.
28590     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
28591       return;
28592
28593     // If we are in non-pic codegen mode, we allow the address of a global (with
28594     // an optional displacement) to be used with 'i'.
28595     GlobalAddressSDNode *GA = nullptr;
28596     int64_t Offset = 0;
28597
28598     // Match either (GA), (GA+C), (GA+C1+C2), etc.
28599     while (1) {
28600       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
28601         Offset += GA->getOffset();
28602         break;
28603       } else if (Op.getOpcode() == ISD::ADD) {
28604         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28605           Offset += C->getZExtValue();
28606           Op = Op.getOperand(0);
28607           continue;
28608         }
28609       } else if (Op.getOpcode() == ISD::SUB) {
28610         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28611           Offset += -C->getZExtValue();
28612           Op = Op.getOperand(0);
28613           continue;
28614         }
28615       }
28616
28617       // Otherwise, this isn't something we can handle, reject it.
28618       return;
28619     }
28620
28621     const GlobalValue *GV = GA->getGlobal();
28622     // If we require an extra load to get this address, as in PIC mode, we
28623     // can't accept it.
28624     if (isGlobalStubReference(
28625             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
28626       return;
28627
28628     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
28629                                         GA->getValueType(0), Offset);
28630     break;
28631   }
28632   }
28633
28634   if (Result.getNode()) {
28635     Ops.push_back(Result);
28636     return;
28637   }
28638   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
28639 }
28640
28641 std::pair<unsigned, const TargetRegisterClass *>
28642 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
28643                                                 StringRef Constraint,
28644                                                 MVT VT) const {
28645   // First, see if this is a constraint that directly corresponds to an LLVM
28646   // register class.
28647   if (Constraint.size() == 1) {
28648     // GCC Constraint Letters
28649     switch (Constraint[0]) {
28650     default: break;
28651       // TODO: Slight differences here in allocation order and leaving
28652       // RIP in the class. Do they matter any more here than they do
28653       // in the normal allocation?
28654     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
28655       if (Subtarget->is64Bit()) {
28656         if (VT == MVT::i32 || VT == MVT::f32)
28657           return std::make_pair(0U, &X86::GR32RegClass);
28658         if (VT == MVT::i16)
28659           return std::make_pair(0U, &X86::GR16RegClass);
28660         if (VT == MVT::i8 || VT == MVT::i1)
28661           return std::make_pair(0U, &X86::GR8RegClass);
28662         if (VT == MVT::i64 || VT == MVT::f64)
28663           return std::make_pair(0U, &X86::GR64RegClass);
28664         break;
28665       }
28666       // 32-bit fallthrough
28667     case 'Q':   // Q_REGS
28668       if (VT == MVT::i32 || VT == MVT::f32)
28669         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
28670       if (VT == MVT::i16)
28671         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
28672       if (VT == MVT::i8 || VT == MVT::i1)
28673         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
28674       if (VT == MVT::i64)
28675         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
28676       break;
28677     case 'r':   // GENERAL_REGS
28678     case 'l':   // INDEX_REGS
28679       if (VT == MVT::i8 || VT == MVT::i1)
28680         return std::make_pair(0U, &X86::GR8RegClass);
28681       if (VT == MVT::i16)
28682         return std::make_pair(0U, &X86::GR16RegClass);
28683       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
28684         return std::make_pair(0U, &X86::GR32RegClass);
28685       return std::make_pair(0U, &X86::GR64RegClass);
28686     case 'R':   // LEGACY_REGS
28687       if (VT == MVT::i8 || VT == MVT::i1)
28688         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
28689       if (VT == MVT::i16)
28690         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
28691       if (VT == MVT::i32 || !Subtarget->is64Bit())
28692         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
28693       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
28694     case 'f':  // FP Stack registers.
28695       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
28696       // value to the correct fpstack register class.
28697       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
28698         return std::make_pair(0U, &X86::RFP32RegClass);
28699       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
28700         return std::make_pair(0U, &X86::RFP64RegClass);
28701       return std::make_pair(0U, &X86::RFP80RegClass);
28702     case 'y':   // MMX_REGS if MMX allowed.
28703       if (!Subtarget->hasMMX()) break;
28704       return std::make_pair(0U, &X86::VR64RegClass);
28705     case 'Y':   // SSE_REGS if SSE2 allowed
28706       if (!Subtarget->hasSSE2()) break;
28707       // FALL THROUGH.
28708     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
28709       if (!Subtarget->hasSSE1()) break;
28710
28711       switch (VT.SimpleTy) {
28712       default: break;
28713       // Scalar SSE types.
28714       case MVT::f32:
28715       case MVT::i32:
28716         return std::make_pair(0U, &X86::FR32RegClass);
28717       case MVT::f64:
28718       case MVT::i64:
28719         return std::make_pair(0U, &X86::FR64RegClass);
28720       // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28721       // Vector types.
28722       case MVT::v16i8:
28723       case MVT::v8i16:
28724       case MVT::v4i32:
28725       case MVT::v2i64:
28726       case MVT::v4f32:
28727       case MVT::v2f64:
28728         return std::make_pair(0U, &X86::VR128RegClass);
28729       // AVX types.
28730       case MVT::v32i8:
28731       case MVT::v16i16:
28732       case MVT::v8i32:
28733       case MVT::v4i64:
28734       case MVT::v8f32:
28735       case MVT::v4f64:
28736         return std::make_pair(0U, &X86::VR256RegClass);
28737       case MVT::v8f64:
28738       case MVT::v16f32:
28739       case MVT::v16i32:
28740       case MVT::v8i64:
28741         return std::make_pair(0U, &X86::VR512RegClass);
28742       }
28743       break;
28744     }
28745   }
28746
28747   // Use the default implementation in TargetLowering to convert the register
28748   // constraint into a member of a register class.
28749   std::pair<unsigned, const TargetRegisterClass*> Res;
28750   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28751
28752   // Not found as a standard register?
28753   if (!Res.second) {
28754     // Map st(0) -> st(7) -> ST0
28755     if (Constraint.size() == 7 && Constraint[0] == '{' &&
28756         tolower(Constraint[1]) == 's' &&
28757         tolower(Constraint[2]) == 't' &&
28758         Constraint[3] == '(' &&
28759         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28760         Constraint[5] == ')' &&
28761         Constraint[6] == '}') {
28762
28763       Res.first = X86::FP0+Constraint[4]-'0';
28764       Res.second = &X86::RFP80RegClass;
28765       return Res;
28766     }
28767
28768     // GCC allows "st(0)" to be called just plain "st".
28769     if (StringRef("{st}").equals_lower(Constraint)) {
28770       Res.first = X86::FP0;
28771       Res.second = &X86::RFP80RegClass;
28772       return Res;
28773     }
28774
28775     // flags -> EFLAGS
28776     if (StringRef("{flags}").equals_lower(Constraint)) {
28777       Res.first = X86::EFLAGS;
28778       Res.second = &X86::CCRRegClass;
28779       return Res;
28780     }
28781
28782     // 'A' means EAX + EDX.
28783     if (Constraint == "A") {
28784       Res.first = X86::EAX;
28785       Res.second = &X86::GR32_ADRegClass;
28786       return Res;
28787     }
28788     return Res;
28789   }
28790
28791   // Otherwise, check to see if this is a register class of the wrong value
28792   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28793   // turn into {ax},{dx}.
28794   // MVT::Other is used to specify clobber names.
28795   if (Res.second->hasType(VT) || VT == MVT::Other)
28796     return Res;   // Correct type already, nothing to do.
28797
28798   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28799   // return "eax". This should even work for things like getting 64bit integer
28800   // registers when given an f64 type.
28801   const TargetRegisterClass *Class = Res.second;
28802   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28803       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28804     unsigned Size = VT.getSizeInBits();
28805     if (Size == 1) Size = 8;
28806     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
28807     if (DestReg > 0) {
28808       Res.first = DestReg;
28809       Res.second = Size == 8 ? &X86::GR8RegClass
28810                  : Size == 16 ? &X86::GR16RegClass
28811                  : Size == 32 ? &X86::GR32RegClass
28812                  : &X86::GR64RegClass;
28813       assert(Res.second->contains(Res.first) && "Register in register class");
28814     } else {
28815       // No register found/type mismatch.
28816       Res.first = 0;
28817       Res.second = nullptr;
28818     }
28819   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28820              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28821              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28822              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28823              Class == &X86::VR512RegClass) {
28824     // Handle references to XMM physical registers that got mapped into the
28825     // wrong class.  This can happen with constraints like {xmm0} where the
28826     // target independent register mapper will just pick the first match it can
28827     // find, ignoring the required type.
28828
28829     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28830     if (VT == MVT::f32 || VT == MVT::i32)
28831       Res.second = &X86::FR32RegClass;
28832     else if (VT == MVT::f64 || VT == MVT::i64)
28833       Res.second = &X86::FR64RegClass;
28834     else if (X86::VR128RegClass.hasType(VT))
28835       Res.second = &X86::VR128RegClass;
28836     else if (X86::VR256RegClass.hasType(VT))
28837       Res.second = &X86::VR256RegClass;
28838     else if (X86::VR512RegClass.hasType(VT))
28839       Res.second = &X86::VR512RegClass;
28840     else {
28841       // Type mismatch and not a clobber: Return an error;
28842       Res.first = 0;
28843       Res.second = nullptr;
28844     }
28845   }
28846
28847   return Res;
28848 }
28849
28850 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28851                                             const AddrMode &AM, Type *Ty,
28852                                             unsigned AS) const {
28853   // Scaling factors are not free at all.
28854   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28855   // will take 2 allocations in the out of order engine instead of 1
28856   // for plain addressing mode, i.e. inst (reg1).
28857   // E.g.,
28858   // vaddps (%rsi,%drx), %ymm0, %ymm1
28859   // Requires two allocations (one for the load, one for the computation)
28860   // whereas:
28861   // vaddps (%rsi), %ymm0, %ymm1
28862   // Requires just 1 allocation, i.e., freeing allocations for other operations
28863   // and having less micro operations to execute.
28864   //
28865   // For some X86 architectures, this is even worse because for instance for
28866   // stores, the complex addressing mode forces the instruction to use the
28867   // "load" ports instead of the dedicated "store" port.
28868   // E.g., on Haswell:
28869   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28870   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28871   if (isLegalAddressingMode(DL, AM, Ty, AS))
28872     // Scale represents reg2 * scale, thus account for 1
28873     // as soon as we use a second register.
28874     return AM.Scale != 0;
28875   return -1;
28876 }
28877
28878 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28879   // Integer division on x86 is expensive. However, when aggressively optimizing
28880   // for code size, we prefer to use a div instruction, as it is usually smaller
28881   // than the alternative sequence.
28882   // The exception to this is vector division. Since x86 doesn't have vector
28883   // integer division, leaving the division as-is is a loss even in terms of
28884   // size, because it will have to be scalarized, while the alternative code
28885   // sequence can be performed in vector form.
28886   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28887                                    Attribute::MinSize);
28888   return OptSize && !VT.isVector();
28889 }
28890
28891 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
28892   if (!Subtarget->is64Bit())
28893     return;
28894
28895   // Update IsSplitCSR in X86MachineFunctionInfo.
28896   X86MachineFunctionInfo *AFI =
28897     Entry->getParent()->getInfo<X86MachineFunctionInfo>();
28898   AFI->setIsSplitCSR(true);
28899 }
28900
28901 void X86TargetLowering::insertCopiesSplitCSR(
28902     MachineBasicBlock *Entry,
28903     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
28904   const X86RegisterInfo *TRI = Subtarget->getRegisterInfo();
28905   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
28906   if (!IStart)
28907     return;
28908
28909   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
28910   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
28911   MachineBasicBlock::iterator MBBI = Entry->begin();
28912   for (const MCPhysReg *I = IStart; *I; ++I) {
28913     const TargetRegisterClass *RC = nullptr;
28914     if (X86::GR64RegClass.contains(*I))
28915       RC = &X86::GR64RegClass;
28916     else
28917       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
28918
28919     unsigned NewVR = MRI->createVirtualRegister(RC);
28920     // Create copy from CSR to a virtual register.
28921     // FIXME: this currently does not emit CFI pseudo-instructions, it works
28922     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
28923     // nounwind. If we want to generalize this later, we may need to emit
28924     // CFI pseudo-instructions.
28925     assert(Entry->getParent()->getFunction()->hasFnAttribute(
28926                Attribute::NoUnwind) &&
28927            "Function should be nounwind in insertCopiesSplitCSR!");
28928     Entry->addLiveIn(*I);
28929     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
28930         .addReg(*I);
28931
28932     // Insert the copy-back instructions right before the terminator.
28933     for (auto *Exit : Exits)
28934       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
28935               TII->get(TargetOpcode::COPY), *I)
28936           .addReg(NewVR);
28937   }
28938 }