X86: Fixed assertion failure in 32-bit mode
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 // Forward declarations.
71 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
72                        SDValue V2);
73
74 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
75                                      const X86Subtarget &STI)
76     : TargetLowering(TM), Subtarget(&STI) {
77   X86ScalarSSEf64 = Subtarget->hasSSE2();
78   X86ScalarSSEf32 = Subtarget->hasSSE1();
79   TD = TM.getDataLayout();
80
81   // Set up the TargetLowering object.
82   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
83
84   // X86 is weird. It always uses i8 for shift amounts and setcc results.
85   setBooleanContents(ZeroOrOneBooleanContent);
86   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
87   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
88
89   // For 64-bit, since we have so many registers, use the ILP scheduler.
90   // For 32-bit, use the register pressure specific scheduling.
91   // For Atom, always use ILP scheduling.
92   if (Subtarget->isAtom())
93     setSchedulingPreference(Sched::ILP);
94   else if (Subtarget->is64Bit())
95     setSchedulingPreference(Sched::ILP);
96   else
97     setSchedulingPreference(Sched::RegPressure);
98   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
99   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
100
101   // Bypass expensive divides on Atom when compiling with O2.
102   if (TM.getOptLevel() >= CodeGenOpt::Default) {
103     if (Subtarget->hasSlowDivide32())
104       addBypassSlowDiv(32, 8);
105     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
106       addBypassSlowDiv(64, 16);
107   }
108
109   if (Subtarget->isTargetKnownWindowsMSVC()) {
110     // Setup Windows compiler runtime calls.
111     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
112     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
113     setLibcallName(RTLIB::SREM_I64, "_allrem");
114     setLibcallName(RTLIB::UREM_I64, "_aullrem");
115     setLibcallName(RTLIB::MUL_I64, "_allmul");
116     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
117     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
118     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
119     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
120     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
121
122     // The _ftol2 runtime function has an unusual calling conv, which
123     // is modeled by a special pseudo-instruction.
124     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
125     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
126     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
127     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
128   }
129
130   if (Subtarget->isTargetDarwin()) {
131     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
132     setUseUnderscoreSetJmp(false);
133     setUseUnderscoreLongJmp(false);
134   } else if (Subtarget->isTargetWindowsGNU()) {
135     // MS runtime is weird: it exports _setjmp, but longjmp!
136     setUseUnderscoreSetJmp(true);
137     setUseUnderscoreLongJmp(false);
138   } else {
139     setUseUnderscoreSetJmp(true);
140     setUseUnderscoreLongJmp(true);
141   }
142
143   // Set up the register classes.
144   addRegisterClass(MVT::i8, &X86::GR8RegClass);
145   addRegisterClass(MVT::i16, &X86::GR16RegClass);
146   addRegisterClass(MVT::i32, &X86::GR32RegClass);
147   if (Subtarget->is64Bit())
148     addRegisterClass(MVT::i64, &X86::GR64RegClass);
149
150   for (MVT VT : MVT::integer_valuetypes())
151     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
152
153   // We don't accept any truncstore of integer registers.
154   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
155   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
156   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
157   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
158   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
159   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
160
161   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
162
163   // SETOEQ and SETUNE require checking two conditions.
164   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
165   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
166   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
167   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
168   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
169   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
170
171   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
172   // operation.
173   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
174   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
175   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
176
177   if (Subtarget->is64Bit()) {
178     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
180   } else if (!Subtarget->useSoftFloat()) {
181     // We have an algorithm for SSE2->double, and we turn this into a
182     // 64-bit FILD followed by conditional FADD for other targets.
183     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
184     // We have an algorithm for SSE2, and we turn this into a 64-bit
185     // FILD for other targets.
186     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
187   }
188
189   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
190   // this operation.
191   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
192   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
193
194   if (!Subtarget->useSoftFloat()) {
195     // SSE has no i16 to fp conversion, only i32
196     if (X86ScalarSSEf32) {
197       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
198       // f32 and f64 cases are Legal, f80 case is not
199       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
200     } else {
201       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
202       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
203     }
204   } else {
205     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
206     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
207   }
208
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   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
215   // this operation.
216   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
217   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
218
219   if (X86ScalarSSEf32) {
220     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
221     // f32 and f64 cases are Legal, f80 case is not
222     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
223   } else {
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
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     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
236     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
237   } else if (!Subtarget->useSoftFloat()) {
238     // Since AVX is a superset of SSE3, only check for SSE here.
239     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
240       // Expand FP_TO_UINT into a select.
241       // FIXME: We would like to use a Custom expander here eventually to do
242       // the optimal thing for SSE vs. the default expansion in the legalizer.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
244     else
245       // With SSE3 we can use fisttpll to convert to a signed i64; without
246       // SSE, we're stuck with a fistpll.
247       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
248   }
249
250   if (isTargetFTOL()) {
251     // Use the _ftol2 runtime function, which has a pseudo-instruction
252     // to handle its weird calling convention.
253     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
254   }
255
256   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
257   if (!X86ScalarSSEf64) {
258     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
259     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
260     if (Subtarget->is64Bit()) {
261       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
262       // Without SSE, i64->f64 goes through memory.
263       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
264     }
265   }
266
267   // Scalar integer divide and remainder are lowered to use operations that
268   // produce two results, to match the available instructions. This exposes
269   // the two-result form to trivial CSE, which is able to combine x/y and x%y
270   // into a single instruction.
271   //
272   // Scalar integer multiply-high is also lowered to use two-result
273   // operations, to match the available instructions. However, plain multiply
274   // (low) operations are left as Legal, as there are single-result
275   // instructions for this in x86. Using the two-result multiply instructions
276   // when both high and low results are needed must be arranged by dagcombine.
277   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
278     MVT VT = IntVTs[i];
279     setOperationAction(ISD::MULHS, VT, Expand);
280     setOperationAction(ISD::MULHU, VT, Expand);
281     setOperationAction(ISD::SDIV, VT, Expand);
282     setOperationAction(ISD::UDIV, VT, Expand);
283     setOperationAction(ISD::SREM, VT, Expand);
284     setOperationAction(ISD::UREM, VT, Expand);
285
286     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
287     setOperationAction(ISD::ADDC, VT, Custom);
288     setOperationAction(ISD::ADDE, VT, Custom);
289     setOperationAction(ISD::SUBC, VT, Custom);
290     setOperationAction(ISD::SUBE, VT, Custom);
291   }
292
293   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
294   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
295   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
299   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
309   if (Subtarget->is64Bit())
310     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
311   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
312   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
313   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
314   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
315   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
316   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
317   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
318   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
319
320   // Promote the i8 variants and force them on up to i32 which has a shorter
321   // encoding.
322   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
323   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
324   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
325   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
326   if (Subtarget->hasBMI()) {
327     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
328     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
329     if (Subtarget->is64Bit())
330       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
331   } else {
332     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
333     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
334     if (Subtarget->is64Bit())
335       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
336   }
337
338   if (Subtarget->hasLZCNT()) {
339     // When promoting the i8 variants, force them to i32 for a shorter
340     // encoding.
341     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
342     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
343     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
344     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
346     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
347     if (Subtarget->is64Bit())
348       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
349   } else {
350     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
351     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
352     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
353     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
354     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
356     if (Subtarget->is64Bit()) {
357       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
358       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
359     }
360   }
361
362   // Special handling for half-precision floating point conversions.
363   // If we don't have F16C support, then lower half float conversions
364   // into library calls.
365   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
366     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
367     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
368   }
369
370   // There's never any support for operations beyond MVT::f32.
371   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
372   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
373   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
374   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
375
376   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
377   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
378   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
379   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
380   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
382
383   if (Subtarget->hasPOPCNT()) {
384     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
385   } else {
386     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
387     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
388     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
391   }
392
393   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
394
395   if (!Subtarget->hasMOVBE())
396     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
397
398   // These should be promoted to a larger select which is supported.
399   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
400   // X86 wants to expand cmov itself.
401   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
402   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
403   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
404   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
405   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
406   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
407   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
408   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
409   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
410   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
413   if (Subtarget->is64Bit()) {
414     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
415     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
416   }
417   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
418   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
419   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
420   // support continuation, user-level threading, and etc.. As a result, no
421   // other SjLj exception interfaces are implemented and please don't build
422   // your own exception handling based on them.
423   // LLVM/Clang supports zero-cost DWARF exception handling.
424   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
425   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
426
427   // Darwin ABI issue.
428   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
429   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
430   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
431   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
432   if (Subtarget->is64Bit())
433     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
435   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
436   if (Subtarget->is64Bit()) {
437     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
438     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
439     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
440     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
441     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
442   }
443   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
445   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
446   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
449     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
450     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
451   }
452
453   if (Subtarget->hasSSE1())
454     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
455
456   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
457
458   // Expand certain atomics
459   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
460     MVT VT = IntVTs[i];
461     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
462     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
463     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
464   }
465
466   if (Subtarget->hasCmpxchg16b()) {
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
468   }
469
470   // FIXME - use subtarget debug flags
471   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
472       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
473     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
474   }
475
476   if (Subtarget->is64Bit()) {
477     setExceptionPointerRegister(X86::RAX);
478     setExceptionSelectorRegister(X86::RDX);
479   } else {
480     setExceptionPointerRegister(X86::EAX);
481     setExceptionSelectorRegister(X86::EDX);
482   }
483   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
484   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
485
486   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
487   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
488
489   setOperationAction(ISD::TRAP, MVT::Other, Legal);
490   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
491
492   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
493   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
494   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
495   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
496     // TargetInfo::X86_64ABIBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
499   } else {
500     // TargetInfo::CharPtrBuiltinVaList
501     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
502     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
503   }
504
505   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
506   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
507
508   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(*TD), Custom);
509
510   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
511   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
512   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
513
514   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
515     // f32 and f64 use SSE.
516     // Set up the FP register classes.
517     addRegisterClass(MVT::f32, &X86::FR32RegClass);
518     addRegisterClass(MVT::f64, &X86::FR64RegClass);
519
520     // Use ANDPD to simulate FABS.
521     setOperationAction(ISD::FABS , MVT::f64, Custom);
522     setOperationAction(ISD::FABS , MVT::f32, Custom);
523
524     // Use XORP to simulate FNEG.
525     setOperationAction(ISD::FNEG , MVT::f64, Custom);
526     setOperationAction(ISD::FNEG , MVT::f32, Custom);
527
528     // Use ANDPD and ORPD to simulate FCOPYSIGN.
529     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
530     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
531
532     // Lower this to FGETSIGNx86 plus an AND.
533     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
534     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
535
536     // We don't support sin/cos/fmod
537     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
538     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
539     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
541     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
543
544     // Expand FP immediates into loads from the stack, except for the special
545     // cases we handle.
546     addLegalFPImmediate(APFloat(+0.0)); // xorpd
547     addLegalFPImmediate(APFloat(+0.0f)); // xorps
548   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
549     // Use SSE for f32, x87 for f64.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, &X86::FR32RegClass);
552     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
553
554     // Use ANDPS to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557     // Use XORP to simulate FNEG.
558     setOperationAction(ISD::FNEG , MVT::f32, Custom);
559
560     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
561
562     // Use ANDPS and ORPS to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // We don't support sin/cos/fmod
567     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
568     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
569     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
570
571     // Special cases we handle for FP constants.
572     addLegalFPImmediate(APFloat(+0.0f)); // xorps
573     addLegalFPImmediate(APFloat(+0.0)); // FLD0
574     addLegalFPImmediate(APFloat(+1.0)); // FLD1
575     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
576     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
577
578     if (!TM.Options.UnsafeFPMath) {
579       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
580       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
581       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
582     }
583   } else if (!Subtarget->useSoftFloat()) {
584     // f32 and f64 in x87.
585     // Set up the FP register classes.
586     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
588
589     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
590     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
591     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
593
594     if (!TM.Options.UnsafeFPMath) {
595       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
596       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
597       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
598       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
599       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
600       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
601     }
602     addLegalFPImmediate(APFloat(+0.0)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
607     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
608     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
609     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
610   }
611
612   // We don't support FMA.
613   setOperationAction(ISD::FMA, MVT::f64, Expand);
614   setOperationAction(ISD::FMA, MVT::f32, Expand);
615
616   // Long double always uses X87.
617   if (!Subtarget->useSoftFloat()) {
618     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
619     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
621     {
622       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
623       addLegalFPImmediate(TmpFlt);  // FLD0
624       TmpFlt.changeSign();
625       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
626
627       bool ignored;
628       APFloat TmpFlt2(+1.0);
629       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
630                       &ignored);
631       addLegalFPImmediate(TmpFlt2);  // FLD1
632       TmpFlt2.changeSign();
633       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
634     }
635
636     if (!TM.Options.UnsafeFPMath) {
637       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
638       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
639       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
640     }
641
642     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
643     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
644     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
645     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
646     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
647     setOperationAction(ISD::FMA, MVT::f80, Expand);
648   }
649
650   // Always use a library call for pow.
651   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
652   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
653   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
654
655   setOperationAction(ISD::FLOG, MVT::f80, Expand);
656   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
657   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
658   setOperationAction(ISD::FEXP, MVT::f80, Expand);
659   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
660   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
661   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
662
663   // First set operation action for all vector types to either promote
664   // (for widening) or expand (for scalarization). Then we will selectively
665   // turn on ones that can be effectively codegen'd.
666   for (MVT VT : MVT::vector_valuetypes()) {
667     setOperationAction(ISD::ADD , VT, Expand);
668     setOperationAction(ISD::SUB , VT, Expand);
669     setOperationAction(ISD::FADD, VT, Expand);
670     setOperationAction(ISD::FNEG, VT, Expand);
671     setOperationAction(ISD::FSUB, VT, Expand);
672     setOperationAction(ISD::MUL , VT, Expand);
673     setOperationAction(ISD::FMUL, VT, Expand);
674     setOperationAction(ISD::SDIV, VT, Expand);
675     setOperationAction(ISD::UDIV, VT, Expand);
676     setOperationAction(ISD::FDIV, VT, Expand);
677     setOperationAction(ISD::SREM, VT, Expand);
678     setOperationAction(ISD::UREM, VT, Expand);
679     setOperationAction(ISD::LOAD, VT, Expand);
680     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
681     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
682     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
683     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
684     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
685     setOperationAction(ISD::FABS, VT, Expand);
686     setOperationAction(ISD::FSIN, VT, Expand);
687     setOperationAction(ISD::FSINCOS, VT, Expand);
688     setOperationAction(ISD::FCOS, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FREM, VT, Expand);
691     setOperationAction(ISD::FMA,  VT, Expand);
692     setOperationAction(ISD::FPOWI, VT, Expand);
693     setOperationAction(ISD::FSQRT, VT, Expand);
694     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
695     setOperationAction(ISD::FFLOOR, VT, Expand);
696     setOperationAction(ISD::FCEIL, VT, Expand);
697     setOperationAction(ISD::FTRUNC, VT, Expand);
698     setOperationAction(ISD::FRINT, VT, Expand);
699     setOperationAction(ISD::FNEARBYINT, VT, Expand);
700     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701     setOperationAction(ISD::MULHS, VT, Expand);
702     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHU, VT, Expand);
704     setOperationAction(ISD::SDIVREM, VT, Expand);
705     setOperationAction(ISD::UDIVREM, VT, Expand);
706     setOperationAction(ISD::FPOW, VT, Expand);
707     setOperationAction(ISD::CTPOP, VT, Expand);
708     setOperationAction(ISD::CTTZ, VT, Expand);
709     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
710     setOperationAction(ISD::CTLZ, VT, Expand);
711     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::SHL, VT, Expand);
713     setOperationAction(ISD::SRA, VT, Expand);
714     setOperationAction(ISD::SRL, VT, Expand);
715     setOperationAction(ISD::ROTL, VT, Expand);
716     setOperationAction(ISD::ROTR, VT, Expand);
717     setOperationAction(ISD::BSWAP, VT, Expand);
718     setOperationAction(ISD::SETCC, VT, Expand);
719     setOperationAction(ISD::FLOG, VT, Expand);
720     setOperationAction(ISD::FLOG2, VT, Expand);
721     setOperationAction(ISD::FLOG10, VT, Expand);
722     setOperationAction(ISD::FEXP, VT, Expand);
723     setOperationAction(ISD::FEXP2, VT, Expand);
724     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
725     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
726     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
727     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
728     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
729     setOperationAction(ISD::TRUNCATE, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
731     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
732     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
733     setOperationAction(ISD::VSELECT, VT, Expand);
734     setOperationAction(ISD::SELECT_CC, VT, Expand);
735     for (MVT InnerVT : MVT::vector_valuetypes()) {
736       setTruncStoreAction(InnerVT, VT, Expand);
737
738       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
739       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
740
741       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
742       // types, we have to deal with them whether we ask for Expansion or not.
743       // Setting Expand causes its own optimisation problems though, so leave
744       // them legal.
745       if (VT.getVectorElementType() == MVT::i1)
746         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
747
748       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
749       // split/scalarized right now.
750       if (VT.getVectorElementType() == MVT::f16)
751         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
752     }
753   }
754
755   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756   // with -msoft-float, disable use of MMX as well.
757   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
758     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
759     // No operations on x86mmx supported, everything uses intrinsics.
760   }
761
762   // MMX-sized vectors (other than x86mmx) are expected to be expanded
763   // into smaller operations.
764   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
765     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
766     setOperationAction(ISD::AND,                MMXTy,      Expand);
767     setOperationAction(ISD::OR,                 MMXTy,      Expand);
768     setOperationAction(ISD::XOR,                MMXTy,      Expand);
769     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
770     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
771     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
772   }
773   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
774
775   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
776     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
777
778     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
783     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
784     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
785     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
786     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
787     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
788     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
789     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
790     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
791     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
792   }
793
794   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
795     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
796
797     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798     // registers cannot be used even for integer operations.
799     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
800     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
801     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
802     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
803
804     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
805     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
806     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
807     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
808     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
809     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
810     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
811     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
812     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
813     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
814     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
815     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
816     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
818     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
820     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
825     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
826     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
827
828     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
829     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
830     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
832
833     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
845     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
846     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
848
849     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
851       MVT VT = (MVT::SimpleValueType)i;
852       // Do not attempt to custom lower non-power-of-2 vectors
853       if (!isPowerOf2_32(VT.getVectorNumElements()))
854         continue;
855       // Do not attempt to custom lower non-128-bit vectors
856       if (!VT.is128BitVector())
857         continue;
858       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
859       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
860       setOperationAction(ISD::VSELECT,            VT, Custom);
861       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
862     }
863
864     // We support custom legalizing of sext and anyext loads for specific
865     // memory vector types which we can load as a scalar (or sequence of
866     // scalars) and extend in-register to a legal 128-bit vector type. For sext
867     // loads these must work with a single scalar load.
868     for (MVT VT : MVT::integer_vector_valuetypes()) {
869       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
870       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
871       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
878     }
879
880     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
881     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
882     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
883     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
884     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
885     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
887     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
888
889     if (Subtarget->is64Bit()) {
890       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
891       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
892     }
893
894     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
895     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896       MVT VT = (MVT::SimpleValueType)i;
897
898       // Do not attempt to promote non-128-bit vectors
899       if (!VT.is128BitVector())
900         continue;
901
902       setOperationAction(ISD::AND,    VT, Promote);
903       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
904       setOperationAction(ISD::OR,     VT, Promote);
905       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
906       setOperationAction(ISD::XOR,    VT, Promote);
907       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
908       setOperationAction(ISD::LOAD,   VT, Promote);
909       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
910       setOperationAction(ISD::SELECT, VT, Promote);
911       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
912     }
913
914     // Custom lower v2i64 and v2f64 selects.
915     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
916     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
917     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
918     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
919
920     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
921     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
922
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
924
925     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
926     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
927     // As there is no 64-bit GPR available, we need build a special custom
928     // sequence to convert from v2i32 to v2f32.
929     if (!Subtarget->is64Bit())
930       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
931
932     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
933     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
934
935     for (MVT VT : MVT::fp_vector_valuetypes())
936       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
937
938     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
939     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
940     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
941   }
942
943   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
944     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
945       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
946       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
947       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
948       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
949       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
950     }
951
952     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
953     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
954     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
955     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
957     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
958     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
959     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
960
961     // FIXME: Do we need to handle scalar-to-vector here?
962     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
963
964     // We directly match byte blends in the backend as they match the VSELECT
965     // condition form.
966     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
967
968     // SSE41 brings specific instructions for doing vector sign extend even in
969     // cases where we don't have SRA.
970     for (MVT VT : MVT::integer_vector_valuetypes()) {
971       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
972       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
974     }
975
976     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
990
991     // i8 and i16 vectors are custom because the source register and source
992     // source memory operand types are not the same width.  f32 vectors are
993     // custom since the immediate controlling the insert encodes additional
994     // information.
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1001     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1004
1005     // FIXME: these should be Legal, but that's only for the case where
1006     // the index is constant.  For now custom expand to deal with that.
1007     if (Subtarget->is64Bit()) {
1008       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1009       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1010     }
1011   }
1012
1013   if (Subtarget->hasSSE2()) {
1014     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1015     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1017
1018     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1026
1027     // In the customized shift lowering, the legal cases in AVX2 will be
1028     // recognized.
1029     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1030     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1031
1032     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1033     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1034
1035     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1036     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1037   }
1038
1039   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1040     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1042     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1043     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1044     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1045     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1046
1047     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1049     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1050
1051     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1052     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1053     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1054     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1056     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1057     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1058     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1059     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1060     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1061     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1062     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1063
1064     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1065     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1066     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1067     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1074     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1075     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1076
1077     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1078     // even though v8i16 is a legal type.
1079     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1080     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1081     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1082
1083     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1084     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1085     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1086
1087     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1088     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1089
1090     for (MVT VT : MVT::fp_vector_valuetypes())
1091       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1092
1093     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1094     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1095
1096     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1097     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1098
1099     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1100     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1101
1102     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1103     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1104     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1105     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1106
1107     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1108     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1109     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1110
1111     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1112     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1113     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1114     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1115     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1116     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1117     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1118     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1119     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1120     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1121     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1122     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1123
1124     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1125     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1126     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1127     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1128
1129     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1130       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1132       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1133       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1134       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1135       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1136     }
1137
1138     if (Subtarget->hasInt256()) {
1139       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1140       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1141       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1142       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1143
1144       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1145       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1146       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1147       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1148
1149       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1150       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1151       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1152       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1153
1154       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1155       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1156       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1157       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1158
1159       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1160       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1161       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1162       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1163       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1164       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1165       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1166       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1167       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1168       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1169       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1170       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1171
1172       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1173       // when we have a 256bit-wide blend with immediate.
1174       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1175
1176       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1177       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1178       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1179       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1182       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1183
1184       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1185       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1186       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1189       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1190     } else {
1191       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1192       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1193       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1194       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1195
1196       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1197       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1198       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1199       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1200
1201       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1202       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1203       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1204       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1205     }
1206
1207     // In the customized shift lowering, the legal cases in AVX2 will be
1208     // recognized.
1209     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1210     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1211
1212     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1213     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1214
1215     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1216     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1217
1218     // Custom lower several nodes for 256-bit types.
1219     for (MVT VT : MVT::vector_valuetypes()) {
1220       if (VT.getScalarSizeInBits() >= 32) {
1221         setOperationAction(ISD::MLOAD,  VT, Legal);
1222         setOperationAction(ISD::MSTORE, VT, Legal);
1223       }
1224       // Extract subvector is special because the value type
1225       // (result) is 128-bit but the source is 256-bit wide.
1226       if (VT.is128BitVector()) {
1227         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1228       }
1229       // Do not attempt to custom lower other non-256-bit vectors
1230       if (!VT.is256BitVector())
1231         continue;
1232
1233       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1234       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1235       setOperationAction(ISD::VSELECT,            VT, Custom);
1236       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1237       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1239       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1240       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1241     }
1242
1243     if (Subtarget->hasInt256())
1244       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1245
1246
1247     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1248     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1249       MVT VT = (MVT::SimpleValueType)i;
1250
1251       // Do not attempt to promote non-256-bit vectors
1252       if (!VT.is256BitVector())
1253         continue;
1254
1255       setOperationAction(ISD::AND,    VT, Promote);
1256       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1257       setOperationAction(ISD::OR,     VT, Promote);
1258       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1259       setOperationAction(ISD::XOR,    VT, Promote);
1260       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1261       setOperationAction(ISD::LOAD,   VT, Promote);
1262       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1263       setOperationAction(ISD::SELECT, VT, Promote);
1264       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1265     }
1266   }
1267
1268   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1269     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1270     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1271     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1272     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1273
1274     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1275     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1276     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1277
1278     for (MVT VT : MVT::fp_vector_valuetypes())
1279       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1280
1281     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1282     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1283     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1284     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1285     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1286     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1287     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1288     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1289     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1290     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1291     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1292     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1293
1294     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1295     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1296     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1297     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1298     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1299     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1300     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1301     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1302     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1303     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1304     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1305     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1306     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1307
1308     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1309     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1310     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1311     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1312     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1313     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1314
1315     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1316     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1317     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1318     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1319     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1320     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1321     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1322     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1323
1324     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1325     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1326     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1327     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1328     if (Subtarget->is64Bit()) {
1329       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1330       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1331       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1332       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1333     }
1334     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1336     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1337     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1338     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1339     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1341     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1342     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1343     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1344     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1346     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1347     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1348     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1349     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1350
1351     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1352     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1353     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1354     if (Subtarget->hasDQI()) {
1355       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1356       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1357
1358       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1359       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1360       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1361       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1362       if (Subtarget->hasVLX()) {
1363         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1364         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1365         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1366         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1367         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1368         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1369         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1370         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1371       }
1372     }
1373     if (Subtarget->hasVLX()) {
1374       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1375       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1376       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1377       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1378       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1379       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1380       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1381       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1382     }
1383     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1384     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1385     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1386     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1387     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1388     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1389     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1390     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1391     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1392     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1393     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1394     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1395     if (Subtarget->hasDQI()) {
1396       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1397       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1398     }
1399     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1400     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1401     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1402     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1403     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1404     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1405     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1406     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1407     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1408     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1409
1410     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1411     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1412     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1413     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1414     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1415
1416     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1417     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1418
1419     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1420
1421     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1422     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1423     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1424     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1425     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1426     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1427     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1428     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1429     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1430     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1431     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1432
1433     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1434     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1435     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1436     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1437     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1438     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1439     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1440     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1441
1442     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1443     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1444
1445     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1446     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1447
1448     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1449
1450     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1451     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1452
1453     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1454     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1455
1456     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1457     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1458
1459     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1460     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1461     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1462     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1463     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1464     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1465
1466     if (Subtarget->hasCDI()) {
1467       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1468       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1469     }
1470     if (Subtarget->hasDQI()) {
1471       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1472       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1473       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1474     }
1475     // Custom lower several nodes.
1476     for (MVT VT : MVT::vector_valuetypes()) {
1477       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1478       if (EltSize == 1) {
1479         setOperationAction(ISD::AND, VT, Legal);
1480         setOperationAction(ISD::OR,  VT, Legal);
1481         setOperationAction(ISD::XOR,  VT, Legal);
1482       }
1483       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1484         setOperationAction(ISD::MGATHER,  VT, Custom);
1485         setOperationAction(ISD::MSCATTER, VT, Custom);
1486       }
1487       // Extract subvector is special because the value type
1488       // (result) is 256/128-bit but the source is 512-bit wide.
1489       if (VT.is128BitVector() || VT.is256BitVector()) {
1490         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1491       }
1492       if (VT.getVectorElementType() == MVT::i1)
1493         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1494
1495       // Do not attempt to custom lower other non-512-bit vectors
1496       if (!VT.is512BitVector())
1497         continue;
1498
1499       if (EltSize >= 32) {
1500         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1501         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1502         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1503         setOperationAction(ISD::VSELECT,             VT, Legal);
1504         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1505         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1506         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1507         setOperationAction(ISD::MLOAD,               VT, Legal);
1508         setOperationAction(ISD::MSTORE,              VT, Legal);
1509       }
1510     }
1511     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1512       MVT VT = (MVT::SimpleValueType)i;
1513
1514       // Do not attempt to promote non-512-bit vectors.
1515       if (!VT.is512BitVector())
1516         continue;
1517
1518       setOperationAction(ISD::SELECT, VT, Promote);
1519       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1520     }
1521   }// has  AVX-512
1522
1523   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1524     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1525     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1526
1527     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1528     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1529
1530     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1531     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1532     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1533     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1534     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1535     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1536     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1537     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1538     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1539     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1540     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1541     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1542     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1543     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1544     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1545     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1546     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1547     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1548     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1549     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1550     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1551     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1552     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1553     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1554     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1555     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1556     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1557     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1558     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1559
1560     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1561     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1562     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1563     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1564     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1565     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1566     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1567     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1568
1569     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1570       const MVT VT = (MVT::SimpleValueType)i;
1571
1572       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1573
1574       // Do not attempt to promote non-512-bit vectors.
1575       if (!VT.is512BitVector())
1576         continue;
1577
1578       if (EltSize < 32) {
1579         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1580         setOperationAction(ISD::VSELECT,             VT, Legal);
1581       }
1582     }
1583   }
1584
1585   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1586     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1587     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1588
1589     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1590     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1591     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1592     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1593     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1594     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1595     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1596     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1597     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1598     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1599
1600     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1601     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1602     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1603     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1604     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1605     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1606     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1607     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1608
1609     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1610     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1611     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1612     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1613     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1614     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1615     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1616     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1617   }
1618
1619   // We want to custom lower some of our intrinsics.
1620   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1621   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1622   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1623   if (!Subtarget->is64Bit())
1624     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1625
1626   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1627   // handle type legalization for these operations here.
1628   //
1629   // FIXME: We really should do custom legalization for addition and
1630   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1631   // than generic legalization for 64-bit multiplication-with-overflow, though.
1632   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1633     // Add/Sub/Mul with overflow operations are custom lowered.
1634     MVT VT = IntVTs[i];
1635     setOperationAction(ISD::SADDO, VT, Custom);
1636     setOperationAction(ISD::UADDO, VT, Custom);
1637     setOperationAction(ISD::SSUBO, VT, Custom);
1638     setOperationAction(ISD::USUBO, VT, Custom);
1639     setOperationAction(ISD::SMULO, VT, Custom);
1640     setOperationAction(ISD::UMULO, VT, Custom);
1641   }
1642
1643
1644   if (!Subtarget->is64Bit()) {
1645     // These libcalls are not available in 32-bit.
1646     setLibcallName(RTLIB::SHL_I128, nullptr);
1647     setLibcallName(RTLIB::SRL_I128, nullptr);
1648     setLibcallName(RTLIB::SRA_I128, nullptr);
1649   }
1650
1651   // Combine sin / cos into one node or libcall if possible.
1652   if (Subtarget->hasSinCos()) {
1653     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1654     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1655     if (Subtarget->isTargetDarwin()) {
1656       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1657       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1658       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1659       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1660     }
1661   }
1662
1663   if (Subtarget->isTargetWin64()) {
1664     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1665     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1666     setOperationAction(ISD::SREM, MVT::i128, Custom);
1667     setOperationAction(ISD::UREM, MVT::i128, Custom);
1668     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1669     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1670   }
1671
1672   // We have target-specific dag combine patterns for the following nodes:
1673   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1674   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1675   setTargetDAGCombine(ISD::BITCAST);
1676   setTargetDAGCombine(ISD::VSELECT);
1677   setTargetDAGCombine(ISD::SELECT);
1678   setTargetDAGCombine(ISD::SHL);
1679   setTargetDAGCombine(ISD::SRA);
1680   setTargetDAGCombine(ISD::SRL);
1681   setTargetDAGCombine(ISD::OR);
1682   setTargetDAGCombine(ISD::AND);
1683   setTargetDAGCombine(ISD::ADD);
1684   setTargetDAGCombine(ISD::FADD);
1685   setTargetDAGCombine(ISD::FSUB);
1686   setTargetDAGCombine(ISD::FMA);
1687   setTargetDAGCombine(ISD::SUB);
1688   setTargetDAGCombine(ISD::LOAD);
1689   setTargetDAGCombine(ISD::MLOAD);
1690   setTargetDAGCombine(ISD::STORE);
1691   setTargetDAGCombine(ISD::MSTORE);
1692   setTargetDAGCombine(ISD::ZERO_EXTEND);
1693   setTargetDAGCombine(ISD::ANY_EXTEND);
1694   setTargetDAGCombine(ISD::SIGN_EXTEND);
1695   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1696   setTargetDAGCombine(ISD::SINT_TO_FP);
1697   setTargetDAGCombine(ISD::UINT_TO_FP);
1698   setTargetDAGCombine(ISD::SETCC);
1699   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1700   setTargetDAGCombine(ISD::BUILD_VECTOR);
1701   setTargetDAGCombine(ISD::MUL);
1702   setTargetDAGCombine(ISD::XOR);
1703
1704   computeRegisterProperties(Subtarget->getRegisterInfo());
1705
1706   // On Darwin, -Os means optimize for size without hurting performance,
1707   // do not reduce the limit.
1708   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1709   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1710   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1711   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1712   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1713   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1714   setPrefLoopAlignment(4); // 2^4 bytes.
1715
1716   // Predictable cmov don't hurt on atom because it's in-order.
1717   PredictableSelectIsExpensive = !Subtarget->isAtom();
1718   EnableExtLdPromotion = true;
1719   setPrefFunctionAlignment(4); // 2^4 bytes.
1720
1721   verifyIntrinsicTables();
1722 }
1723
1724 // This has so far only been implemented for 64-bit MachO.
1725 bool X86TargetLowering::useLoadStackGuardNode() const {
1726   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1727 }
1728
1729 TargetLoweringBase::LegalizeTypeAction
1730 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1731   if (ExperimentalVectorWideningLegalization &&
1732       VT.getVectorNumElements() != 1 &&
1733       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1734     return TypeWidenVector;
1735
1736   return TargetLoweringBase::getPreferredVectorAction(VT);
1737 }
1738
1739 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1740                                           EVT VT) const {
1741   if (!VT.isVector())
1742     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1743
1744   const unsigned NumElts = VT.getVectorNumElements();
1745   const EVT EltVT = VT.getVectorElementType();
1746   if (VT.is512BitVector()) {
1747     if (Subtarget->hasAVX512())
1748       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1749           EltVT == MVT::f32 || EltVT == MVT::f64)
1750         switch(NumElts) {
1751         case  8: return MVT::v8i1;
1752         case 16: return MVT::v16i1;
1753       }
1754     if (Subtarget->hasBWI())
1755       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1756         switch(NumElts) {
1757         case 32: return MVT::v32i1;
1758         case 64: return MVT::v64i1;
1759       }
1760   }
1761
1762   if (VT.is256BitVector() || VT.is128BitVector()) {
1763     if (Subtarget->hasVLX())
1764       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1765           EltVT == MVT::f32 || EltVT == MVT::f64)
1766         switch(NumElts) {
1767         case 2: return MVT::v2i1;
1768         case 4: return MVT::v4i1;
1769         case 8: return MVT::v8i1;
1770       }
1771     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1772       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1773         switch(NumElts) {
1774         case  8: return MVT::v8i1;
1775         case 16: return MVT::v16i1;
1776         case 32: return MVT::v32i1;
1777       }
1778   }
1779
1780   return VT.changeVectorElementTypeToInteger();
1781 }
1782
1783 /// Helper for getByValTypeAlignment to determine
1784 /// the desired ByVal argument alignment.
1785 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1786   if (MaxAlign == 16)
1787     return;
1788   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1789     if (VTy->getBitWidth() == 128)
1790       MaxAlign = 16;
1791   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1792     unsigned EltAlign = 0;
1793     getMaxByValAlign(ATy->getElementType(), EltAlign);
1794     if (EltAlign > MaxAlign)
1795       MaxAlign = EltAlign;
1796   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1797     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1798       unsigned EltAlign = 0;
1799       getMaxByValAlign(STy->getElementType(i), EltAlign);
1800       if (EltAlign > MaxAlign)
1801         MaxAlign = EltAlign;
1802       if (MaxAlign == 16)
1803         break;
1804     }
1805   }
1806 }
1807
1808 /// Return the desired alignment for ByVal aggregate
1809 /// function arguments in the caller parameter area. For X86, aggregates
1810 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1811 /// are at 4-byte boundaries.
1812 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1813                                                   const DataLayout &DL) const {
1814   if (Subtarget->is64Bit()) {
1815     // Max of 8 and alignment of type.
1816     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1817     if (TyAlign > 8)
1818       return TyAlign;
1819     return 8;
1820   }
1821
1822   unsigned Align = 4;
1823   if (Subtarget->hasSSE1())
1824     getMaxByValAlign(Ty, Align);
1825   return Align;
1826 }
1827
1828 /// Returns the target specific optimal type for load
1829 /// and store operations as a result of memset, memcpy, and memmove
1830 /// lowering. If DstAlign is zero that means it's safe to destination
1831 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1832 /// means there isn't a need to check it against alignment requirement,
1833 /// probably because the source does not need to be loaded. If 'IsMemset' is
1834 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1835 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1836 /// source is constant so it does not need to be loaded.
1837 /// It returns EVT::Other if the type should be determined using generic
1838 /// target-independent logic.
1839 EVT
1840 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1841                                        unsigned DstAlign, unsigned SrcAlign,
1842                                        bool IsMemset, bool ZeroMemset,
1843                                        bool MemcpyStrSrc,
1844                                        MachineFunction &MF) const {
1845   const Function *F = MF.getFunction();
1846   if ((!IsMemset || ZeroMemset) &&
1847       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1848     if (Size >= 16 &&
1849         (Subtarget->isUnalignedMemAccessFast() ||
1850          ((DstAlign == 0 || DstAlign >= 16) &&
1851           (SrcAlign == 0 || SrcAlign >= 16)))) {
1852       if (Size >= 32) {
1853         if (Subtarget->hasInt256())
1854           return MVT::v8i32;
1855         if (Subtarget->hasFp256())
1856           return MVT::v8f32;
1857       }
1858       if (Subtarget->hasSSE2())
1859         return MVT::v4i32;
1860       if (Subtarget->hasSSE1())
1861         return MVT::v4f32;
1862     } else if (!MemcpyStrSrc && Size >= 8 &&
1863                !Subtarget->is64Bit() &&
1864                Subtarget->hasSSE2()) {
1865       // Do not use f64 to lower memcpy if source is string constant. It's
1866       // better to use i32 to avoid the loads.
1867       return MVT::f64;
1868     }
1869   }
1870   if (Subtarget->is64Bit() && Size >= 8)
1871     return MVT::i64;
1872   return MVT::i32;
1873 }
1874
1875 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1876   if (VT == MVT::f32)
1877     return X86ScalarSSEf32;
1878   else if (VT == MVT::f64)
1879     return X86ScalarSSEf64;
1880   return true;
1881 }
1882
1883 bool
1884 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1885                                                   unsigned,
1886                                                   unsigned,
1887                                                   bool *Fast) const {
1888   if (Fast)
1889     *Fast = Subtarget->isUnalignedMemAccessFast();
1890   return true;
1891 }
1892
1893 /// Return the entry encoding for a jump table in the
1894 /// current function.  The returned value is a member of the
1895 /// MachineJumpTableInfo::JTEntryKind enum.
1896 unsigned X86TargetLowering::getJumpTableEncoding() const {
1897   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1898   // symbol.
1899   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1900       Subtarget->isPICStyleGOT())
1901     return MachineJumpTableInfo::EK_Custom32;
1902
1903   // Otherwise, use the normal jump table encoding heuristics.
1904   return TargetLowering::getJumpTableEncoding();
1905 }
1906
1907 bool X86TargetLowering::useSoftFloat() const {
1908   return Subtarget->useSoftFloat();
1909 }
1910
1911 const MCExpr *
1912 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1913                                              const MachineBasicBlock *MBB,
1914                                              unsigned uid,MCContext &Ctx) const{
1915   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1916          Subtarget->isPICStyleGOT());
1917   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1918   // entries.
1919   return MCSymbolRefExpr::create(MBB->getSymbol(),
1920                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1921 }
1922
1923 /// Returns relocation base for the given PIC jumptable.
1924 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1925                                                     SelectionDAG &DAG) const {
1926   if (!Subtarget->is64Bit())
1927     // This doesn't have SDLoc associated with it, but is not really the
1928     // same as a Register.
1929     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1930                        getPointerTy(DAG.getDataLayout()));
1931   return Table;
1932 }
1933
1934 /// This returns the relocation base for the given PIC jumptable,
1935 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1936 const MCExpr *X86TargetLowering::
1937 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1938                              MCContext &Ctx) const {
1939   // X86-64 uses RIP relative addressing based on the jump table label.
1940   if (Subtarget->isPICStyleRIPRel())
1941     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1942
1943   // Otherwise, the reference is relative to the PIC base.
1944   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1945 }
1946
1947 std::pair<const TargetRegisterClass *, uint8_t>
1948 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1949                                            MVT VT) const {
1950   const TargetRegisterClass *RRC = nullptr;
1951   uint8_t Cost = 1;
1952   switch (VT.SimpleTy) {
1953   default:
1954     return TargetLowering::findRepresentativeClass(TRI, VT);
1955   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1956     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1957     break;
1958   case MVT::x86mmx:
1959     RRC = &X86::VR64RegClass;
1960     break;
1961   case MVT::f32: case MVT::f64:
1962   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1963   case MVT::v4f32: case MVT::v2f64:
1964   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1965   case MVT::v4f64:
1966     RRC = &X86::VR128RegClass;
1967     break;
1968   }
1969   return std::make_pair(RRC, Cost);
1970 }
1971
1972 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1973                                                unsigned &Offset) const {
1974   if (!Subtarget->isTargetLinux())
1975     return false;
1976
1977   if (Subtarget->is64Bit()) {
1978     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1979     Offset = 0x28;
1980     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1981       AddressSpace = 256;
1982     else
1983       AddressSpace = 257;
1984   } else {
1985     // %gs:0x14 on i386
1986     Offset = 0x14;
1987     AddressSpace = 256;
1988   }
1989   return true;
1990 }
1991
1992 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1993                                             unsigned DestAS) const {
1994   assert(SrcAS != DestAS && "Expected different address spaces!");
1995
1996   return SrcAS < 256 && DestAS < 256;
1997 }
1998
1999 //===----------------------------------------------------------------------===//
2000 //               Return Value Calling Convention Implementation
2001 //===----------------------------------------------------------------------===//
2002
2003 #include "X86GenCallingConv.inc"
2004
2005 bool
2006 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2007                                   MachineFunction &MF, bool isVarArg,
2008                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2009                         LLVMContext &Context) const {
2010   SmallVector<CCValAssign, 16> RVLocs;
2011   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2012   return CCInfo.CheckReturn(Outs, RetCC_X86);
2013 }
2014
2015 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2016   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2017   return ScratchRegs;
2018 }
2019
2020 SDValue
2021 X86TargetLowering::LowerReturn(SDValue Chain,
2022                                CallingConv::ID CallConv, bool isVarArg,
2023                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2024                                const SmallVectorImpl<SDValue> &OutVals,
2025                                SDLoc dl, SelectionDAG &DAG) const {
2026   MachineFunction &MF = DAG.getMachineFunction();
2027   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2028
2029   SmallVector<CCValAssign, 16> RVLocs;
2030   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2031   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2032
2033   SDValue Flag;
2034   SmallVector<SDValue, 6> RetOps;
2035   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2036   // Operand #1 = Bytes To Pop
2037   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2038                    MVT::i16));
2039
2040   // Copy the result values into the output registers.
2041   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2042     CCValAssign &VA = RVLocs[i];
2043     assert(VA.isRegLoc() && "Can only return in registers!");
2044     SDValue ValToCopy = OutVals[i];
2045     EVT ValVT = ValToCopy.getValueType();
2046
2047     // Promote values to the appropriate types.
2048     if (VA.getLocInfo() == CCValAssign::SExt)
2049       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2050     else if (VA.getLocInfo() == CCValAssign::ZExt)
2051       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2052     else if (VA.getLocInfo() == CCValAssign::AExt) {
2053       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2054         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2055       else
2056         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2057     }
2058     else if (VA.getLocInfo() == CCValAssign::BCvt)
2059       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2060
2061     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2062            "Unexpected FP-extend for return value.");
2063
2064     // If this is x86-64, and we disabled SSE, we can't return FP values,
2065     // or SSE or MMX vectors.
2066     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2067          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2068           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2069       report_fatal_error("SSE register return with SSE disabled");
2070     }
2071     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2072     // llvm-gcc has never done it right and no one has noticed, so this
2073     // should be OK for now.
2074     if (ValVT == MVT::f64 &&
2075         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2076       report_fatal_error("SSE2 register return with SSE2 disabled");
2077
2078     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2079     // the RET instruction and handled by the FP Stackifier.
2080     if (VA.getLocReg() == X86::FP0 ||
2081         VA.getLocReg() == X86::FP1) {
2082       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2083       // change the value to the FP stack register class.
2084       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2085         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2086       RetOps.push_back(ValToCopy);
2087       // Don't emit a copytoreg.
2088       continue;
2089     }
2090
2091     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2092     // which is returned in RAX / RDX.
2093     if (Subtarget->is64Bit()) {
2094       if (ValVT == MVT::x86mmx) {
2095         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2096           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2097           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2098                                   ValToCopy);
2099           // If we don't have SSE2 available, convert to v4f32 so the generated
2100           // register is legal.
2101           if (!Subtarget->hasSSE2())
2102             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2103         }
2104       }
2105     }
2106
2107     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2108     Flag = Chain.getValue(1);
2109     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2110   }
2111
2112   // All x86 ABIs require that for returning structs by value we copy
2113   // the sret argument into %rax/%eax (depending on ABI) for the return.
2114   // We saved the argument into a virtual register in the entry block,
2115   // so now we copy the value out and into %rax/%eax.
2116   //
2117   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2118   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2119   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2120   // either case FuncInfo->setSRetReturnReg() will have been called.
2121   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2122     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2123                                      getPointerTy(MF.getDataLayout()));
2124
2125     unsigned RetValReg
2126         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2127           X86::RAX : X86::EAX;
2128     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2129     Flag = Chain.getValue(1);
2130
2131     // RAX/EAX now acts like a return value.
2132     RetOps.push_back(
2133         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2134   }
2135
2136   RetOps[0] = Chain;  // Update chain.
2137
2138   // Add the flag if we have it.
2139   if (Flag.getNode())
2140     RetOps.push_back(Flag);
2141
2142   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2143 }
2144
2145 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2146   if (N->getNumValues() != 1)
2147     return false;
2148   if (!N->hasNUsesOfValue(1, 0))
2149     return false;
2150
2151   SDValue TCChain = Chain;
2152   SDNode *Copy = *N->use_begin();
2153   if (Copy->getOpcode() == ISD::CopyToReg) {
2154     // If the copy has a glue operand, we conservatively assume it isn't safe to
2155     // perform a tail call.
2156     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2157       return false;
2158     TCChain = Copy->getOperand(0);
2159   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2160     return false;
2161
2162   bool HasRet = false;
2163   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2164        UI != UE; ++UI) {
2165     if (UI->getOpcode() != X86ISD::RET_FLAG)
2166       return false;
2167     // If we are returning more than one value, we can definitely
2168     // not make a tail call see PR19530
2169     if (UI->getNumOperands() > 4)
2170       return false;
2171     if (UI->getNumOperands() == 4 &&
2172         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2173       return false;
2174     HasRet = true;
2175   }
2176
2177   if (!HasRet)
2178     return false;
2179
2180   Chain = TCChain;
2181   return true;
2182 }
2183
2184 EVT
2185 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2186                                             ISD::NodeType ExtendKind) const {
2187   MVT ReturnMVT;
2188   // TODO: Is this also valid on 32-bit?
2189   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2190     ReturnMVT = MVT::i8;
2191   else
2192     ReturnMVT = MVT::i32;
2193
2194   EVT MinVT = getRegisterType(Context, ReturnMVT);
2195   return VT.bitsLT(MinVT) ? MinVT : VT;
2196 }
2197
2198 /// Lower the result values of a call into the
2199 /// appropriate copies out of appropriate physical registers.
2200 ///
2201 SDValue
2202 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2203                                    CallingConv::ID CallConv, bool isVarArg,
2204                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2205                                    SDLoc dl, SelectionDAG &DAG,
2206                                    SmallVectorImpl<SDValue> &InVals) const {
2207
2208   // Assign locations to each value returned by this call.
2209   SmallVector<CCValAssign, 16> RVLocs;
2210   bool Is64Bit = Subtarget->is64Bit();
2211   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2212                  *DAG.getContext());
2213   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2214
2215   // Copy all of the result registers out of their specified physreg.
2216   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2217     CCValAssign &VA = RVLocs[i];
2218     EVT CopyVT = VA.getLocVT();
2219
2220     // If this is x86-64, and we disabled SSE, we can't return FP values
2221     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2222         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2223       report_fatal_error("SSE register return with SSE disabled");
2224     }
2225
2226     // If we prefer to use the value in xmm registers, copy it out as f80 and
2227     // use a truncate to move it from fp stack reg to xmm reg.
2228     bool RoundAfterCopy = false;
2229     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2230         isScalarFPTypeInSSEReg(VA.getValVT())) {
2231       CopyVT = MVT::f80;
2232       RoundAfterCopy = (CopyVT != VA.getLocVT());
2233     }
2234
2235     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2236                                CopyVT, InFlag).getValue(1);
2237     SDValue Val = Chain.getValue(0);
2238
2239     if (RoundAfterCopy)
2240       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2241                         // This truncation won't change the value.
2242                         DAG.getIntPtrConstant(1, dl));
2243
2244     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2245       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2246
2247     InFlag = Chain.getValue(2);
2248     InVals.push_back(Val);
2249   }
2250
2251   return Chain;
2252 }
2253
2254 //===----------------------------------------------------------------------===//
2255 //                C & StdCall & Fast Calling Convention implementation
2256 //===----------------------------------------------------------------------===//
2257 //  StdCall calling convention seems to be standard for many Windows' API
2258 //  routines and around. It differs from C calling convention just a little:
2259 //  callee should clean up the stack, not caller. Symbols should be also
2260 //  decorated in some fancy way :) It doesn't support any vector arguments.
2261 //  For info on fast calling convention see Fast Calling Convention (tail call)
2262 //  implementation LowerX86_32FastCCCallTo.
2263
2264 /// CallIsStructReturn - Determines whether a call uses struct return
2265 /// semantics.
2266 enum StructReturnType {
2267   NotStructReturn,
2268   RegStructReturn,
2269   StackStructReturn
2270 };
2271 static StructReturnType
2272 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2273   if (Outs.empty())
2274     return NotStructReturn;
2275
2276   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2277   if (!Flags.isSRet())
2278     return NotStructReturn;
2279   if (Flags.isInReg())
2280     return RegStructReturn;
2281   return StackStructReturn;
2282 }
2283
2284 /// Determines whether a function uses struct return semantics.
2285 static StructReturnType
2286 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2287   if (Ins.empty())
2288     return NotStructReturn;
2289
2290   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2291   if (!Flags.isSRet())
2292     return NotStructReturn;
2293   if (Flags.isInReg())
2294     return RegStructReturn;
2295   return StackStructReturn;
2296 }
2297
2298 /// Make a copy of an aggregate at address specified by "Src" to address
2299 /// "Dst" with size and alignment information specified by the specific
2300 /// parameter attribute. The copy will be passed as a byval function parameter.
2301 static SDValue
2302 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2303                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2304                           SDLoc dl) {
2305   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2306
2307   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2308                        /*isVolatile*/false, /*AlwaysInline=*/true,
2309                        /*isTailCall*/false,
2310                        MachinePointerInfo(), MachinePointerInfo());
2311 }
2312
2313 /// Return true if the calling convention is one that
2314 /// supports tail call optimization.
2315 static bool IsTailCallConvention(CallingConv::ID CC) {
2316   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2317           CC == CallingConv::HiPE);
2318 }
2319
2320 /// \brief Return true if the calling convention is a C calling convention.
2321 static bool IsCCallConvention(CallingConv::ID CC) {
2322   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2323           CC == CallingConv::X86_64_SysV);
2324 }
2325
2326 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2327   auto Attr =
2328       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2329   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2330     return false;
2331
2332   CallSite CS(CI);
2333   CallingConv::ID CalleeCC = CS.getCallingConv();
2334   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2335     return false;
2336
2337   return true;
2338 }
2339
2340 /// Return true if the function is being made into
2341 /// a tailcall target by changing its ABI.
2342 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2343                                    bool GuaranteedTailCallOpt) {
2344   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2345 }
2346
2347 SDValue
2348 X86TargetLowering::LowerMemArgument(SDValue Chain,
2349                                     CallingConv::ID CallConv,
2350                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2351                                     SDLoc dl, SelectionDAG &DAG,
2352                                     const CCValAssign &VA,
2353                                     MachineFrameInfo *MFI,
2354                                     unsigned i) const {
2355   // Create the nodes corresponding to a load from this parameter slot.
2356   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2357   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2358       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2359   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2360   EVT ValVT;
2361
2362   // If value is passed by pointer we have address passed instead of the value
2363   // itself.
2364   bool ExtendedInMem = VA.isExtInLoc() &&
2365     VA.getValVT().getScalarType() == MVT::i1;
2366
2367   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2368     ValVT = VA.getLocVT();
2369   else
2370     ValVT = VA.getValVT();
2371
2372   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2373   // changed with more analysis.
2374   // In case of tail call optimization mark all arguments mutable. Since they
2375   // could be overwritten by lowering of arguments in case of a tail call.
2376   if (Flags.isByVal()) {
2377     unsigned Bytes = Flags.getByValSize();
2378     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2379     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2380     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2381   } else {
2382     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2383                                     VA.getLocMemOffset(), isImmutable);
2384     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2385     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2386                                MachinePointerInfo::getFixedStack(FI),
2387                                false, false, false, 0);
2388     return ExtendedInMem ?
2389       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2390   }
2391 }
2392
2393 // FIXME: Get this from tablegen.
2394 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2395                                                 const X86Subtarget *Subtarget) {
2396   assert(Subtarget->is64Bit());
2397
2398   if (Subtarget->isCallingConvWin64(CallConv)) {
2399     static const MCPhysReg GPR64ArgRegsWin64[] = {
2400       X86::RCX, X86::RDX, X86::R8,  X86::R9
2401     };
2402     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2403   }
2404
2405   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2406     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2407   };
2408   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2409 }
2410
2411 // FIXME: Get this from tablegen.
2412 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2413                                                 CallingConv::ID CallConv,
2414                                                 const X86Subtarget *Subtarget) {
2415   assert(Subtarget->is64Bit());
2416   if (Subtarget->isCallingConvWin64(CallConv)) {
2417     // The XMM registers which might contain var arg parameters are shadowed
2418     // in their paired GPR.  So we only need to save the GPR to their home
2419     // slots.
2420     // TODO: __vectorcall will change this.
2421     return None;
2422   }
2423
2424   const Function *Fn = MF.getFunction();
2425   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2426   bool isSoftFloat = Subtarget->useSoftFloat();
2427   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2428          "SSE register cannot be used when SSE is disabled!");
2429   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2430     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2431     // registers.
2432     return None;
2433
2434   static const MCPhysReg XMMArgRegs64Bit[] = {
2435     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2436     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2437   };
2438   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2439 }
2440
2441 SDValue
2442 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2443                                         CallingConv::ID CallConv,
2444                                         bool isVarArg,
2445                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2446                                         SDLoc dl,
2447                                         SelectionDAG &DAG,
2448                                         SmallVectorImpl<SDValue> &InVals)
2449                                           const {
2450   MachineFunction &MF = DAG.getMachineFunction();
2451   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2452   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2453
2454   const Function* Fn = MF.getFunction();
2455   if (Fn->hasExternalLinkage() &&
2456       Subtarget->isTargetCygMing() &&
2457       Fn->getName() == "main")
2458     FuncInfo->setForceFramePointer(true);
2459
2460   MachineFrameInfo *MFI = MF.getFrameInfo();
2461   bool Is64Bit = Subtarget->is64Bit();
2462   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2463
2464   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2465          "Var args not supported with calling convention fastcc, ghc or hipe");
2466
2467   // Assign locations to all of the incoming arguments.
2468   SmallVector<CCValAssign, 16> ArgLocs;
2469   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2470
2471   // Allocate shadow area for Win64
2472   if (IsWin64)
2473     CCInfo.AllocateStack(32, 8);
2474
2475   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2476
2477   unsigned LastVal = ~0U;
2478   SDValue ArgValue;
2479   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2480     CCValAssign &VA = ArgLocs[i];
2481     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2482     // places.
2483     assert(VA.getValNo() != LastVal &&
2484            "Don't support value assigned to multiple locs yet");
2485     (void)LastVal;
2486     LastVal = VA.getValNo();
2487
2488     if (VA.isRegLoc()) {
2489       EVT RegVT = VA.getLocVT();
2490       const TargetRegisterClass *RC;
2491       if (RegVT == MVT::i32)
2492         RC = &X86::GR32RegClass;
2493       else if (Is64Bit && RegVT == MVT::i64)
2494         RC = &X86::GR64RegClass;
2495       else if (RegVT == MVT::f32)
2496         RC = &X86::FR32RegClass;
2497       else if (RegVT == MVT::f64)
2498         RC = &X86::FR64RegClass;
2499       else if (RegVT.is512BitVector())
2500         RC = &X86::VR512RegClass;
2501       else if (RegVT.is256BitVector())
2502         RC = &X86::VR256RegClass;
2503       else if (RegVT.is128BitVector())
2504         RC = &X86::VR128RegClass;
2505       else if (RegVT == MVT::x86mmx)
2506         RC = &X86::VR64RegClass;
2507       else if (RegVT == MVT::i1)
2508         RC = &X86::VK1RegClass;
2509       else if (RegVT == MVT::v8i1)
2510         RC = &X86::VK8RegClass;
2511       else if (RegVT == MVT::v16i1)
2512         RC = &X86::VK16RegClass;
2513       else if (RegVT == MVT::v32i1)
2514         RC = &X86::VK32RegClass;
2515       else if (RegVT == MVT::v64i1)
2516         RC = &X86::VK64RegClass;
2517       else
2518         llvm_unreachable("Unknown argument type!");
2519
2520       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2521       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2522
2523       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2524       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2525       // right size.
2526       if (VA.getLocInfo() == CCValAssign::SExt)
2527         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2528                                DAG.getValueType(VA.getValVT()));
2529       else if (VA.getLocInfo() == CCValAssign::ZExt)
2530         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2531                                DAG.getValueType(VA.getValVT()));
2532       else if (VA.getLocInfo() == CCValAssign::BCvt)
2533         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2534
2535       if (VA.isExtInLoc()) {
2536         // Handle MMX values passed in XMM regs.
2537         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2538           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2539         else
2540           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2541       }
2542     } else {
2543       assert(VA.isMemLoc());
2544       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2545     }
2546
2547     // If value is passed via pointer - do a load.
2548     if (VA.getLocInfo() == CCValAssign::Indirect)
2549       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2550                              MachinePointerInfo(), false, false, false, 0);
2551
2552     InVals.push_back(ArgValue);
2553   }
2554
2555   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2556     // All x86 ABIs require that for returning structs by value we copy the
2557     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2558     // the argument into a virtual register so that we can access it from the
2559     // return points.
2560     if (Ins[i].Flags.isSRet()) {
2561       unsigned Reg = FuncInfo->getSRetReturnReg();
2562       if (!Reg) {
2563         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2564         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2565         FuncInfo->setSRetReturnReg(Reg);
2566       }
2567       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2568       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2569       break;
2570     }
2571   }
2572
2573   unsigned StackSize = CCInfo.getNextStackOffset();
2574   // Align stack specially for tail calls.
2575   if (FuncIsMadeTailCallSafe(CallConv,
2576                              MF.getTarget().Options.GuaranteedTailCallOpt))
2577     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2578
2579   // If the function takes variable number of arguments, make a frame index for
2580   // the start of the first vararg value... for expansion of llvm.va_start. We
2581   // can skip this if there are no va_start calls.
2582   if (MFI->hasVAStart() &&
2583       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2584                    CallConv != CallingConv::X86_ThisCall))) {
2585     FuncInfo->setVarArgsFrameIndex(
2586         MFI->CreateFixedObject(1, StackSize, true));
2587   }
2588
2589   MachineModuleInfo &MMI = MF.getMMI();
2590   const Function *WinEHParent = nullptr;
2591   if (MMI.hasWinEHFuncInfo(Fn))
2592     WinEHParent = MMI.getWinEHParent(Fn);
2593   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2594   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2595
2596   // Figure out if XMM registers are in use.
2597   assert(!(Subtarget->useSoftFloat() &&
2598            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2599          "SSE register cannot be used when SSE is disabled!");
2600
2601   // 64-bit calling conventions support varargs and register parameters, so we
2602   // have to do extra work to spill them in the prologue.
2603   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2604     // Find the first unallocated argument registers.
2605     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2606     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2607     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2608     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2609     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2610            "SSE register cannot be used when SSE is disabled!");
2611
2612     // Gather all the live in physical registers.
2613     SmallVector<SDValue, 6> LiveGPRs;
2614     SmallVector<SDValue, 8> LiveXMMRegs;
2615     SDValue ALVal;
2616     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2617       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2618       LiveGPRs.push_back(
2619           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2620     }
2621     if (!ArgXMMs.empty()) {
2622       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2623       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2624       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2625         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2626         LiveXMMRegs.push_back(
2627             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2628       }
2629     }
2630
2631     if (IsWin64) {
2632       // Get to the caller-allocated home save location.  Add 8 to account
2633       // for the return address.
2634       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2635       FuncInfo->setRegSaveFrameIndex(
2636           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2637       // Fixup to set vararg frame on shadow area (4 x i64).
2638       if (NumIntRegs < 4)
2639         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2640     } else {
2641       // For X86-64, if there are vararg parameters that are passed via
2642       // registers, then we must store them to their spots on the stack so
2643       // they may be loaded by deferencing the result of va_next.
2644       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2645       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2646       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2647           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2648     }
2649
2650     // Store the integer parameter registers.
2651     SmallVector<SDValue, 8> MemOps;
2652     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2653                                       getPointerTy(DAG.getDataLayout()));
2654     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2655     for (SDValue Val : LiveGPRs) {
2656       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2657                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2658       SDValue Store =
2659         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2660                      MachinePointerInfo::getFixedStack(
2661                        FuncInfo->getRegSaveFrameIndex(), Offset),
2662                      false, false, 0);
2663       MemOps.push_back(Store);
2664       Offset += 8;
2665     }
2666
2667     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2668       // Now store the XMM (fp + vector) parameter registers.
2669       SmallVector<SDValue, 12> SaveXMMOps;
2670       SaveXMMOps.push_back(Chain);
2671       SaveXMMOps.push_back(ALVal);
2672       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2673                              FuncInfo->getRegSaveFrameIndex(), dl));
2674       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2675                              FuncInfo->getVarArgsFPOffset(), dl));
2676       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2677                         LiveXMMRegs.end());
2678       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2679                                    MVT::Other, SaveXMMOps));
2680     }
2681
2682     if (!MemOps.empty())
2683       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2684   } else if (IsWin64 && IsWinEHOutlined) {
2685     // Get to the caller-allocated home save location.  Add 8 to account
2686     // for the return address.
2687     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2688     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2689         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2690
2691     MMI.getWinEHFuncInfo(Fn)
2692         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2693         FuncInfo->getRegSaveFrameIndex();
2694
2695     // Store the second integer parameter (rdx) into rsp+16 relative to the
2696     // stack pointer at the entry of the function.
2697     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2698                                       getPointerTy(DAG.getDataLayout()));
2699     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2700     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2701     Chain = DAG.getStore(
2702         Val.getValue(1), dl, Val, RSFIN,
2703         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2704         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2705   }
2706
2707   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2708     // Find the largest legal vector type.
2709     MVT VecVT = MVT::Other;
2710     // FIXME: Only some x86_32 calling conventions support AVX512.
2711     if (Subtarget->hasAVX512() &&
2712         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2713                      CallConv == CallingConv::Intel_OCL_BI)))
2714       VecVT = MVT::v16f32;
2715     else if (Subtarget->hasAVX())
2716       VecVT = MVT::v8f32;
2717     else if (Subtarget->hasSSE2())
2718       VecVT = MVT::v4f32;
2719
2720     // We forward some GPRs and some vector types.
2721     SmallVector<MVT, 2> RegParmTypes;
2722     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2723     RegParmTypes.push_back(IntVT);
2724     if (VecVT != MVT::Other)
2725       RegParmTypes.push_back(VecVT);
2726
2727     // Compute the set of forwarded registers. The rest are scratch.
2728     SmallVectorImpl<ForwardedRegister> &Forwards =
2729         FuncInfo->getForwardedMustTailRegParms();
2730     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2731
2732     // Conservatively forward AL on x86_64, since it might be used for varargs.
2733     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2734       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2735       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2736     }
2737
2738     // Copy all forwards from physical to virtual registers.
2739     for (ForwardedRegister &F : Forwards) {
2740       // FIXME: Can we use a less constrained schedule?
2741       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2742       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2743       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2744     }
2745   }
2746
2747   // Some CCs need callee pop.
2748   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2749                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2750     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2751   } else {
2752     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2753     // If this is an sret function, the return should pop the hidden pointer.
2754     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2755         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2756         argsAreStructReturn(Ins) == StackStructReturn)
2757       FuncInfo->setBytesToPopOnReturn(4);
2758   }
2759
2760   if (!Is64Bit) {
2761     // RegSaveFrameIndex is X86-64 only.
2762     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2763     if (CallConv == CallingConv::X86_FastCall ||
2764         CallConv == CallingConv::X86_ThisCall)
2765       // fastcc functions can't have varargs.
2766       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2767   }
2768
2769   FuncInfo->setArgumentStackSize(StackSize);
2770
2771   if (IsWinEHParent) {
2772     if (Is64Bit) {
2773       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2774       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2775       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2776       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2777       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2778                            MachinePointerInfo::getFixedStack(UnwindHelpFI),
2779                            /*isVolatile=*/true,
2780                            /*isNonTemporal=*/false, /*Alignment=*/0);
2781     } else {
2782       // Functions using Win32 EH are considered to have opaque SP adjustments
2783       // to force local variables to be addressed from the frame or base
2784       // pointers.
2785       MFI->setHasOpaqueSPAdjustment(true);
2786     }
2787   }
2788
2789   return Chain;
2790 }
2791
2792 SDValue
2793 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2794                                     SDValue StackPtr, SDValue Arg,
2795                                     SDLoc dl, SelectionDAG &DAG,
2796                                     const CCValAssign &VA,
2797                                     ISD::ArgFlagsTy Flags) const {
2798   unsigned LocMemOffset = VA.getLocMemOffset();
2799   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2800   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2801                        StackPtr, PtrOff);
2802   if (Flags.isByVal())
2803     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2804
2805   return DAG.getStore(Chain, dl, Arg, PtrOff,
2806                       MachinePointerInfo::getStack(LocMemOffset),
2807                       false, false, 0);
2808 }
2809
2810 /// Emit a load of return address if tail call
2811 /// optimization is performed and it is required.
2812 SDValue
2813 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2814                                            SDValue &OutRetAddr, SDValue Chain,
2815                                            bool IsTailCall, bool Is64Bit,
2816                                            int FPDiff, SDLoc dl) const {
2817   // Adjust the Return address stack slot.
2818   EVT VT = getPointerTy(DAG.getDataLayout());
2819   OutRetAddr = getReturnAddressFrameIndex(DAG);
2820
2821   // Load the "old" Return address.
2822   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2823                            false, false, false, 0);
2824   return SDValue(OutRetAddr.getNode(), 1);
2825 }
2826
2827 /// Emit a store of the return address if tail call
2828 /// optimization is performed and it is required (FPDiff!=0).
2829 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2830                                         SDValue Chain, SDValue RetAddrFrIdx,
2831                                         EVT PtrVT, unsigned SlotSize,
2832                                         int FPDiff, SDLoc dl) {
2833   // Store the return address to the appropriate stack slot.
2834   if (!FPDiff) return Chain;
2835   // Calculate the new stack slot for the return address.
2836   int NewReturnAddrFI =
2837     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2838                                          false);
2839   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2840   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2841                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2842                        false, false, 0);
2843   return Chain;
2844 }
2845
2846 SDValue
2847 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2848                              SmallVectorImpl<SDValue> &InVals) const {
2849   SelectionDAG &DAG                     = CLI.DAG;
2850   SDLoc &dl                             = CLI.DL;
2851   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2852   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2853   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2854   SDValue Chain                         = CLI.Chain;
2855   SDValue Callee                        = CLI.Callee;
2856   CallingConv::ID CallConv              = CLI.CallConv;
2857   bool &isTailCall                      = CLI.IsTailCall;
2858   bool isVarArg                         = CLI.IsVarArg;
2859
2860   MachineFunction &MF = DAG.getMachineFunction();
2861   bool Is64Bit        = Subtarget->is64Bit();
2862   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2863   StructReturnType SR = callIsStructReturn(Outs);
2864   bool IsSibcall      = false;
2865   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2866   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2867
2868   if (Attr.getValueAsString() == "true")
2869     isTailCall = false;
2870
2871   if (Subtarget->isPICStyleGOT() &&
2872       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2873     // If we are using a GOT, disable tail calls to external symbols with
2874     // default visibility. Tail calling such a symbol requires using a GOT
2875     // relocation, which forces early binding of the symbol. This breaks code
2876     // that require lazy function symbol resolution. Using musttail or
2877     // GuaranteedTailCallOpt will override this.
2878     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2879     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2880                G->getGlobal()->hasDefaultVisibility()))
2881       isTailCall = false;
2882   }
2883
2884   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2885   if (IsMustTail) {
2886     // Force this to be a tail call.  The verifier rules are enough to ensure
2887     // that we can lower this successfully without moving the return address
2888     // around.
2889     isTailCall = true;
2890   } else if (isTailCall) {
2891     // Check if it's really possible to do a tail call.
2892     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2893                     isVarArg, SR != NotStructReturn,
2894                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2895                     Outs, OutVals, Ins, DAG);
2896
2897     // Sibcalls are automatically detected tailcalls which do not require
2898     // ABI changes.
2899     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2900       IsSibcall = true;
2901
2902     if (isTailCall)
2903       ++NumTailCalls;
2904   }
2905
2906   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2907          "Var args not supported with calling convention fastcc, ghc or hipe");
2908
2909   // Analyze operands of the call, assigning locations to each operand.
2910   SmallVector<CCValAssign, 16> ArgLocs;
2911   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2912
2913   // Allocate shadow area for Win64
2914   if (IsWin64)
2915     CCInfo.AllocateStack(32, 8);
2916
2917   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2918
2919   // Get a count of how many bytes are to be pushed on the stack.
2920   unsigned NumBytes = CCInfo.getNextStackOffset();
2921   if (IsSibcall)
2922     // This is a sibcall. The memory operands are available in caller's
2923     // own caller's stack.
2924     NumBytes = 0;
2925   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2926            IsTailCallConvention(CallConv))
2927     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2928
2929   int FPDiff = 0;
2930   if (isTailCall && !IsSibcall && !IsMustTail) {
2931     // Lower arguments at fp - stackoffset + fpdiff.
2932     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2933
2934     FPDiff = NumBytesCallerPushed - NumBytes;
2935
2936     // Set the delta of movement of the returnaddr stackslot.
2937     // But only set if delta is greater than previous delta.
2938     if (FPDiff < X86Info->getTCReturnAddrDelta())
2939       X86Info->setTCReturnAddrDelta(FPDiff);
2940   }
2941
2942   unsigned NumBytesToPush = NumBytes;
2943   unsigned NumBytesToPop = NumBytes;
2944
2945   // If we have an inalloca argument, all stack space has already been allocated
2946   // for us and be right at the top of the stack.  We don't support multiple
2947   // arguments passed in memory when using inalloca.
2948   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2949     NumBytesToPush = 0;
2950     if (!ArgLocs.back().isMemLoc())
2951       report_fatal_error("cannot use inalloca attribute on a register "
2952                          "parameter");
2953     if (ArgLocs.back().getLocMemOffset() != 0)
2954       report_fatal_error("any parameter with the inalloca attribute must be "
2955                          "the only memory argument");
2956   }
2957
2958   if (!IsSibcall)
2959     Chain = DAG.getCALLSEQ_START(
2960         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2961
2962   SDValue RetAddrFrIdx;
2963   // Load return address for tail calls.
2964   if (isTailCall && FPDiff)
2965     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2966                                     Is64Bit, FPDiff, dl);
2967
2968   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2969   SmallVector<SDValue, 8> MemOpChains;
2970   SDValue StackPtr;
2971
2972   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2973   // of tail call optimization arguments are handle later.
2974   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2975   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2976     // Skip inalloca arguments, they have already been written.
2977     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2978     if (Flags.isInAlloca())
2979       continue;
2980
2981     CCValAssign &VA = ArgLocs[i];
2982     EVT RegVT = VA.getLocVT();
2983     SDValue Arg = OutVals[i];
2984     bool isByVal = Flags.isByVal();
2985
2986     // Promote the value if needed.
2987     switch (VA.getLocInfo()) {
2988     default: llvm_unreachable("Unknown loc info!");
2989     case CCValAssign::Full: break;
2990     case CCValAssign::SExt:
2991       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2992       break;
2993     case CCValAssign::ZExt:
2994       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2995       break;
2996     case CCValAssign::AExt:
2997       if (Arg.getValueType().isVector() &&
2998           Arg.getValueType().getScalarType() == MVT::i1)
2999         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3000       else if (RegVT.is128BitVector()) {
3001         // Special case: passing MMX values in XMM registers.
3002         Arg = DAG.getBitcast(MVT::i64, Arg);
3003         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3004         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3005       } else
3006         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3007       break;
3008     case CCValAssign::BCvt:
3009       Arg = DAG.getBitcast(RegVT, Arg);
3010       break;
3011     case CCValAssign::Indirect: {
3012       // Store the argument.
3013       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3014       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3015       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
3016                            MachinePointerInfo::getFixedStack(FI),
3017                            false, false, 0);
3018       Arg = SpillSlot;
3019       break;
3020     }
3021     }
3022
3023     if (VA.isRegLoc()) {
3024       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3025       if (isVarArg && IsWin64) {
3026         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3027         // shadow reg if callee is a varargs function.
3028         unsigned ShadowReg = 0;
3029         switch (VA.getLocReg()) {
3030         case X86::XMM0: ShadowReg = X86::RCX; break;
3031         case X86::XMM1: ShadowReg = X86::RDX; break;
3032         case X86::XMM2: ShadowReg = X86::R8; break;
3033         case X86::XMM3: ShadowReg = X86::R9; break;
3034         }
3035         if (ShadowReg)
3036           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3037       }
3038     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3039       assert(VA.isMemLoc());
3040       if (!StackPtr.getNode())
3041         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3042                                       getPointerTy(DAG.getDataLayout()));
3043       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3044                                              dl, DAG, VA, Flags));
3045     }
3046   }
3047
3048   if (!MemOpChains.empty())
3049     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3050
3051   if (Subtarget->isPICStyleGOT()) {
3052     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3053     // GOT pointer.
3054     if (!isTailCall) {
3055       RegsToPass.push_back(std::make_pair(
3056           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3057                                           getPointerTy(DAG.getDataLayout()))));
3058     } else {
3059       // If we are tail calling and generating PIC/GOT style code load the
3060       // address of the callee into ECX. The value in ecx is used as target of
3061       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3062       // for tail calls on PIC/GOT architectures. Normally we would just put the
3063       // address of GOT into ebx and then call target@PLT. But for tail calls
3064       // ebx would be restored (since ebx is callee saved) before jumping to the
3065       // target@PLT.
3066
3067       // Note: The actual moving to ECX is done further down.
3068       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3069       if (G && !G->getGlobal()->hasLocalLinkage() &&
3070           G->getGlobal()->hasDefaultVisibility())
3071         Callee = LowerGlobalAddress(Callee, DAG);
3072       else if (isa<ExternalSymbolSDNode>(Callee))
3073         Callee = LowerExternalSymbol(Callee, DAG);
3074     }
3075   }
3076
3077   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3078     // From AMD64 ABI document:
3079     // For calls that may call functions that use varargs or stdargs
3080     // (prototype-less calls or calls to functions containing ellipsis (...) in
3081     // the declaration) %al is used as hidden argument to specify the number
3082     // of SSE registers used. The contents of %al do not need to match exactly
3083     // the number of registers, but must be an ubound on the number of SSE
3084     // registers used and is in the range 0 - 8 inclusive.
3085
3086     // Count the number of XMM registers allocated.
3087     static const MCPhysReg XMMArgRegs[] = {
3088       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3089       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3090     };
3091     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3092     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3093            && "SSE registers cannot be used when SSE is disabled");
3094
3095     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3096                                         DAG.getConstant(NumXMMRegs, dl,
3097                                                         MVT::i8)));
3098   }
3099
3100   if (isVarArg && IsMustTail) {
3101     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3102     for (const auto &F : Forwards) {
3103       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3104       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3105     }
3106   }
3107
3108   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3109   // don't need this because the eligibility check rejects calls that require
3110   // shuffling arguments passed in memory.
3111   if (!IsSibcall && isTailCall) {
3112     // Force all the incoming stack arguments to be loaded from the stack
3113     // before any new outgoing arguments are stored to the stack, because the
3114     // outgoing stack slots may alias the incoming argument stack slots, and
3115     // the alias isn't otherwise explicit. This is slightly more conservative
3116     // than necessary, because it means that each store effectively depends
3117     // on every argument instead of just those arguments it would clobber.
3118     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3119
3120     SmallVector<SDValue, 8> MemOpChains2;
3121     SDValue FIN;
3122     int FI = 0;
3123     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3124       CCValAssign &VA = ArgLocs[i];
3125       if (VA.isRegLoc())
3126         continue;
3127       assert(VA.isMemLoc());
3128       SDValue Arg = OutVals[i];
3129       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3130       // Skip inalloca arguments.  They don't require any work.
3131       if (Flags.isInAlloca())
3132         continue;
3133       // Create frame index.
3134       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3135       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3136       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3137       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3138
3139       if (Flags.isByVal()) {
3140         // Copy relative to framepointer.
3141         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3142         if (!StackPtr.getNode())
3143           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3144                                         getPointerTy(DAG.getDataLayout()));
3145         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3146                              StackPtr, Source);
3147
3148         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3149                                                          ArgChain,
3150                                                          Flags, DAG, dl));
3151       } else {
3152         // Store relative to framepointer.
3153         MemOpChains2.push_back(
3154           DAG.getStore(ArgChain, dl, Arg, FIN,
3155                        MachinePointerInfo::getFixedStack(FI),
3156                        false, false, 0));
3157       }
3158     }
3159
3160     if (!MemOpChains2.empty())
3161       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3162
3163     // Store the return address to the appropriate stack slot.
3164     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3165                                      getPointerTy(DAG.getDataLayout()),
3166                                      RegInfo->getSlotSize(), FPDiff, dl);
3167   }
3168
3169   // Build a sequence of copy-to-reg nodes chained together with token chain
3170   // and flag operands which copy the outgoing args into registers.
3171   SDValue InFlag;
3172   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3173     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3174                              RegsToPass[i].second, InFlag);
3175     InFlag = Chain.getValue(1);
3176   }
3177
3178   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3179     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3180     // In the 64-bit large code model, we have to make all calls
3181     // through a register, since the call instruction's 32-bit
3182     // pc-relative offset may not be large enough to hold the whole
3183     // address.
3184   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3185     // If the callee is a GlobalAddress node (quite common, every direct call
3186     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3187     // it.
3188     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3189
3190     // We should use extra load for direct calls to dllimported functions in
3191     // non-JIT mode.
3192     const GlobalValue *GV = G->getGlobal();
3193     if (!GV->hasDLLImportStorageClass()) {
3194       unsigned char OpFlags = 0;
3195       bool ExtraLoad = false;
3196       unsigned WrapperKind = ISD::DELETED_NODE;
3197
3198       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3199       // external symbols most go through the PLT in PIC mode.  If the symbol
3200       // has hidden or protected visibility, or if it is static or local, then
3201       // we don't need to use the PLT - we can directly call it.
3202       if (Subtarget->isTargetELF() &&
3203           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3204           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3205         OpFlags = X86II::MO_PLT;
3206       } else if (Subtarget->isPICStyleStubAny() &&
3207                  !GV->isStrongDefinitionForLinker() &&
3208                  (!Subtarget->getTargetTriple().isMacOSX() ||
3209                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3210         // PC-relative references to external symbols should go through $stub,
3211         // unless we're building with the leopard linker or later, which
3212         // automatically synthesizes these stubs.
3213         OpFlags = X86II::MO_DARWIN_STUB;
3214       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3215                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3216         // If the function is marked as non-lazy, generate an indirect call
3217         // which loads from the GOT directly. This avoids runtime overhead
3218         // at the cost of eager binding (and one extra byte of encoding).
3219         OpFlags = X86II::MO_GOTPCREL;
3220         WrapperKind = X86ISD::WrapperRIP;
3221         ExtraLoad = true;
3222       }
3223
3224       Callee = DAG.getTargetGlobalAddress(
3225           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3226
3227       // Add a wrapper if needed.
3228       if (WrapperKind != ISD::DELETED_NODE)
3229         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3230                              getPointerTy(DAG.getDataLayout()), Callee);
3231       // Add extra indirection if needed.
3232       if (ExtraLoad)
3233         Callee = DAG.getLoad(
3234             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3235             MachinePointerInfo::getGOT(), false, false, false, 0);
3236     }
3237   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3238     unsigned char OpFlags = 0;
3239
3240     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3241     // external symbols should go through the PLT.
3242     if (Subtarget->isTargetELF() &&
3243         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3244       OpFlags = X86II::MO_PLT;
3245     } else if (Subtarget->isPICStyleStubAny() &&
3246                (!Subtarget->getTargetTriple().isMacOSX() ||
3247                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3248       // PC-relative references to external symbols should go through $stub,
3249       // unless we're building with the leopard linker or later, which
3250       // automatically synthesizes these stubs.
3251       OpFlags = X86II::MO_DARWIN_STUB;
3252     }
3253
3254     Callee = DAG.getTargetExternalSymbol(
3255         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3256   } else if (Subtarget->isTarget64BitILP32() &&
3257              Callee->getValueType(0) == MVT::i32) {
3258     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3259     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3260   }
3261
3262   // Returns a chain & a flag for retval copy to use.
3263   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3264   SmallVector<SDValue, 8> Ops;
3265
3266   if (!IsSibcall && isTailCall) {
3267     Chain = DAG.getCALLSEQ_END(Chain,
3268                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3269                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3270     InFlag = Chain.getValue(1);
3271   }
3272
3273   Ops.push_back(Chain);
3274   Ops.push_back(Callee);
3275
3276   if (isTailCall)
3277     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3278
3279   // Add argument registers to the end of the list so that they are known live
3280   // into the call.
3281   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3282     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3283                                   RegsToPass[i].second.getValueType()));
3284
3285   // Add a register mask operand representing the call-preserved registers.
3286   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3287   assert(Mask && "Missing call preserved mask for calling convention");
3288
3289   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3290   // the function clobbers all registers. If an exception is thrown, the runtime
3291   // will not restore CSRs.
3292   // FIXME: Model this more precisely so that we can register allocate across
3293   // the normal edge and spill and fill across the exceptional edge.
3294   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3295     const Function *CallerFn = MF.getFunction();
3296     EHPersonality Pers =
3297         CallerFn->hasPersonalityFn()
3298             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3299             : EHPersonality::Unknown;
3300     if (isMSVCEHPersonality(Pers))
3301       Mask = RegInfo->getNoPreservedMask();
3302   }
3303
3304   Ops.push_back(DAG.getRegisterMask(Mask));
3305
3306   if (InFlag.getNode())
3307     Ops.push_back(InFlag);
3308
3309   if (isTailCall) {
3310     // We used to do:
3311     //// If this is the first return lowered for this function, add the regs
3312     //// to the liveout set for the function.
3313     // This isn't right, although it's probably harmless on x86; liveouts
3314     // should be computed from returns not tail calls.  Consider a void
3315     // function making a tail call to a function returning int.
3316     MF.getFrameInfo()->setHasTailCall();
3317     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3318   }
3319
3320   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3321   InFlag = Chain.getValue(1);
3322
3323   // Create the CALLSEQ_END node.
3324   unsigned NumBytesForCalleeToPop;
3325   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3326                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3327     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3328   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3329            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3330            SR == StackStructReturn)
3331     // If this is a call to a struct-return function, the callee
3332     // pops the hidden struct pointer, so we have to push it back.
3333     // This is common for Darwin/X86, Linux & Mingw32 targets.
3334     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3335     NumBytesForCalleeToPop = 4;
3336   else
3337     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3338
3339   // Returns a flag for retval copy to use.
3340   if (!IsSibcall) {
3341     Chain = DAG.getCALLSEQ_END(Chain,
3342                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3343                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3344                                                      true),
3345                                InFlag, dl);
3346     InFlag = Chain.getValue(1);
3347   }
3348
3349   // Handle result values, copying them out of physregs into vregs that we
3350   // return.
3351   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3352                          Ins, dl, DAG, InVals);
3353 }
3354
3355 //===----------------------------------------------------------------------===//
3356 //                Fast Calling Convention (tail call) implementation
3357 //===----------------------------------------------------------------------===//
3358
3359 //  Like std call, callee cleans arguments, convention except that ECX is
3360 //  reserved for storing the tail called function address. Only 2 registers are
3361 //  free for argument passing (inreg). Tail call optimization is performed
3362 //  provided:
3363 //                * tailcallopt is enabled
3364 //                * caller/callee are fastcc
3365 //  On X86_64 architecture with GOT-style position independent code only local
3366 //  (within module) calls are supported at the moment.
3367 //  To keep the stack aligned according to platform abi the function
3368 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3369 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3370 //  If a tail called function callee has more arguments than the caller the
3371 //  caller needs to make sure that there is room to move the RETADDR to. This is
3372 //  achieved by reserving an area the size of the argument delta right after the
3373 //  original RETADDR, but before the saved framepointer or the spilled registers
3374 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3375 //  stack layout:
3376 //    arg1
3377 //    arg2
3378 //    RETADDR
3379 //    [ new RETADDR
3380 //      move area ]
3381 //    (possible EBP)
3382 //    ESI
3383 //    EDI
3384 //    local1 ..
3385
3386 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3387 /// for a 16 byte align requirement.
3388 unsigned
3389 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3390                                                SelectionDAG& DAG) const {
3391   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3392   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3393   unsigned StackAlignment = TFI.getStackAlignment();
3394   uint64_t AlignMask = StackAlignment - 1;
3395   int64_t Offset = StackSize;
3396   unsigned SlotSize = RegInfo->getSlotSize();
3397   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3398     // Number smaller than 12 so just add the difference.
3399     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3400   } else {
3401     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3402     Offset = ((~AlignMask) & Offset) + StackAlignment +
3403       (StackAlignment-SlotSize);
3404   }
3405   return Offset;
3406 }
3407
3408 /// MatchingStackOffset - Return true if the given stack call argument is
3409 /// already available in the same position (relatively) of the caller's
3410 /// incoming argument stack.
3411 static
3412 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3413                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3414                          const X86InstrInfo *TII) {
3415   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3416   int FI = INT_MAX;
3417   if (Arg.getOpcode() == ISD::CopyFromReg) {
3418     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3419     if (!TargetRegisterInfo::isVirtualRegister(VR))
3420       return false;
3421     MachineInstr *Def = MRI->getVRegDef(VR);
3422     if (!Def)
3423       return false;
3424     if (!Flags.isByVal()) {
3425       if (!TII->isLoadFromStackSlot(Def, FI))
3426         return false;
3427     } else {
3428       unsigned Opcode = Def->getOpcode();
3429       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3430            Opcode == X86::LEA64_32r) &&
3431           Def->getOperand(1).isFI()) {
3432         FI = Def->getOperand(1).getIndex();
3433         Bytes = Flags.getByValSize();
3434       } else
3435         return false;
3436     }
3437   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3438     if (Flags.isByVal())
3439       // ByVal argument is passed in as a pointer but it's now being
3440       // dereferenced. e.g.
3441       // define @foo(%struct.X* %A) {
3442       //   tail call @bar(%struct.X* byval %A)
3443       // }
3444       return false;
3445     SDValue Ptr = Ld->getBasePtr();
3446     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3447     if (!FINode)
3448       return false;
3449     FI = FINode->getIndex();
3450   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3451     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3452     FI = FINode->getIndex();
3453     Bytes = Flags.getByValSize();
3454   } else
3455     return false;
3456
3457   assert(FI != INT_MAX);
3458   if (!MFI->isFixedObjectIndex(FI))
3459     return false;
3460   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3461 }
3462
3463 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3464 /// for tail call optimization. Targets which want to do tail call
3465 /// optimization should implement this function.
3466 bool
3467 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3468                                                      CallingConv::ID CalleeCC,
3469                                                      bool isVarArg,
3470                                                      bool isCalleeStructRet,
3471                                                      bool isCallerStructRet,
3472                                                      Type *RetTy,
3473                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3474                                     const SmallVectorImpl<SDValue> &OutVals,
3475                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3476                                                      SelectionDAG &DAG) const {
3477   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3478     return false;
3479
3480   // If -tailcallopt is specified, make fastcc functions tail-callable.
3481   const MachineFunction &MF = DAG.getMachineFunction();
3482   const Function *CallerF = MF.getFunction();
3483
3484   // If the function return type is x86_fp80 and the callee return type is not,
3485   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3486   // perform a tailcall optimization here.
3487   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3488     return false;
3489
3490   CallingConv::ID CallerCC = CallerF->getCallingConv();
3491   bool CCMatch = CallerCC == CalleeCC;
3492   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3493   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3494
3495   // Win64 functions have extra shadow space for argument homing. Don't do the
3496   // sibcall if the caller and callee have mismatched expectations for this
3497   // space.
3498   if (IsCalleeWin64 != IsCallerWin64)
3499     return false;
3500
3501   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3502     if (IsTailCallConvention(CalleeCC) && CCMatch)
3503       return true;
3504     return false;
3505   }
3506
3507   // Look for obvious safe cases to perform tail call optimization that do not
3508   // require ABI changes. This is what gcc calls sibcall.
3509
3510   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3511   // emit a special epilogue.
3512   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3513   if (RegInfo->needsStackRealignment(MF))
3514     return false;
3515
3516   // Also avoid sibcall optimization if either caller or callee uses struct
3517   // return semantics.
3518   if (isCalleeStructRet || isCallerStructRet)
3519     return false;
3520
3521   // An stdcall/thiscall caller is expected to clean up its arguments; the
3522   // callee isn't going to do that.
3523   // FIXME: this is more restrictive than needed. We could produce a tailcall
3524   // when the stack adjustment matches. For example, with a thiscall that takes
3525   // only one argument.
3526   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3527                    CallerCC == CallingConv::X86_ThisCall))
3528     return false;
3529
3530   // Do not sibcall optimize vararg calls unless all arguments are passed via
3531   // registers.
3532   if (isVarArg && !Outs.empty()) {
3533
3534     // Optimizing for varargs on Win64 is unlikely to be safe without
3535     // additional testing.
3536     if (IsCalleeWin64 || IsCallerWin64)
3537       return false;
3538
3539     SmallVector<CCValAssign, 16> ArgLocs;
3540     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3541                    *DAG.getContext());
3542
3543     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3544     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3545       if (!ArgLocs[i].isRegLoc())
3546         return false;
3547   }
3548
3549   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3550   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3551   // this into a sibcall.
3552   bool Unused = false;
3553   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3554     if (!Ins[i].Used) {
3555       Unused = true;
3556       break;
3557     }
3558   }
3559   if (Unused) {
3560     SmallVector<CCValAssign, 16> RVLocs;
3561     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3562                    *DAG.getContext());
3563     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3564     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3565       CCValAssign &VA = RVLocs[i];
3566       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3567         return false;
3568     }
3569   }
3570
3571   // If the calling conventions do not match, then we'd better make sure the
3572   // results are returned in the same way as what the caller expects.
3573   if (!CCMatch) {
3574     SmallVector<CCValAssign, 16> RVLocs1;
3575     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3576                     *DAG.getContext());
3577     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3578
3579     SmallVector<CCValAssign, 16> RVLocs2;
3580     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3581                     *DAG.getContext());
3582     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3583
3584     if (RVLocs1.size() != RVLocs2.size())
3585       return false;
3586     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3587       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3588         return false;
3589       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3590         return false;
3591       if (RVLocs1[i].isRegLoc()) {
3592         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3593           return false;
3594       } else {
3595         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3596           return false;
3597       }
3598     }
3599   }
3600
3601   // If the callee takes no arguments then go on to check the results of the
3602   // call.
3603   if (!Outs.empty()) {
3604     // Check if stack adjustment is needed. For now, do not do this if any
3605     // argument is passed on the stack.
3606     SmallVector<CCValAssign, 16> ArgLocs;
3607     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3608                    *DAG.getContext());
3609
3610     // Allocate shadow area for Win64
3611     if (IsCalleeWin64)
3612       CCInfo.AllocateStack(32, 8);
3613
3614     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3615     if (CCInfo.getNextStackOffset()) {
3616       MachineFunction &MF = DAG.getMachineFunction();
3617       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3618         return false;
3619
3620       // Check if the arguments are already laid out in the right way as
3621       // the caller's fixed stack objects.
3622       MachineFrameInfo *MFI = MF.getFrameInfo();
3623       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3624       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3625       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3626         CCValAssign &VA = ArgLocs[i];
3627         SDValue Arg = OutVals[i];
3628         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3629         if (VA.getLocInfo() == CCValAssign::Indirect)
3630           return false;
3631         if (!VA.isRegLoc()) {
3632           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3633                                    MFI, MRI, TII))
3634             return false;
3635         }
3636       }
3637     }
3638
3639     // If the tailcall address may be in a register, then make sure it's
3640     // possible to register allocate for it. In 32-bit, the call address can
3641     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3642     // callee-saved registers are restored. These happen to be the same
3643     // registers used to pass 'inreg' arguments so watch out for those.
3644     if (!Subtarget->is64Bit() &&
3645         ((!isa<GlobalAddressSDNode>(Callee) &&
3646           !isa<ExternalSymbolSDNode>(Callee)) ||
3647          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3648       unsigned NumInRegs = 0;
3649       // In PIC we need an extra register to formulate the address computation
3650       // for the callee.
3651       unsigned MaxInRegs =
3652         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3653
3654       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3655         CCValAssign &VA = ArgLocs[i];
3656         if (!VA.isRegLoc())
3657           continue;
3658         unsigned Reg = VA.getLocReg();
3659         switch (Reg) {
3660         default: break;
3661         case X86::EAX: case X86::EDX: case X86::ECX:
3662           if (++NumInRegs == MaxInRegs)
3663             return false;
3664           break;
3665         }
3666       }
3667     }
3668   }
3669
3670   return true;
3671 }
3672
3673 FastISel *
3674 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3675                                   const TargetLibraryInfo *libInfo) const {
3676   return X86::createFastISel(funcInfo, libInfo);
3677 }
3678
3679 //===----------------------------------------------------------------------===//
3680 //                           Other Lowering Hooks
3681 //===----------------------------------------------------------------------===//
3682
3683 static bool MayFoldLoad(SDValue Op) {
3684   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3685 }
3686
3687 static bool MayFoldIntoStore(SDValue Op) {
3688   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3689 }
3690
3691 static bool isTargetShuffle(unsigned Opcode) {
3692   switch(Opcode) {
3693   default: return false;
3694   case X86ISD::BLENDI:
3695   case X86ISD::PSHUFB:
3696   case X86ISD::PSHUFD:
3697   case X86ISD::PSHUFHW:
3698   case X86ISD::PSHUFLW:
3699   case X86ISD::SHUFP:
3700   case X86ISD::PALIGNR:
3701   case X86ISD::MOVLHPS:
3702   case X86ISD::MOVLHPD:
3703   case X86ISD::MOVHLPS:
3704   case X86ISD::MOVLPS:
3705   case X86ISD::MOVLPD:
3706   case X86ISD::MOVSHDUP:
3707   case X86ISD::MOVSLDUP:
3708   case X86ISD::MOVDDUP:
3709   case X86ISD::MOVSS:
3710   case X86ISD::MOVSD:
3711   case X86ISD::UNPCKL:
3712   case X86ISD::UNPCKH:
3713   case X86ISD::VPERMILPI:
3714   case X86ISD::VPERM2X128:
3715   case X86ISD::VPERMI:
3716     return true;
3717   }
3718 }
3719
3720 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3721                                     SDValue V1, unsigned TargetMask,
3722                                     SelectionDAG &DAG) {
3723   switch(Opc) {
3724   default: llvm_unreachable("Unknown x86 shuffle node");
3725   case X86ISD::PSHUFD:
3726   case X86ISD::PSHUFHW:
3727   case X86ISD::PSHUFLW:
3728   case X86ISD::VPERMILPI:
3729   case X86ISD::VPERMI:
3730     return DAG.getNode(Opc, dl, VT, V1,
3731                        DAG.getConstant(TargetMask, dl, MVT::i8));
3732   }
3733 }
3734
3735 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3736                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3737   switch(Opc) {
3738   default: llvm_unreachable("Unknown x86 shuffle node");
3739   case X86ISD::MOVLHPS:
3740   case X86ISD::MOVLHPD:
3741   case X86ISD::MOVHLPS:
3742   case X86ISD::MOVLPS:
3743   case X86ISD::MOVLPD:
3744   case X86ISD::MOVSS:
3745   case X86ISD::MOVSD:
3746   case X86ISD::UNPCKL:
3747   case X86ISD::UNPCKH:
3748     return DAG.getNode(Opc, dl, VT, V1, V2);
3749   }
3750 }
3751
3752 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3753   MachineFunction &MF = DAG.getMachineFunction();
3754   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3755   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3756   int ReturnAddrIndex = FuncInfo->getRAIndex();
3757
3758   if (ReturnAddrIndex == 0) {
3759     // Set up a frame object for the return address.
3760     unsigned SlotSize = RegInfo->getSlotSize();
3761     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3762                                                            -(int64_t)SlotSize,
3763                                                            false);
3764     FuncInfo->setRAIndex(ReturnAddrIndex);
3765   }
3766
3767   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3768 }
3769
3770 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3771                                        bool hasSymbolicDisplacement) {
3772   // Offset should fit into 32 bit immediate field.
3773   if (!isInt<32>(Offset))
3774     return false;
3775
3776   // If we don't have a symbolic displacement - we don't have any extra
3777   // restrictions.
3778   if (!hasSymbolicDisplacement)
3779     return true;
3780
3781   // FIXME: Some tweaks might be needed for medium code model.
3782   if (M != CodeModel::Small && M != CodeModel::Kernel)
3783     return false;
3784
3785   // For small code model we assume that latest object is 16MB before end of 31
3786   // bits boundary. We may also accept pretty large negative constants knowing
3787   // that all objects are in the positive half of address space.
3788   if (M == CodeModel::Small && Offset < 16*1024*1024)
3789     return true;
3790
3791   // For kernel code model we know that all object resist in the negative half
3792   // of 32bits address space. We may not accept negative offsets, since they may
3793   // be just off and we may accept pretty large positive ones.
3794   if (M == CodeModel::Kernel && Offset >= 0)
3795     return true;
3796
3797   return false;
3798 }
3799
3800 /// isCalleePop - Determines whether the callee is required to pop its
3801 /// own arguments. Callee pop is necessary to support tail calls.
3802 bool X86::isCalleePop(CallingConv::ID CallingConv,
3803                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3804   switch (CallingConv) {
3805   default:
3806     return false;
3807   case CallingConv::X86_StdCall:
3808   case CallingConv::X86_FastCall:
3809   case CallingConv::X86_ThisCall:
3810     return !is64Bit;
3811   case CallingConv::Fast:
3812   case CallingConv::GHC:
3813   case CallingConv::HiPE:
3814     if (IsVarArg)
3815       return false;
3816     return TailCallOpt;
3817   }
3818 }
3819
3820 /// \brief Return true if the condition is an unsigned comparison operation.
3821 static bool isX86CCUnsigned(unsigned X86CC) {
3822   switch (X86CC) {
3823   default: llvm_unreachable("Invalid integer condition!");
3824   case X86::COND_E:     return true;
3825   case X86::COND_G:     return false;
3826   case X86::COND_GE:    return false;
3827   case X86::COND_L:     return false;
3828   case X86::COND_LE:    return false;
3829   case X86::COND_NE:    return true;
3830   case X86::COND_B:     return true;
3831   case X86::COND_A:     return true;
3832   case X86::COND_BE:    return true;
3833   case X86::COND_AE:    return true;
3834   }
3835   llvm_unreachable("covered switch fell through?!");
3836 }
3837
3838 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3839 /// specific condition code, returning the condition code and the LHS/RHS of the
3840 /// comparison to make.
3841 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3842                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3843   if (!isFP) {
3844     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3845       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3846         // X > -1   -> X == 0, jump !sign.
3847         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3848         return X86::COND_NS;
3849       }
3850       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3851         // X < 0   -> X == 0, jump on sign.
3852         return X86::COND_S;
3853       }
3854       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3855         // X < 1   -> X <= 0
3856         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3857         return X86::COND_LE;
3858       }
3859     }
3860
3861     switch (SetCCOpcode) {
3862     default: llvm_unreachable("Invalid integer condition!");
3863     case ISD::SETEQ:  return X86::COND_E;
3864     case ISD::SETGT:  return X86::COND_G;
3865     case ISD::SETGE:  return X86::COND_GE;
3866     case ISD::SETLT:  return X86::COND_L;
3867     case ISD::SETLE:  return X86::COND_LE;
3868     case ISD::SETNE:  return X86::COND_NE;
3869     case ISD::SETULT: return X86::COND_B;
3870     case ISD::SETUGT: return X86::COND_A;
3871     case ISD::SETULE: return X86::COND_BE;
3872     case ISD::SETUGE: return X86::COND_AE;
3873     }
3874   }
3875
3876   // First determine if it is required or is profitable to flip the operands.
3877
3878   // If LHS is a foldable load, but RHS is not, flip the condition.
3879   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3880       !ISD::isNON_EXTLoad(RHS.getNode())) {
3881     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3882     std::swap(LHS, RHS);
3883   }
3884
3885   switch (SetCCOpcode) {
3886   default: break;
3887   case ISD::SETOLT:
3888   case ISD::SETOLE:
3889   case ISD::SETUGT:
3890   case ISD::SETUGE:
3891     std::swap(LHS, RHS);
3892     break;
3893   }
3894
3895   // On a floating point condition, the flags are set as follows:
3896   // ZF  PF  CF   op
3897   //  0 | 0 | 0 | X > Y
3898   //  0 | 0 | 1 | X < Y
3899   //  1 | 0 | 0 | X == Y
3900   //  1 | 1 | 1 | unordered
3901   switch (SetCCOpcode) {
3902   default: llvm_unreachable("Condcode should be pre-legalized away");
3903   case ISD::SETUEQ:
3904   case ISD::SETEQ:   return X86::COND_E;
3905   case ISD::SETOLT:              // flipped
3906   case ISD::SETOGT:
3907   case ISD::SETGT:   return X86::COND_A;
3908   case ISD::SETOLE:              // flipped
3909   case ISD::SETOGE:
3910   case ISD::SETGE:   return X86::COND_AE;
3911   case ISD::SETUGT:              // flipped
3912   case ISD::SETULT:
3913   case ISD::SETLT:   return X86::COND_B;
3914   case ISD::SETUGE:              // flipped
3915   case ISD::SETULE:
3916   case ISD::SETLE:   return X86::COND_BE;
3917   case ISD::SETONE:
3918   case ISD::SETNE:   return X86::COND_NE;
3919   case ISD::SETUO:   return X86::COND_P;
3920   case ISD::SETO:    return X86::COND_NP;
3921   case ISD::SETOEQ:
3922   case ISD::SETUNE:  return X86::COND_INVALID;
3923   }
3924 }
3925
3926 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3927 /// code. Current x86 isa includes the following FP cmov instructions:
3928 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3929 static bool hasFPCMov(unsigned X86CC) {
3930   switch (X86CC) {
3931   default:
3932     return false;
3933   case X86::COND_B:
3934   case X86::COND_BE:
3935   case X86::COND_E:
3936   case X86::COND_P:
3937   case X86::COND_A:
3938   case X86::COND_AE:
3939   case X86::COND_NE:
3940   case X86::COND_NP:
3941     return true;
3942   }
3943 }
3944
3945 /// isFPImmLegal - Returns true if the target can instruction select the
3946 /// specified FP immediate natively. If false, the legalizer will
3947 /// materialize the FP immediate as a load from a constant pool.
3948 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3949   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3950     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3951       return true;
3952   }
3953   return false;
3954 }
3955
3956 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3957                                               ISD::LoadExtType ExtTy,
3958                                               EVT NewVT) const {
3959   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3960   // relocation target a movq or addq instruction: don't let the load shrink.
3961   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3962   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3963     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3964       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3965   return true;
3966 }
3967
3968 /// \brief Returns true if it is beneficial to convert a load of a constant
3969 /// to just the constant itself.
3970 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3971                                                           Type *Ty) const {
3972   assert(Ty->isIntegerTy());
3973
3974   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3975   if (BitSize == 0 || BitSize > 64)
3976     return false;
3977   return true;
3978 }
3979
3980 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3981                                                 unsigned Index) const {
3982   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3983     return false;
3984
3985   return (Index == 0 || Index == ResVT.getVectorNumElements());
3986 }
3987
3988 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3989   // Speculate cttz only if we can directly use TZCNT.
3990   return Subtarget->hasBMI();
3991 }
3992
3993 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3994   // Speculate ctlz only if we can directly use LZCNT.
3995   return Subtarget->hasLZCNT();
3996 }
3997
3998 /// isUndefInRange - Return true if every element in Mask, beginning
3999 /// from position Pos and ending in Pos+Size is undef.
4000 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4001   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4002     if (0 <= Mask[i])
4003       return false;
4004   return true;
4005 }
4006
4007 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
4008 /// the specified range (L, H].
4009 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4010   return (Val < 0) || (Val >= Low && Val < Hi);
4011 }
4012
4013 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
4014 /// specified value.
4015 static bool isUndefOrEqual(int Val, int CmpVal) {
4016   return (Val < 0 || Val == CmpVal);
4017 }
4018
4019 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
4020 /// from position Pos and ending in Pos+Size, falls within the specified
4021 /// sequential range (Low, Low+Size]. or is undef.
4022 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4023                                        unsigned Pos, unsigned Size, int Low) {
4024   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4025     if (!isUndefOrEqual(Mask[i], Low))
4026       return false;
4027   return true;
4028 }
4029
4030 /// isVEXTRACTIndex - Return true if the specified
4031 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4032 /// suitable for instruction that extract 128 or 256 bit vectors
4033 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4034   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4035   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4036     return false;
4037
4038   // The index should be aligned on a vecWidth-bit boundary.
4039   uint64_t Index =
4040     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4041
4042   MVT VT = N->getSimpleValueType(0);
4043   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4044   bool Result = (Index * ElSize) % vecWidth == 0;
4045
4046   return Result;
4047 }
4048
4049 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4050 /// operand specifies a subvector insert that is suitable for input to
4051 /// insertion of 128 or 256-bit subvectors
4052 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4053   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4054   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4055     return false;
4056   // The index should be aligned on a vecWidth-bit boundary.
4057   uint64_t Index =
4058     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4059
4060   MVT VT = N->getSimpleValueType(0);
4061   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4062   bool Result = (Index * ElSize) % vecWidth == 0;
4063
4064   return Result;
4065 }
4066
4067 bool X86::isVINSERT128Index(SDNode *N) {
4068   return isVINSERTIndex(N, 128);
4069 }
4070
4071 bool X86::isVINSERT256Index(SDNode *N) {
4072   return isVINSERTIndex(N, 256);
4073 }
4074
4075 bool X86::isVEXTRACT128Index(SDNode *N) {
4076   return isVEXTRACTIndex(N, 128);
4077 }
4078
4079 bool X86::isVEXTRACT256Index(SDNode *N) {
4080   return isVEXTRACTIndex(N, 256);
4081 }
4082
4083 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4084   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4085   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4086     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4087
4088   uint64_t Index =
4089     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4090
4091   MVT VecVT = N->getOperand(0).getSimpleValueType();
4092   MVT ElVT = VecVT.getVectorElementType();
4093
4094   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4095   return Index / NumElemsPerChunk;
4096 }
4097
4098 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4099   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4100   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4101     llvm_unreachable("Illegal insert subvector for VINSERT");
4102
4103   uint64_t Index =
4104     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4105
4106   MVT VecVT = N->getSimpleValueType(0);
4107   MVT ElVT = VecVT.getVectorElementType();
4108
4109   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4110   return Index / NumElemsPerChunk;
4111 }
4112
4113 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4114 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4115 /// and VINSERTI128 instructions.
4116 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4117   return getExtractVEXTRACTImmediate(N, 128);
4118 }
4119
4120 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4121 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4122 /// and VINSERTI64x4 instructions.
4123 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4124   return getExtractVEXTRACTImmediate(N, 256);
4125 }
4126
4127 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4128 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4129 /// and VINSERTI128 instructions.
4130 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4131   return getInsertVINSERTImmediate(N, 128);
4132 }
4133
4134 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4135 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4136 /// and VINSERTI64x4 instructions.
4137 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4138   return getInsertVINSERTImmediate(N, 256);
4139 }
4140
4141 /// isZero - Returns true if Elt is a constant integer zero
4142 static bool isZero(SDValue V) {
4143   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4144   return C && C->isNullValue();
4145 }
4146
4147 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4148 /// constant +0.0.
4149 bool X86::isZeroNode(SDValue Elt) {
4150   if (isZero(Elt))
4151     return true;
4152   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4153     return CFP->getValueAPF().isPosZero();
4154   return false;
4155 }
4156
4157 /// getZeroVector - Returns a vector of specified type with all zero elements.
4158 ///
4159 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4160                              SelectionDAG &DAG, SDLoc dl) {
4161   assert(VT.isVector() && "Expected a vector type");
4162
4163   // Always build SSE zero vectors as <4 x i32> bitcasted
4164   // to their dest type. This ensures they get CSE'd.
4165   SDValue Vec;
4166   if (VT.is128BitVector()) {  // SSE
4167     if (Subtarget->hasSSE2()) {  // SSE2
4168       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4169       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4170     } else { // SSE1
4171       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4172       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4173     }
4174   } else if (VT.is256BitVector()) { // AVX
4175     if (Subtarget->hasInt256()) { // AVX2
4176       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4177       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4178       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4179     } else {
4180       // 256-bit logic and arithmetic instructions in AVX are all
4181       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4182       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4183       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4184       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4185     }
4186   } else if (VT.is512BitVector()) { // AVX-512
4187       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4188       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4189                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4190       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4191   } else if (VT.getScalarType() == MVT::i1) {
4192
4193     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4194             && "Unexpected vector type");
4195     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4196             && "Unexpected vector type");
4197     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4198     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4199     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4200   } else
4201     llvm_unreachable("Unexpected vector type");
4202
4203   return DAG.getBitcast(VT, Vec);
4204 }
4205
4206 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4207                                 SelectionDAG &DAG, SDLoc dl,
4208                                 unsigned vectorWidth) {
4209   assert((vectorWidth == 128 || vectorWidth == 256) &&
4210          "Unsupported vector width");
4211   EVT VT = Vec.getValueType();
4212   EVT ElVT = VT.getVectorElementType();
4213   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4214   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4215                                   VT.getVectorNumElements()/Factor);
4216
4217   // Extract from UNDEF is UNDEF.
4218   if (Vec.getOpcode() == ISD::UNDEF)
4219     return DAG.getUNDEF(ResultVT);
4220
4221   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4222   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4223
4224   // This is the index of the first element of the vectorWidth-bit chunk
4225   // we want.
4226   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4227                                * ElemsPerChunk);
4228
4229   // If the input is a buildvector just emit a smaller one.
4230   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4231     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4232                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4233                                     ElemsPerChunk));
4234
4235   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4236   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4237 }
4238
4239 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4240 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4241 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4242 /// instructions or a simple subregister reference. Idx is an index in the
4243 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4244 /// lowering EXTRACT_VECTOR_ELT operations easier.
4245 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4246                                    SelectionDAG &DAG, SDLoc dl) {
4247   assert((Vec.getValueType().is256BitVector() ||
4248           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4249   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4250 }
4251
4252 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4253 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4254                                    SelectionDAG &DAG, SDLoc dl) {
4255   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4256   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4257 }
4258
4259 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4260                                unsigned IdxVal, SelectionDAG &DAG,
4261                                SDLoc dl, unsigned vectorWidth) {
4262   assert((vectorWidth == 128 || vectorWidth == 256) &&
4263          "Unsupported vector width");
4264   // Inserting UNDEF is Result
4265   if (Vec.getOpcode() == ISD::UNDEF)
4266     return Result;
4267   EVT VT = Vec.getValueType();
4268   EVT ElVT = VT.getVectorElementType();
4269   EVT ResultVT = Result.getValueType();
4270
4271   // Insert the relevant vectorWidth bits.
4272   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4273
4274   // This is the index of the first element of the vectorWidth-bit chunk
4275   // we want.
4276   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4277                                * ElemsPerChunk);
4278
4279   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4280   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4281 }
4282
4283 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4284 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4285 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4286 /// simple superregister reference.  Idx is an index in the 128 bits
4287 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4288 /// lowering INSERT_VECTOR_ELT operations easier.
4289 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4290                                   SelectionDAG &DAG, SDLoc dl) {
4291   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4292
4293   // For insertion into the zero index (low half) of a 256-bit vector, it is
4294   // more efficient to generate a blend with immediate instead of an insert*128.
4295   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4296   // extend the subvector to the size of the result vector. Make sure that
4297   // we are not recursing on that node by checking for undef here.
4298   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4299       Result.getOpcode() != ISD::UNDEF) {
4300     EVT ResultVT = Result.getValueType();
4301     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4302     SDValue Undef = DAG.getUNDEF(ResultVT);
4303     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4304                                  Vec, ZeroIndex);
4305
4306     // The blend instruction, and therefore its mask, depend on the data type.
4307     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4308     if (ScalarType.isFloatingPoint()) {
4309       // Choose either vblendps (float) or vblendpd (double).
4310       unsigned ScalarSize = ScalarType.getSizeInBits();
4311       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4312       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4313       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4314       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4315     }
4316
4317     const X86Subtarget &Subtarget =
4318     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4319
4320     // AVX2 is needed for 256-bit integer blend support.
4321     // Integers must be cast to 32-bit because there is only vpblendd;
4322     // vpblendw can't be used for this because it has a handicapped mask.
4323
4324     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4325     // is still more efficient than using the wrong domain vinsertf128 that
4326     // will be created by InsertSubVector().
4327     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4328
4329     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4330     Vec256 = DAG.getBitcast(CastVT, Vec256);
4331     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4332     return DAG.getBitcast(ResultVT, Vec256);
4333   }
4334
4335   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4336 }
4337
4338 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4339                                   SelectionDAG &DAG, SDLoc dl) {
4340   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4341   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4342 }
4343
4344 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4345 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4346 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4347 /// large BUILD_VECTORS.
4348 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4349                                    unsigned NumElems, SelectionDAG &DAG,
4350                                    SDLoc dl) {
4351   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4352   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4353 }
4354
4355 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4356                                    unsigned NumElems, SelectionDAG &DAG,
4357                                    SDLoc dl) {
4358   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4359   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4360 }
4361
4362 /// getOnesVector - Returns a vector of specified type with all bits set.
4363 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4364 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4365 /// Then bitcast to their original type, ensuring they get CSE'd.
4366 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4367                              SDLoc dl) {
4368   assert(VT.isVector() && "Expected a vector type");
4369
4370   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4371   SDValue Vec;
4372   if (VT.is256BitVector()) {
4373     if (HasInt256) { // AVX2
4374       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4375       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4376     } else { // AVX
4377       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4378       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4379     }
4380   } else if (VT.is128BitVector()) {
4381     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4382   } else
4383     llvm_unreachable("Unexpected vector type");
4384
4385   return DAG.getBitcast(VT, Vec);
4386 }
4387
4388 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4389 /// operation of specified width.
4390 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4391                        SDValue V2) {
4392   unsigned NumElems = VT.getVectorNumElements();
4393   SmallVector<int, 8> Mask;
4394   Mask.push_back(NumElems);
4395   for (unsigned i = 1; i != NumElems; ++i)
4396     Mask.push_back(i);
4397   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4398 }
4399
4400 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4401 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4402                           SDValue V2) {
4403   unsigned NumElems = VT.getVectorNumElements();
4404   SmallVector<int, 8> Mask;
4405   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4406     Mask.push_back(i);
4407     Mask.push_back(i + NumElems);
4408   }
4409   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4410 }
4411
4412 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4413 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4414                           SDValue V2) {
4415   unsigned NumElems = VT.getVectorNumElements();
4416   SmallVector<int, 8> Mask;
4417   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4418     Mask.push_back(i + Half);
4419     Mask.push_back(i + NumElems + Half);
4420   }
4421   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4422 }
4423
4424 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4425 /// vector of zero or undef vector.  This produces a shuffle where the low
4426 /// element of V2 is swizzled into the zero/undef vector, landing at element
4427 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4428 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4429                                            bool IsZero,
4430                                            const X86Subtarget *Subtarget,
4431                                            SelectionDAG &DAG) {
4432   MVT VT = V2.getSimpleValueType();
4433   SDValue V1 = IsZero
4434     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4435   unsigned NumElems = VT.getVectorNumElements();
4436   SmallVector<int, 16> MaskVec;
4437   for (unsigned i = 0; i != NumElems; ++i)
4438     // If this is the insertion idx, put the low elt of V2 here.
4439     MaskVec.push_back(i == Idx ? NumElems : i);
4440   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4441 }
4442
4443 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4444 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4445 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4446 /// shuffles which use a single input multiple times, and in those cases it will
4447 /// adjust the mask to only have indices within that single input.
4448 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4449 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4450                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4451   unsigned NumElems = VT.getVectorNumElements();
4452   SDValue ImmN;
4453
4454   IsUnary = false;
4455   bool IsFakeUnary = false;
4456   switch(N->getOpcode()) {
4457   case X86ISD::BLENDI:
4458     ImmN = N->getOperand(N->getNumOperands()-1);
4459     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4460     break;
4461   case X86ISD::SHUFP:
4462     ImmN = N->getOperand(N->getNumOperands()-1);
4463     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4464     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4465     break;
4466   case X86ISD::UNPCKH:
4467     DecodeUNPCKHMask(VT, Mask);
4468     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4469     break;
4470   case X86ISD::UNPCKL:
4471     DecodeUNPCKLMask(VT, Mask);
4472     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4473     break;
4474   case X86ISD::MOVHLPS:
4475     DecodeMOVHLPSMask(NumElems, Mask);
4476     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4477     break;
4478   case X86ISD::MOVLHPS:
4479     DecodeMOVLHPSMask(NumElems, Mask);
4480     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4481     break;
4482   case X86ISD::PALIGNR:
4483     ImmN = N->getOperand(N->getNumOperands()-1);
4484     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4485     break;
4486   case X86ISD::PSHUFD:
4487   case X86ISD::VPERMILPI:
4488     ImmN = N->getOperand(N->getNumOperands()-1);
4489     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4490     IsUnary = true;
4491     break;
4492   case X86ISD::PSHUFHW:
4493     ImmN = N->getOperand(N->getNumOperands()-1);
4494     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4495     IsUnary = true;
4496     break;
4497   case X86ISD::PSHUFLW:
4498     ImmN = N->getOperand(N->getNumOperands()-1);
4499     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4500     IsUnary = true;
4501     break;
4502   case X86ISD::PSHUFB: {
4503     IsUnary = true;
4504     SDValue MaskNode = N->getOperand(1);
4505     while (MaskNode->getOpcode() == ISD::BITCAST)
4506       MaskNode = MaskNode->getOperand(0);
4507
4508     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4509       // If we have a build-vector, then things are easy.
4510       EVT VT = MaskNode.getValueType();
4511       assert(VT.isVector() &&
4512              "Can't produce a non-vector with a build_vector!");
4513       if (!VT.isInteger())
4514         return false;
4515
4516       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4517
4518       SmallVector<uint64_t, 32> RawMask;
4519       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4520         SDValue Op = MaskNode->getOperand(i);
4521         if (Op->getOpcode() == ISD::UNDEF) {
4522           RawMask.push_back((uint64_t)SM_SentinelUndef);
4523           continue;
4524         }
4525         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4526         if (!CN)
4527           return false;
4528         APInt MaskElement = CN->getAPIntValue();
4529
4530         // We now have to decode the element which could be any integer size and
4531         // extract each byte of it.
4532         for (int j = 0; j < NumBytesPerElement; ++j) {
4533           // Note that this is x86 and so always little endian: the low byte is
4534           // the first byte of the mask.
4535           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4536           MaskElement = MaskElement.lshr(8);
4537         }
4538       }
4539       DecodePSHUFBMask(RawMask, Mask);
4540       break;
4541     }
4542
4543     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4544     if (!MaskLoad)
4545       return false;
4546
4547     SDValue Ptr = MaskLoad->getBasePtr();
4548     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4549         Ptr->getOpcode() == X86ISD::WrapperRIP)
4550       Ptr = Ptr->getOperand(0);
4551
4552     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4553     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4554       return false;
4555
4556     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4557       DecodePSHUFBMask(C, Mask);
4558       if (Mask.empty())
4559         return false;
4560       break;
4561     }
4562
4563     return false;
4564   }
4565   case X86ISD::VPERMI:
4566     ImmN = N->getOperand(N->getNumOperands()-1);
4567     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4568     IsUnary = true;
4569     break;
4570   case X86ISD::MOVSS:
4571   case X86ISD::MOVSD:
4572     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4573     break;
4574   case X86ISD::VPERM2X128:
4575     ImmN = N->getOperand(N->getNumOperands()-1);
4576     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4577     if (Mask.empty()) return false;
4578     // Mask only contains negative index if an element is zero.
4579     if (std::any_of(Mask.begin(), Mask.end(),
4580                     [](int M){ return M == SM_SentinelZero; }))
4581       return false;
4582     break;
4583   case X86ISD::MOVSLDUP:
4584     DecodeMOVSLDUPMask(VT, Mask);
4585     IsUnary = true;
4586     break;
4587   case X86ISD::MOVSHDUP:
4588     DecodeMOVSHDUPMask(VT, Mask);
4589     IsUnary = true;
4590     break;
4591   case X86ISD::MOVDDUP:
4592     DecodeMOVDDUPMask(VT, Mask);
4593     IsUnary = true;
4594     break;
4595   case X86ISD::MOVLHPD:
4596   case X86ISD::MOVLPD:
4597   case X86ISD::MOVLPS:
4598     // Not yet implemented
4599     return false;
4600   default: llvm_unreachable("unknown target shuffle node");
4601   }
4602
4603   // If we have a fake unary shuffle, the shuffle mask is spread across two
4604   // inputs that are actually the same node. Re-map the mask to always point
4605   // into the first input.
4606   if (IsFakeUnary)
4607     for (int &M : Mask)
4608       if (M >= (int)Mask.size())
4609         M -= Mask.size();
4610
4611   return true;
4612 }
4613
4614 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4615 /// element of the result of the vector shuffle.
4616 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4617                                    unsigned Depth) {
4618   if (Depth == 6)
4619     return SDValue();  // Limit search depth.
4620
4621   SDValue V = SDValue(N, 0);
4622   EVT VT = V.getValueType();
4623   unsigned Opcode = V.getOpcode();
4624
4625   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4626   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4627     int Elt = SV->getMaskElt(Index);
4628
4629     if (Elt < 0)
4630       return DAG.getUNDEF(VT.getVectorElementType());
4631
4632     unsigned NumElems = VT.getVectorNumElements();
4633     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4634                                          : SV->getOperand(1);
4635     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4636   }
4637
4638   // Recurse into target specific vector shuffles to find scalars.
4639   if (isTargetShuffle(Opcode)) {
4640     MVT ShufVT = V.getSimpleValueType();
4641     unsigned NumElems = ShufVT.getVectorNumElements();
4642     SmallVector<int, 16> ShuffleMask;
4643     bool IsUnary;
4644
4645     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4646       return SDValue();
4647
4648     int Elt = ShuffleMask[Index];
4649     if (Elt < 0)
4650       return DAG.getUNDEF(ShufVT.getVectorElementType());
4651
4652     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4653                                          : N->getOperand(1);
4654     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4655                                Depth+1);
4656   }
4657
4658   // Actual nodes that may contain scalar elements
4659   if (Opcode == ISD::BITCAST) {
4660     V = V.getOperand(0);
4661     EVT SrcVT = V.getValueType();
4662     unsigned NumElems = VT.getVectorNumElements();
4663
4664     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4665       return SDValue();
4666   }
4667
4668   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4669     return (Index == 0) ? V.getOperand(0)
4670                         : DAG.getUNDEF(VT.getVectorElementType());
4671
4672   if (V.getOpcode() == ISD::BUILD_VECTOR)
4673     return V.getOperand(Index);
4674
4675   return SDValue();
4676 }
4677
4678 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4679 ///
4680 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4681                                        unsigned NumNonZero, unsigned NumZero,
4682                                        SelectionDAG &DAG,
4683                                        const X86Subtarget* Subtarget,
4684                                        const TargetLowering &TLI) {
4685   if (NumNonZero > 8)
4686     return SDValue();
4687
4688   SDLoc dl(Op);
4689   SDValue V;
4690   bool First = true;
4691
4692   // SSE4.1 - use PINSRB to insert each byte directly.
4693   if (Subtarget->hasSSE41()) {
4694     for (unsigned i = 0; i < 16; ++i) {
4695       bool isNonZero = (NonZeros & (1 << i)) != 0;
4696       if (isNonZero) {
4697         if (First) {
4698           if (NumZero)
4699             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4700           else
4701             V = DAG.getUNDEF(MVT::v16i8);
4702           First = false;
4703         }
4704         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4705                         MVT::v16i8, V, Op.getOperand(i),
4706                         DAG.getIntPtrConstant(i, dl));
4707       }
4708     }
4709
4710     return V;
4711   }
4712
4713   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4714   for (unsigned i = 0; i < 16; ++i) {
4715     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4716     if (ThisIsNonZero && First) {
4717       if (NumZero)
4718         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4719       else
4720         V = DAG.getUNDEF(MVT::v8i16);
4721       First = false;
4722     }
4723
4724     if ((i & 1) != 0) {
4725       SDValue ThisElt, LastElt;
4726       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4727       if (LastIsNonZero) {
4728         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4729                               MVT::i16, Op.getOperand(i-1));
4730       }
4731       if (ThisIsNonZero) {
4732         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4733         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4734                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4735         if (LastIsNonZero)
4736           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4737       } else
4738         ThisElt = LastElt;
4739
4740       if (ThisElt.getNode())
4741         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4742                         DAG.getIntPtrConstant(i/2, dl));
4743     }
4744   }
4745
4746   return DAG.getBitcast(MVT::v16i8, V);
4747 }
4748
4749 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4750 ///
4751 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4752                                      unsigned NumNonZero, unsigned NumZero,
4753                                      SelectionDAG &DAG,
4754                                      const X86Subtarget* Subtarget,
4755                                      const TargetLowering &TLI) {
4756   if (NumNonZero > 4)
4757     return SDValue();
4758
4759   SDLoc dl(Op);
4760   SDValue V;
4761   bool First = true;
4762   for (unsigned i = 0; i < 8; ++i) {
4763     bool isNonZero = (NonZeros & (1 << i)) != 0;
4764     if (isNonZero) {
4765       if (First) {
4766         if (NumZero)
4767           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4768         else
4769           V = DAG.getUNDEF(MVT::v8i16);
4770         First = false;
4771       }
4772       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4773                       MVT::v8i16, V, Op.getOperand(i),
4774                       DAG.getIntPtrConstant(i, dl));
4775     }
4776   }
4777
4778   return V;
4779 }
4780
4781 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4782 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4783                                      const X86Subtarget *Subtarget,
4784                                      const TargetLowering &TLI) {
4785   // Find all zeroable elements.
4786   std::bitset<4> Zeroable;
4787   for (int i=0; i < 4; ++i) {
4788     SDValue Elt = Op->getOperand(i);
4789     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4790   }
4791   assert(Zeroable.size() - Zeroable.count() > 1 &&
4792          "We expect at least two non-zero elements!");
4793
4794   // We only know how to deal with build_vector nodes where elements are either
4795   // zeroable or extract_vector_elt with constant index.
4796   SDValue FirstNonZero;
4797   unsigned FirstNonZeroIdx;
4798   for (unsigned i=0; i < 4; ++i) {
4799     if (Zeroable[i])
4800       continue;
4801     SDValue Elt = Op->getOperand(i);
4802     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4803         !isa<ConstantSDNode>(Elt.getOperand(1)))
4804       return SDValue();
4805     // Make sure that this node is extracting from a 128-bit vector.
4806     MVT VT = Elt.getOperand(0).getSimpleValueType();
4807     if (!VT.is128BitVector())
4808       return SDValue();
4809     if (!FirstNonZero.getNode()) {
4810       FirstNonZero = Elt;
4811       FirstNonZeroIdx = i;
4812     }
4813   }
4814
4815   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4816   SDValue V1 = FirstNonZero.getOperand(0);
4817   MVT VT = V1.getSimpleValueType();
4818
4819   // See if this build_vector can be lowered as a blend with zero.
4820   SDValue Elt;
4821   unsigned EltMaskIdx, EltIdx;
4822   int Mask[4];
4823   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4824     if (Zeroable[EltIdx]) {
4825       // The zero vector will be on the right hand side.
4826       Mask[EltIdx] = EltIdx+4;
4827       continue;
4828     }
4829
4830     Elt = Op->getOperand(EltIdx);
4831     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4832     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4833     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4834       break;
4835     Mask[EltIdx] = EltIdx;
4836   }
4837
4838   if (EltIdx == 4) {
4839     // Let the shuffle legalizer deal with blend operations.
4840     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4841     if (V1.getSimpleValueType() != VT)
4842       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4843     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4844   }
4845
4846   // See if we can lower this build_vector to a INSERTPS.
4847   if (!Subtarget->hasSSE41())
4848     return SDValue();
4849
4850   SDValue V2 = Elt.getOperand(0);
4851   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4852     V1 = SDValue();
4853
4854   bool CanFold = true;
4855   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4856     if (Zeroable[i])
4857       continue;
4858
4859     SDValue Current = Op->getOperand(i);
4860     SDValue SrcVector = Current->getOperand(0);
4861     if (!V1.getNode())
4862       V1 = SrcVector;
4863     CanFold = SrcVector == V1 &&
4864       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4865   }
4866
4867   if (!CanFold)
4868     return SDValue();
4869
4870   assert(V1.getNode() && "Expected at least two non-zero elements!");
4871   if (V1.getSimpleValueType() != MVT::v4f32)
4872     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4873   if (V2.getSimpleValueType() != MVT::v4f32)
4874     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4875
4876   // Ok, we can emit an INSERTPS instruction.
4877   unsigned ZMask = Zeroable.to_ulong();
4878
4879   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4880   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4881   SDLoc DL(Op);
4882   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4883                                DAG.getIntPtrConstant(InsertPSMask, DL));
4884   return DAG.getBitcast(VT, Result);
4885 }
4886
4887 /// Return a vector logical shift node.
4888 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4889                          unsigned NumBits, SelectionDAG &DAG,
4890                          const TargetLowering &TLI, SDLoc dl) {
4891   assert(VT.is128BitVector() && "Unknown type for VShift");
4892   MVT ShVT = MVT::v2i64;
4893   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4894   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4895   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4896   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4897   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4898   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4899 }
4900
4901 static SDValue
4902 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4903
4904   // Check if the scalar load can be widened into a vector load. And if
4905   // the address is "base + cst" see if the cst can be "absorbed" into
4906   // the shuffle mask.
4907   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4908     SDValue Ptr = LD->getBasePtr();
4909     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4910       return SDValue();
4911     EVT PVT = LD->getValueType(0);
4912     if (PVT != MVT::i32 && PVT != MVT::f32)
4913       return SDValue();
4914
4915     int FI = -1;
4916     int64_t Offset = 0;
4917     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4918       FI = FINode->getIndex();
4919       Offset = 0;
4920     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4921                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4922       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4923       Offset = Ptr.getConstantOperandVal(1);
4924       Ptr = Ptr.getOperand(0);
4925     } else {
4926       return SDValue();
4927     }
4928
4929     // FIXME: 256-bit vector instructions don't require a strict alignment,
4930     // improve this code to support it better.
4931     unsigned RequiredAlign = VT.getSizeInBits()/8;
4932     SDValue Chain = LD->getChain();
4933     // Make sure the stack object alignment is at least 16 or 32.
4934     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4935     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4936       if (MFI->isFixedObjectIndex(FI)) {
4937         // Can't change the alignment. FIXME: It's possible to compute
4938         // the exact stack offset and reference FI + adjust offset instead.
4939         // If someone *really* cares about this. That's the way to implement it.
4940         return SDValue();
4941       } else {
4942         MFI->setObjectAlignment(FI, RequiredAlign);
4943       }
4944     }
4945
4946     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4947     // Ptr + (Offset & ~15).
4948     if (Offset < 0)
4949       return SDValue();
4950     if ((Offset % RequiredAlign) & 3)
4951       return SDValue();
4952     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4953     if (StartOffset) {
4954       SDLoc DL(Ptr);
4955       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4956                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4957     }
4958
4959     int EltNo = (Offset - StartOffset) >> 2;
4960     unsigned NumElems = VT.getVectorNumElements();
4961
4962     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4963     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4964                              LD->getPointerInfo().getWithOffset(StartOffset),
4965                              false, false, false, 0);
4966
4967     SmallVector<int, 8> Mask(NumElems, EltNo);
4968
4969     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4970   }
4971
4972   return SDValue();
4973 }
4974
4975 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4976 /// elements can be replaced by a single large load which has the same value as
4977 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4978 ///
4979 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4980 ///
4981 /// FIXME: we'd also like to handle the case where the last elements are zero
4982 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4983 /// There's even a handy isZeroNode for that purpose.
4984 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4985                                         SDLoc &DL, SelectionDAG &DAG,
4986                                         bool isAfterLegalize) {
4987   unsigned NumElems = Elts.size();
4988
4989   LoadSDNode *LDBase = nullptr;
4990   unsigned LastLoadedElt = -1U;
4991
4992   // For each element in the initializer, see if we've found a load or an undef.
4993   // If we don't find an initial load element, or later load elements are
4994   // non-consecutive, bail out.
4995   for (unsigned i = 0; i < NumElems; ++i) {
4996     SDValue Elt = Elts[i];
4997     // Look through a bitcast.
4998     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4999       Elt = Elt.getOperand(0);
5000     if (!Elt.getNode() ||
5001         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5002       return SDValue();
5003     if (!LDBase) {
5004       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5005         return SDValue();
5006       LDBase = cast<LoadSDNode>(Elt.getNode());
5007       LastLoadedElt = i;
5008       continue;
5009     }
5010     if (Elt.getOpcode() == ISD::UNDEF)
5011       continue;
5012
5013     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5014     EVT LdVT = Elt.getValueType();
5015     // Each loaded element must be the correct fractional portion of the
5016     // requested vector load.
5017     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5018       return SDValue();
5019     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5020       return SDValue();
5021     LastLoadedElt = i;
5022   }
5023
5024   // If we have found an entire vector of loads and undefs, then return a large
5025   // load of the entire vector width starting at the base pointer.  If we found
5026   // consecutive loads for the low half, generate a vzext_load node.
5027   if (LastLoadedElt == NumElems - 1) {
5028     assert(LDBase && "Did not find base load for merging consecutive loads");
5029     EVT EltVT = LDBase->getValueType(0);
5030     // Ensure that the input vector size for the merged loads matches the
5031     // cumulative size of the input elements.
5032     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5033       return SDValue();
5034
5035     if (isAfterLegalize &&
5036         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5037       return SDValue();
5038
5039     SDValue NewLd = SDValue();
5040
5041     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5042                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5043                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5044                         LDBase->getAlignment());
5045
5046     if (LDBase->hasAnyUseOfValue(1)) {
5047       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5048                                      SDValue(LDBase, 1),
5049                                      SDValue(NewLd.getNode(), 1));
5050       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5051       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5052                              SDValue(NewLd.getNode(), 1));
5053     }
5054
5055     return NewLd;
5056   }
5057
5058   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5059   //of a v4i32 / v4f32. It's probably worth generalizing.
5060   EVT EltVT = VT.getVectorElementType();
5061   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5062       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5063     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5064     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5065     SDValue ResNode =
5066         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5067                                 LDBase->getPointerInfo(),
5068                                 LDBase->getAlignment(),
5069                                 false/*isVolatile*/, true/*ReadMem*/,
5070                                 false/*WriteMem*/);
5071
5072     // Make sure the newly-created LOAD is in the same position as LDBase in
5073     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5074     // update uses of LDBase's output chain to use the TokenFactor.
5075     if (LDBase->hasAnyUseOfValue(1)) {
5076       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5077                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5078       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5079       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5080                              SDValue(ResNode.getNode(), 1));
5081     }
5082
5083     return DAG.getBitcast(VT, ResNode);
5084   }
5085   return SDValue();
5086 }
5087
5088 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5089 /// to generate a splat value for the following cases:
5090 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5091 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5092 /// a scalar load, or a constant.
5093 /// The VBROADCAST node is returned when a pattern is found,
5094 /// or SDValue() otherwise.
5095 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5096                                     SelectionDAG &DAG) {
5097   // VBROADCAST requires AVX.
5098   // TODO: Splats could be generated for non-AVX CPUs using SSE
5099   // instructions, but there's less potential gain for only 128-bit vectors.
5100   if (!Subtarget->hasAVX())
5101     return SDValue();
5102
5103   MVT VT = Op.getSimpleValueType();
5104   SDLoc dl(Op);
5105
5106   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5107          "Unsupported vector type for broadcast.");
5108
5109   SDValue Ld;
5110   bool ConstSplatVal;
5111
5112   switch (Op.getOpcode()) {
5113     default:
5114       // Unknown pattern found.
5115       return SDValue();
5116
5117     case ISD::BUILD_VECTOR: {
5118       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5119       BitVector UndefElements;
5120       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5121
5122       // We need a splat of a single value to use broadcast, and it doesn't
5123       // make any sense if the value is only in one element of the vector.
5124       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5125         return SDValue();
5126
5127       Ld = Splat;
5128       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5129                        Ld.getOpcode() == ISD::ConstantFP);
5130
5131       // Make sure that all of the users of a non-constant load are from the
5132       // BUILD_VECTOR node.
5133       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5134         return SDValue();
5135       break;
5136     }
5137
5138     case ISD::VECTOR_SHUFFLE: {
5139       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5140
5141       // Shuffles must have a splat mask where the first element is
5142       // broadcasted.
5143       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5144         return SDValue();
5145
5146       SDValue Sc = Op.getOperand(0);
5147       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5148           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5149
5150         if (!Subtarget->hasInt256())
5151           return SDValue();
5152
5153         // Use the register form of the broadcast instruction available on AVX2.
5154         if (VT.getSizeInBits() >= 256)
5155           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5156         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5157       }
5158
5159       Ld = Sc.getOperand(0);
5160       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5161                        Ld.getOpcode() == ISD::ConstantFP);
5162
5163       // The scalar_to_vector node and the suspected
5164       // load node must have exactly one user.
5165       // Constants may have multiple users.
5166
5167       // AVX-512 has register version of the broadcast
5168       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5169         Ld.getValueType().getSizeInBits() >= 32;
5170       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5171           !hasRegVer))
5172         return SDValue();
5173       break;
5174     }
5175   }
5176
5177   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5178   bool IsGE256 = (VT.getSizeInBits() >= 256);
5179
5180   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5181   // instruction to save 8 or more bytes of constant pool data.
5182   // TODO: If multiple splats are generated to load the same constant,
5183   // it may be detrimental to overall size. There needs to be a way to detect
5184   // that condition to know if this is truly a size win.
5185   const Function *F = DAG.getMachineFunction().getFunction();
5186   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5187
5188   // Handle broadcasting a single constant scalar from the constant pool
5189   // into a vector.
5190   // On Sandybridge (no AVX2), it is still better to load a constant vector
5191   // from the constant pool and not to broadcast it from a scalar.
5192   // But override that restriction when optimizing for size.
5193   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5194   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5195     EVT CVT = Ld.getValueType();
5196     assert(!CVT.isVector() && "Must not broadcast a vector type");
5197
5198     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5199     // For size optimization, also splat v2f64 and v2i64, and for size opt
5200     // with AVX2, also splat i8 and i16.
5201     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5202     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5203         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5204       const Constant *C = nullptr;
5205       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5206         C = CI->getConstantIntValue();
5207       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5208         C = CF->getConstantFPValue();
5209
5210       assert(C && "Invalid constant type");
5211
5212       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5213       SDValue CP =
5214           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5215       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5216       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5217                        MachinePointerInfo::getConstantPool(),
5218                        false, false, false, Alignment);
5219
5220       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5221     }
5222   }
5223
5224   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5225
5226   // Handle AVX2 in-register broadcasts.
5227   if (!IsLoad && Subtarget->hasInt256() &&
5228       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5229     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5230
5231   // The scalar source must be a normal load.
5232   if (!IsLoad)
5233     return SDValue();
5234
5235   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5236       (Subtarget->hasVLX() && ScalarSize == 64))
5237     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5238
5239   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5240   // double since there is no vbroadcastsd xmm
5241   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5242     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5243       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5244   }
5245
5246   // Unsupported broadcast.
5247   return SDValue();
5248 }
5249
5250 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5251 /// underlying vector and index.
5252 ///
5253 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5254 /// index.
5255 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5256                                          SDValue ExtIdx) {
5257   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5258   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5259     return Idx;
5260
5261   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5262   // lowered this:
5263   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5264   // to:
5265   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5266   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5267   //                           undef)
5268   //                       Constant<0>)
5269   // In this case the vector is the extract_subvector expression and the index
5270   // is 2, as specified by the shuffle.
5271   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5272   SDValue ShuffleVec = SVOp->getOperand(0);
5273   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5274   assert(ShuffleVecVT.getVectorElementType() ==
5275          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5276
5277   int ShuffleIdx = SVOp->getMaskElt(Idx);
5278   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5279     ExtractedFromVec = ShuffleVec;
5280     return ShuffleIdx;
5281   }
5282   return Idx;
5283 }
5284
5285 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5286   MVT VT = Op.getSimpleValueType();
5287
5288   // Skip if insert_vec_elt is not supported.
5289   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5290   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5291     return SDValue();
5292
5293   SDLoc DL(Op);
5294   unsigned NumElems = Op.getNumOperands();
5295
5296   SDValue VecIn1;
5297   SDValue VecIn2;
5298   SmallVector<unsigned, 4> InsertIndices;
5299   SmallVector<int, 8> Mask(NumElems, -1);
5300
5301   for (unsigned i = 0; i != NumElems; ++i) {
5302     unsigned Opc = Op.getOperand(i).getOpcode();
5303
5304     if (Opc == ISD::UNDEF)
5305       continue;
5306
5307     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5308       // Quit if more than 1 elements need inserting.
5309       if (InsertIndices.size() > 1)
5310         return SDValue();
5311
5312       InsertIndices.push_back(i);
5313       continue;
5314     }
5315
5316     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5317     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5318     // Quit if non-constant index.
5319     if (!isa<ConstantSDNode>(ExtIdx))
5320       return SDValue();
5321     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5322
5323     // Quit if extracted from vector of different type.
5324     if (ExtractedFromVec.getValueType() != VT)
5325       return SDValue();
5326
5327     if (!VecIn1.getNode())
5328       VecIn1 = ExtractedFromVec;
5329     else if (VecIn1 != ExtractedFromVec) {
5330       if (!VecIn2.getNode())
5331         VecIn2 = ExtractedFromVec;
5332       else if (VecIn2 != ExtractedFromVec)
5333         // Quit if more than 2 vectors to shuffle
5334         return SDValue();
5335     }
5336
5337     if (ExtractedFromVec == VecIn1)
5338       Mask[i] = Idx;
5339     else if (ExtractedFromVec == VecIn2)
5340       Mask[i] = Idx + NumElems;
5341   }
5342
5343   if (!VecIn1.getNode())
5344     return SDValue();
5345
5346   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5347   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5348   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5349     unsigned Idx = InsertIndices[i];
5350     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5351                      DAG.getIntPtrConstant(Idx, DL));
5352   }
5353
5354   return NV;
5355 }
5356
5357 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5358   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5359          Op.getScalarValueSizeInBits() == 1 &&
5360          "Can not convert non-constant vector");
5361   uint64_t Immediate = 0;
5362   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5363     SDValue In = Op.getOperand(idx);
5364     if (In.getOpcode() != ISD::UNDEF)
5365       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5366   }
5367   SDLoc dl(Op);
5368   MVT VT =
5369    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5370   return DAG.getConstant(Immediate, dl, VT);
5371 }
5372 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5373 SDValue
5374 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5375
5376   MVT VT = Op.getSimpleValueType();
5377   assert((VT.getVectorElementType() == MVT::i1) &&
5378          "Unexpected type in LowerBUILD_VECTORvXi1!");
5379
5380   SDLoc dl(Op);
5381   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5382     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5383     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5384     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5385   }
5386
5387   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5388     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5389     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5390     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5391   }
5392
5393   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5394     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5395     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5396       return DAG.getBitcast(VT, Imm);
5397     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5398     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5399                         DAG.getIntPtrConstant(0, dl));
5400   }
5401
5402   // Vector has one or more non-const elements
5403   uint64_t Immediate = 0;
5404   SmallVector<unsigned, 16> NonConstIdx;
5405   bool IsSplat = true;
5406   bool HasConstElts = false;
5407   int SplatIdx = -1;
5408   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5409     SDValue In = Op.getOperand(idx);
5410     if (In.getOpcode() == ISD::UNDEF)
5411       continue;
5412     if (!isa<ConstantSDNode>(In))
5413       NonConstIdx.push_back(idx);
5414     else {
5415       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5416       HasConstElts = true;
5417     }
5418     if (SplatIdx == -1)
5419       SplatIdx = idx;
5420     else if (In != Op.getOperand(SplatIdx))
5421       IsSplat = false;
5422   }
5423
5424   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5425   if (IsSplat)
5426     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5427                        DAG.getConstant(1, dl, VT),
5428                        DAG.getConstant(0, dl, VT));
5429
5430   // insert elements one by one
5431   SDValue DstVec;
5432   SDValue Imm;
5433   if (Immediate) {
5434     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5435     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5436   }
5437   else if (HasConstElts)
5438     Imm = DAG.getConstant(0, dl, VT);
5439   else
5440     Imm = DAG.getUNDEF(VT);
5441   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5442     DstVec = DAG.getBitcast(VT, Imm);
5443   else {
5444     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5445     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5446                          DAG.getIntPtrConstant(0, dl));
5447   }
5448
5449   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5450     unsigned InsertIdx = NonConstIdx[i];
5451     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5452                          Op.getOperand(InsertIdx),
5453                          DAG.getIntPtrConstant(InsertIdx, dl));
5454   }
5455   return DstVec;
5456 }
5457
5458 /// \brief Return true if \p N implements a horizontal binop and return the
5459 /// operands for the horizontal binop into V0 and V1.
5460 ///
5461 /// This is a helper function of LowerToHorizontalOp().
5462 /// This function checks that the build_vector \p N in input implements a
5463 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5464 /// operation to match.
5465 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5466 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5467 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5468 /// arithmetic sub.
5469 ///
5470 /// This function only analyzes elements of \p N whose indices are
5471 /// in range [BaseIdx, LastIdx).
5472 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5473                               SelectionDAG &DAG,
5474                               unsigned BaseIdx, unsigned LastIdx,
5475                               SDValue &V0, SDValue &V1) {
5476   EVT VT = N->getValueType(0);
5477
5478   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5479   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5480          "Invalid Vector in input!");
5481
5482   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5483   bool CanFold = true;
5484   unsigned ExpectedVExtractIdx = BaseIdx;
5485   unsigned NumElts = LastIdx - BaseIdx;
5486   V0 = DAG.getUNDEF(VT);
5487   V1 = DAG.getUNDEF(VT);
5488
5489   // Check if N implements a horizontal binop.
5490   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5491     SDValue Op = N->getOperand(i + BaseIdx);
5492
5493     // Skip UNDEFs.
5494     if (Op->getOpcode() == ISD::UNDEF) {
5495       // Update the expected vector extract index.
5496       if (i * 2 == NumElts)
5497         ExpectedVExtractIdx = BaseIdx;
5498       ExpectedVExtractIdx += 2;
5499       continue;
5500     }
5501
5502     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5503
5504     if (!CanFold)
5505       break;
5506
5507     SDValue Op0 = Op.getOperand(0);
5508     SDValue Op1 = Op.getOperand(1);
5509
5510     // Try to match the following pattern:
5511     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5512     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5513         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5514         Op0.getOperand(0) == Op1.getOperand(0) &&
5515         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5516         isa<ConstantSDNode>(Op1.getOperand(1)));
5517     if (!CanFold)
5518       break;
5519
5520     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5521     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5522
5523     if (i * 2 < NumElts) {
5524       if (V0.getOpcode() == ISD::UNDEF) {
5525         V0 = Op0.getOperand(0);
5526         if (V0.getValueType() != VT)
5527           return false;
5528       }
5529     } else {
5530       if (V1.getOpcode() == ISD::UNDEF) {
5531         V1 = Op0.getOperand(0);
5532         if (V1.getValueType() != VT)
5533           return false;
5534       }
5535       if (i * 2 == NumElts)
5536         ExpectedVExtractIdx = BaseIdx;
5537     }
5538
5539     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5540     if (I0 == ExpectedVExtractIdx)
5541       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5542     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5543       // Try to match the following dag sequence:
5544       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5545       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5546     } else
5547       CanFold = false;
5548
5549     ExpectedVExtractIdx += 2;
5550   }
5551
5552   return CanFold;
5553 }
5554
5555 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5556 /// a concat_vector.
5557 ///
5558 /// This is a helper function of LowerToHorizontalOp().
5559 /// This function expects two 256-bit vectors called V0 and V1.
5560 /// At first, each vector is split into two separate 128-bit vectors.
5561 /// Then, the resulting 128-bit vectors are used to implement two
5562 /// horizontal binary operations.
5563 ///
5564 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5565 ///
5566 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5567 /// the two new horizontal binop.
5568 /// When Mode is set, the first horizontal binop dag node would take as input
5569 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5570 /// horizontal binop dag node would take as input the lower 128-bit of V1
5571 /// and the upper 128-bit of V1.
5572 ///   Example:
5573 ///     HADD V0_LO, V0_HI
5574 ///     HADD V1_LO, V1_HI
5575 ///
5576 /// Otherwise, the first horizontal binop dag node takes as input the lower
5577 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5578 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5579 ///   Example:
5580 ///     HADD V0_LO, V1_LO
5581 ///     HADD V0_HI, V1_HI
5582 ///
5583 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5584 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5585 /// the upper 128-bits of the result.
5586 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5587                                      SDLoc DL, SelectionDAG &DAG,
5588                                      unsigned X86Opcode, bool Mode,
5589                                      bool isUndefLO, bool isUndefHI) {
5590   EVT VT = V0.getValueType();
5591   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5592          "Invalid nodes in input!");
5593
5594   unsigned NumElts = VT.getVectorNumElements();
5595   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5596   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5597   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5598   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5599   EVT NewVT = V0_LO.getValueType();
5600
5601   SDValue LO = DAG.getUNDEF(NewVT);
5602   SDValue HI = DAG.getUNDEF(NewVT);
5603
5604   if (Mode) {
5605     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5606     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5607       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5608     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5609       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5610   } else {
5611     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5612     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5613                        V1_LO->getOpcode() != ISD::UNDEF))
5614       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5615
5616     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5617                        V1_HI->getOpcode() != ISD::UNDEF))
5618       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5619   }
5620
5621   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5622 }
5623
5624 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5625 /// node.
5626 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5627                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5628   EVT VT = BV->getValueType(0);
5629   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5630       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5631     return SDValue();
5632
5633   SDLoc DL(BV);
5634   unsigned NumElts = VT.getVectorNumElements();
5635   SDValue InVec0 = DAG.getUNDEF(VT);
5636   SDValue InVec1 = DAG.getUNDEF(VT);
5637
5638   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5639           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5640
5641   // Odd-numbered elements in the input build vector are obtained from
5642   // adding two integer/float elements.
5643   // Even-numbered elements in the input build vector are obtained from
5644   // subtracting two integer/float elements.
5645   unsigned ExpectedOpcode = ISD::FSUB;
5646   unsigned NextExpectedOpcode = ISD::FADD;
5647   bool AddFound = false;
5648   bool SubFound = false;
5649
5650   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5651     SDValue Op = BV->getOperand(i);
5652
5653     // Skip 'undef' values.
5654     unsigned Opcode = Op.getOpcode();
5655     if (Opcode == ISD::UNDEF) {
5656       std::swap(ExpectedOpcode, NextExpectedOpcode);
5657       continue;
5658     }
5659
5660     // Early exit if we found an unexpected opcode.
5661     if (Opcode != ExpectedOpcode)
5662       return SDValue();
5663
5664     SDValue Op0 = Op.getOperand(0);
5665     SDValue Op1 = Op.getOperand(1);
5666
5667     // Try to match the following pattern:
5668     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5669     // Early exit if we cannot match that sequence.
5670     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5671         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5672         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5673         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5674         Op0.getOperand(1) != Op1.getOperand(1))
5675       return SDValue();
5676
5677     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5678     if (I0 != i)
5679       return SDValue();
5680
5681     // We found a valid add/sub node. Update the information accordingly.
5682     if (i & 1)
5683       AddFound = true;
5684     else
5685       SubFound = true;
5686
5687     // Update InVec0 and InVec1.
5688     if (InVec0.getOpcode() == ISD::UNDEF) {
5689       InVec0 = Op0.getOperand(0);
5690       if (InVec0.getValueType() != VT)
5691         return SDValue();
5692     }
5693     if (InVec1.getOpcode() == ISD::UNDEF) {
5694       InVec1 = Op1.getOperand(0);
5695       if (InVec1.getValueType() != VT)
5696         return SDValue();
5697     }
5698
5699     // Make sure that operands in input to each add/sub node always
5700     // come from a same pair of vectors.
5701     if (InVec0 != Op0.getOperand(0)) {
5702       if (ExpectedOpcode == ISD::FSUB)
5703         return SDValue();
5704
5705       // FADD is commutable. Try to commute the operands
5706       // and then test again.
5707       std::swap(Op0, Op1);
5708       if (InVec0 != Op0.getOperand(0))
5709         return SDValue();
5710     }
5711
5712     if (InVec1 != Op1.getOperand(0))
5713       return SDValue();
5714
5715     // Update the pair of expected opcodes.
5716     std::swap(ExpectedOpcode, NextExpectedOpcode);
5717   }
5718
5719   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5720   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5721       InVec1.getOpcode() != ISD::UNDEF)
5722     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5723
5724   return SDValue();
5725 }
5726
5727 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5728 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5729                                    const X86Subtarget *Subtarget,
5730                                    SelectionDAG &DAG) {
5731   EVT VT = BV->getValueType(0);
5732   unsigned NumElts = VT.getVectorNumElements();
5733   unsigned NumUndefsLO = 0;
5734   unsigned NumUndefsHI = 0;
5735   unsigned Half = NumElts/2;
5736
5737   // Count the number of UNDEF operands in the build_vector in input.
5738   for (unsigned i = 0, e = Half; i != e; ++i)
5739     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5740       NumUndefsLO++;
5741
5742   for (unsigned i = Half, e = NumElts; i != e; ++i)
5743     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5744       NumUndefsHI++;
5745
5746   // Early exit if this is either a build_vector of all UNDEFs or all the
5747   // operands but one are UNDEF.
5748   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5749     return SDValue();
5750
5751   SDLoc DL(BV);
5752   SDValue InVec0, InVec1;
5753   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5754     // Try to match an SSE3 float HADD/HSUB.
5755     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5756       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5757
5758     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5759       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5760   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5761     // Try to match an SSSE3 integer HADD/HSUB.
5762     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5763       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5764
5765     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5766       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5767   }
5768
5769   if (!Subtarget->hasAVX())
5770     return SDValue();
5771
5772   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5773     // Try to match an AVX horizontal add/sub of packed single/double
5774     // precision floating point values from 256-bit vectors.
5775     SDValue InVec2, InVec3;
5776     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5777         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5778         ((InVec0.getOpcode() == ISD::UNDEF ||
5779           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5780         ((InVec1.getOpcode() == ISD::UNDEF ||
5781           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5782       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5783
5784     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5785         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5786         ((InVec0.getOpcode() == ISD::UNDEF ||
5787           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5788         ((InVec1.getOpcode() == ISD::UNDEF ||
5789           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5790       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5791   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5792     // Try to match an AVX2 horizontal add/sub of signed integers.
5793     SDValue InVec2, InVec3;
5794     unsigned X86Opcode;
5795     bool CanFold = true;
5796
5797     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5798         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5799         ((InVec0.getOpcode() == ISD::UNDEF ||
5800           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5801         ((InVec1.getOpcode() == ISD::UNDEF ||
5802           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5803       X86Opcode = X86ISD::HADD;
5804     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5805         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5806         ((InVec0.getOpcode() == ISD::UNDEF ||
5807           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5808         ((InVec1.getOpcode() == ISD::UNDEF ||
5809           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5810       X86Opcode = X86ISD::HSUB;
5811     else
5812       CanFold = false;
5813
5814     if (CanFold) {
5815       // Fold this build_vector into a single horizontal add/sub.
5816       // Do this only if the target has AVX2.
5817       if (Subtarget->hasAVX2())
5818         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5819
5820       // Do not try to expand this build_vector into a pair of horizontal
5821       // add/sub if we can emit a pair of scalar add/sub.
5822       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5823         return SDValue();
5824
5825       // Convert this build_vector into a pair of horizontal binop followed by
5826       // a concat vector.
5827       bool isUndefLO = NumUndefsLO == Half;
5828       bool isUndefHI = NumUndefsHI == Half;
5829       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5830                                    isUndefLO, isUndefHI);
5831     }
5832   }
5833
5834   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5835        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5836     unsigned X86Opcode;
5837     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5838       X86Opcode = X86ISD::HADD;
5839     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5840       X86Opcode = X86ISD::HSUB;
5841     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5842       X86Opcode = X86ISD::FHADD;
5843     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5844       X86Opcode = X86ISD::FHSUB;
5845     else
5846       return SDValue();
5847
5848     // Don't try to expand this build_vector into a pair of horizontal add/sub
5849     // if we can simply emit a pair of scalar add/sub.
5850     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5851       return SDValue();
5852
5853     // Convert this build_vector into two horizontal add/sub followed by
5854     // a concat vector.
5855     bool isUndefLO = NumUndefsLO == Half;
5856     bool isUndefHI = NumUndefsHI == Half;
5857     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5858                                  isUndefLO, isUndefHI);
5859   }
5860
5861   return SDValue();
5862 }
5863
5864 SDValue
5865 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5866   SDLoc dl(Op);
5867
5868   MVT VT = Op.getSimpleValueType();
5869   MVT ExtVT = VT.getVectorElementType();
5870   unsigned NumElems = Op.getNumOperands();
5871
5872   // Generate vectors for predicate vectors.
5873   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5874     return LowerBUILD_VECTORvXi1(Op, DAG);
5875
5876   // Vectors containing all zeros can be matched by pxor and xorps later
5877   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5878     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5879     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5880     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5881       return Op;
5882
5883     return getZeroVector(VT, Subtarget, DAG, dl);
5884   }
5885
5886   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5887   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5888   // vpcmpeqd on 256-bit vectors.
5889   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5890     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5891       return Op;
5892
5893     if (!VT.is512BitVector())
5894       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5895   }
5896
5897   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5898   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5899     return AddSub;
5900   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5901     return HorizontalOp;
5902   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5903     return Broadcast;
5904
5905   unsigned EVTBits = ExtVT.getSizeInBits();
5906
5907   unsigned NumZero  = 0;
5908   unsigned NumNonZero = 0;
5909   unsigned NonZeros = 0;
5910   bool IsAllConstants = true;
5911   SmallSet<SDValue, 8> Values;
5912   for (unsigned i = 0; i < NumElems; ++i) {
5913     SDValue Elt = Op.getOperand(i);
5914     if (Elt.getOpcode() == ISD::UNDEF)
5915       continue;
5916     Values.insert(Elt);
5917     if (Elt.getOpcode() != ISD::Constant &&
5918         Elt.getOpcode() != ISD::ConstantFP)
5919       IsAllConstants = false;
5920     if (X86::isZeroNode(Elt))
5921       NumZero++;
5922     else {
5923       NonZeros |= (1 << i);
5924       NumNonZero++;
5925     }
5926   }
5927
5928   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5929   if (NumNonZero == 0)
5930     return DAG.getUNDEF(VT);
5931
5932   // Special case for single non-zero, non-undef, element.
5933   if (NumNonZero == 1) {
5934     unsigned Idx = countTrailingZeros(NonZeros);
5935     SDValue Item = Op.getOperand(Idx);
5936
5937     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5938     // the value are obviously zero, truncate the value to i32 and do the
5939     // insertion that way.  Only do this if the value is non-constant or if the
5940     // value is a constant being inserted into element 0.  It is cheaper to do
5941     // a constant pool load than it is to do a movd + shuffle.
5942     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5943         (!IsAllConstants || Idx == 0)) {
5944       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5945         // Handle SSE only.
5946         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5947         EVT VecVT = MVT::v4i32;
5948
5949         // Truncate the value (which may itself be a constant) to i32, and
5950         // convert it to a vector with movd (S2V+shuffle to zero extend).
5951         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5952         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5953         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5954                                       Item, Idx * 2, true, Subtarget, DAG));
5955       }
5956     }
5957
5958     // If we have a constant or non-constant insertion into the low element of
5959     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5960     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5961     // depending on what the source datatype is.
5962     if (Idx == 0) {
5963       if (NumZero == 0)
5964         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5965
5966       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5967           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5968         if (VT.is512BitVector()) {
5969           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5970           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5971                              Item, DAG.getIntPtrConstant(0, dl));
5972         }
5973         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5974                "Expected an SSE value type!");
5975         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5976         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5977         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5978       }
5979
5980       // We can't directly insert an i8 or i16 into a vector, so zero extend
5981       // it to i32 first.
5982       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5983         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5984         if (VT.is256BitVector()) {
5985           if (Subtarget->hasAVX()) {
5986             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5987             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5988           } else {
5989             // Without AVX, we need to extend to a 128-bit vector and then
5990             // insert into the 256-bit vector.
5991             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5992             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5993             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5994           }
5995         } else {
5996           assert(VT.is128BitVector() && "Expected an SSE value type!");
5997           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5998           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5999         }
6000         return DAG.getBitcast(VT, Item);
6001       }
6002     }
6003
6004     // Is it a vector logical left shift?
6005     if (NumElems == 2 && Idx == 1 &&
6006         X86::isZeroNode(Op.getOperand(0)) &&
6007         !X86::isZeroNode(Op.getOperand(1))) {
6008       unsigned NumBits = VT.getSizeInBits();
6009       return getVShift(true, VT,
6010                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6011                                    VT, Op.getOperand(1)),
6012                        NumBits/2, DAG, *this, dl);
6013     }
6014
6015     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6016       return SDValue();
6017
6018     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6019     // is a non-constant being inserted into an element other than the low one,
6020     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6021     // movd/movss) to move this into the low element, then shuffle it into
6022     // place.
6023     if (EVTBits == 32) {
6024       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6025       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6026     }
6027   }
6028
6029   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6030   if (Values.size() == 1) {
6031     if (EVTBits == 32) {
6032       // Instead of a shuffle like this:
6033       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6034       // Check if it's possible to issue this instead.
6035       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6036       unsigned Idx = countTrailingZeros(NonZeros);
6037       SDValue Item = Op.getOperand(Idx);
6038       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6039         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6040     }
6041     return SDValue();
6042   }
6043
6044   // A vector full of immediates; various special cases are already
6045   // handled, so this is best done with a single constant-pool load.
6046   if (IsAllConstants)
6047     return SDValue();
6048
6049   // For AVX-length vectors, see if we can use a vector load to get all of the
6050   // elements, otherwise build the individual 128-bit pieces and use
6051   // shuffles to put them in place.
6052   if (VT.is256BitVector() || VT.is512BitVector()) {
6053     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6054
6055     // Check for a build vector of consecutive loads.
6056     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6057       return LD;
6058
6059     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6060
6061     // Build both the lower and upper subvector.
6062     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6063                                 makeArrayRef(&V[0], NumElems/2));
6064     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6065                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6066
6067     // Recreate the wider vector with the lower and upper part.
6068     if (VT.is256BitVector())
6069       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6070     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6071   }
6072
6073   // Let legalizer expand 2-wide build_vectors.
6074   if (EVTBits == 64) {
6075     if (NumNonZero == 1) {
6076       // One half is zero or undef.
6077       unsigned Idx = countTrailingZeros(NonZeros);
6078       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6079                                  Op.getOperand(Idx));
6080       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6081     }
6082     return SDValue();
6083   }
6084
6085   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6086   if (EVTBits == 8 && NumElems == 16)
6087     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6088                                         Subtarget, *this))
6089       return V;
6090
6091   if (EVTBits == 16 && NumElems == 8)
6092     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6093                                       Subtarget, *this))
6094       return V;
6095
6096   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6097   if (EVTBits == 32 && NumElems == 4)
6098     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6099       return V;
6100
6101   // If element VT is == 32 bits, turn it into a number of shuffles.
6102   SmallVector<SDValue, 8> V(NumElems);
6103   if (NumElems == 4 && NumZero > 0) {
6104     for (unsigned i = 0; i < 4; ++i) {
6105       bool isZero = !(NonZeros & (1 << i));
6106       if (isZero)
6107         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6108       else
6109         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6110     }
6111
6112     for (unsigned i = 0; i < 2; ++i) {
6113       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6114         default: break;
6115         case 0:
6116           V[i] = V[i*2];  // Must be a zero vector.
6117           break;
6118         case 1:
6119           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6120           break;
6121         case 2:
6122           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6123           break;
6124         case 3:
6125           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6126           break;
6127       }
6128     }
6129
6130     bool Reverse1 = (NonZeros & 0x3) == 2;
6131     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6132     int MaskVec[] = {
6133       Reverse1 ? 1 : 0,
6134       Reverse1 ? 0 : 1,
6135       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6136       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6137     };
6138     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6139   }
6140
6141   if (Values.size() > 1 && VT.is128BitVector()) {
6142     // Check for a build vector of consecutive loads.
6143     for (unsigned i = 0; i < NumElems; ++i)
6144       V[i] = Op.getOperand(i);
6145
6146     // Check for elements which are consecutive loads.
6147     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6148       return LD;
6149
6150     // Check for a build vector from mostly shuffle plus few inserting.
6151     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6152       return Sh;
6153
6154     // For SSE 4.1, use insertps to put the high elements into the low element.
6155     if (Subtarget->hasSSE41()) {
6156       SDValue Result;
6157       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6158         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6159       else
6160         Result = DAG.getUNDEF(VT);
6161
6162       for (unsigned i = 1; i < NumElems; ++i) {
6163         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6164         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6165                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6166       }
6167       return Result;
6168     }
6169
6170     // Otherwise, expand into a number of unpckl*, start by extending each of
6171     // our (non-undef) elements to the full vector width with the element in the
6172     // bottom slot of the vector (which generates no code for SSE).
6173     for (unsigned i = 0; i < NumElems; ++i) {
6174       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6175         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6176       else
6177         V[i] = DAG.getUNDEF(VT);
6178     }
6179
6180     // Next, we iteratively mix elements, e.g. for v4f32:
6181     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6182     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6183     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6184     unsigned EltStride = NumElems >> 1;
6185     while (EltStride != 0) {
6186       for (unsigned i = 0; i < EltStride; ++i) {
6187         // If V[i+EltStride] is undef and this is the first round of mixing,
6188         // then it is safe to just drop this shuffle: V[i] is already in the
6189         // right place, the one element (since it's the first round) being
6190         // inserted as undef can be dropped.  This isn't safe for successive
6191         // rounds because they will permute elements within both vectors.
6192         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6193             EltStride == NumElems/2)
6194           continue;
6195
6196         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6197       }
6198       EltStride >>= 1;
6199     }
6200     return V[0];
6201   }
6202   return SDValue();
6203 }
6204
6205 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6206 // to create 256-bit vectors from two other 128-bit ones.
6207 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6208   SDLoc dl(Op);
6209   MVT ResVT = Op.getSimpleValueType();
6210
6211   assert((ResVT.is256BitVector() ||
6212           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6213
6214   SDValue V1 = Op.getOperand(0);
6215   SDValue V2 = Op.getOperand(1);
6216   unsigned NumElems = ResVT.getVectorNumElements();
6217   if (ResVT.is256BitVector())
6218     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6219
6220   if (Op.getNumOperands() == 4) {
6221     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6222                                 ResVT.getVectorNumElements()/2);
6223     SDValue V3 = Op.getOperand(2);
6224     SDValue V4 = Op.getOperand(3);
6225     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6226       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6227   }
6228   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6229 }
6230
6231 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6232                                        const X86Subtarget *Subtarget,
6233                                        SelectionDAG & DAG) {
6234   SDLoc dl(Op);
6235   MVT ResVT = Op.getSimpleValueType();
6236   unsigned NumOfOperands = Op.getNumOperands();
6237
6238   assert(isPowerOf2_32(NumOfOperands) &&
6239          "Unexpected number of operands in CONCAT_VECTORS");
6240
6241   if (NumOfOperands > 2) {
6242     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6243                                   ResVT.getVectorNumElements()/2);
6244     SmallVector<SDValue, 2> Ops;
6245     for (unsigned i = 0; i < NumOfOperands/2; i++)
6246       Ops.push_back(Op.getOperand(i));
6247     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6248     Ops.clear();
6249     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6250       Ops.push_back(Op.getOperand(i));
6251     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6252     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6253   }
6254
6255   SDValue V1 = Op.getOperand(0);
6256   SDValue V2 = Op.getOperand(1);
6257   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6258   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6259
6260   if (IsZeroV1 && IsZeroV2)
6261     return getZeroVector(ResVT, Subtarget, DAG, dl);
6262
6263   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6264   SDValue Undef = DAG.getUNDEF(ResVT);
6265   unsigned NumElems = ResVT.getVectorNumElements();
6266   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6267
6268   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6269   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6270   if (IsZeroV1)
6271     return V2;
6272
6273   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6274   // Zero the upper bits of V1
6275   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6276   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6277   if (IsZeroV2)
6278     return V1;
6279   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6280 }
6281
6282 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6283                                    const X86Subtarget *Subtarget,
6284                                    SelectionDAG &DAG) {
6285   MVT VT = Op.getSimpleValueType();
6286   if (VT.getVectorElementType() == MVT::i1)
6287     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6288
6289   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6290          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6291           Op.getNumOperands() == 4)));
6292
6293   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6294   // from two other 128-bit ones.
6295
6296   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6297   return LowerAVXCONCAT_VECTORS(Op, DAG);
6298 }
6299
6300
6301 //===----------------------------------------------------------------------===//
6302 // Vector shuffle lowering
6303 //
6304 // This is an experimental code path for lowering vector shuffles on x86. It is
6305 // designed to handle arbitrary vector shuffles and blends, gracefully
6306 // degrading performance as necessary. It works hard to recognize idiomatic
6307 // shuffles and lower them to optimal instruction patterns without leaving
6308 // a framework that allows reasonably efficient handling of all vector shuffle
6309 // patterns.
6310 //===----------------------------------------------------------------------===//
6311
6312 /// \brief Tiny helper function to identify a no-op mask.
6313 ///
6314 /// This is a somewhat boring predicate function. It checks whether the mask
6315 /// array input, which is assumed to be a single-input shuffle mask of the kind
6316 /// used by the X86 shuffle instructions (not a fully general
6317 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6318 /// in-place shuffle are 'no-op's.
6319 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6320   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6321     if (Mask[i] != -1 && Mask[i] != i)
6322       return false;
6323   return true;
6324 }
6325
6326 /// \brief Helper function to classify a mask as a single-input mask.
6327 ///
6328 /// This isn't a generic single-input test because in the vector shuffle
6329 /// lowering we canonicalize single inputs to be the first input operand. This
6330 /// means we can more quickly test for a single input by only checking whether
6331 /// an input from the second operand exists. We also assume that the size of
6332 /// mask corresponds to the size of the input vectors which isn't true in the
6333 /// fully general case.
6334 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6335   for (int M : Mask)
6336     if (M >= (int)Mask.size())
6337       return false;
6338   return true;
6339 }
6340
6341 /// \brief Test whether there are elements crossing 128-bit lanes in this
6342 /// shuffle mask.
6343 ///
6344 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6345 /// and we routinely test for these.
6346 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6347   int LaneSize = 128 / VT.getScalarSizeInBits();
6348   int Size = Mask.size();
6349   for (int i = 0; i < Size; ++i)
6350     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6351       return true;
6352   return false;
6353 }
6354
6355 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6356 ///
6357 /// This checks a shuffle mask to see if it is performing the same
6358 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6359 /// that it is also not lane-crossing. It may however involve a blend from the
6360 /// same lane of a second vector.
6361 ///
6362 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6363 /// non-trivial to compute in the face of undef lanes. The representation is
6364 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6365 /// entries from both V1 and V2 inputs to the wider mask.
6366 static bool
6367 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6368                                 SmallVectorImpl<int> &RepeatedMask) {
6369   int LaneSize = 128 / VT.getScalarSizeInBits();
6370   RepeatedMask.resize(LaneSize, -1);
6371   int Size = Mask.size();
6372   for (int i = 0; i < Size; ++i) {
6373     if (Mask[i] < 0)
6374       continue;
6375     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6376       // This entry crosses lanes, so there is no way to model this shuffle.
6377       return false;
6378
6379     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6380     if (RepeatedMask[i % LaneSize] == -1)
6381       // This is the first non-undef entry in this slot of a 128-bit lane.
6382       RepeatedMask[i % LaneSize] =
6383           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6384     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6385       // Found a mismatch with the repeated mask.
6386       return false;
6387   }
6388   return true;
6389 }
6390
6391 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6392 /// arguments.
6393 ///
6394 /// This is a fast way to test a shuffle mask against a fixed pattern:
6395 ///
6396 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6397 ///
6398 /// It returns true if the mask is exactly as wide as the argument list, and
6399 /// each element of the mask is either -1 (signifying undef) or the value given
6400 /// in the argument.
6401 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6402                                 ArrayRef<int> ExpectedMask) {
6403   if (Mask.size() != ExpectedMask.size())
6404     return false;
6405
6406   int Size = Mask.size();
6407
6408   // If the values are build vectors, we can look through them to find
6409   // equivalent inputs that make the shuffles equivalent.
6410   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6411   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6412
6413   for (int i = 0; i < Size; ++i)
6414     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6415       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6416       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6417       if (!MaskBV || !ExpectedBV ||
6418           MaskBV->getOperand(Mask[i] % Size) !=
6419               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6420         return false;
6421     }
6422
6423   return true;
6424 }
6425
6426 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6427 ///
6428 /// This helper function produces an 8-bit shuffle immediate corresponding to
6429 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6430 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6431 /// example.
6432 ///
6433 /// NB: We rely heavily on "undef" masks preserving the input lane.
6434 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6435                                           SelectionDAG &DAG) {
6436   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6437   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6438   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6439   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6440   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6441
6442   unsigned Imm = 0;
6443   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6444   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6445   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6446   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6447   return DAG.getConstant(Imm, DL, MVT::i8);
6448 }
6449
6450 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6451 ///
6452 /// This is used as a fallback approach when first class blend instructions are
6453 /// unavailable. Currently it is only suitable for integer vectors, but could
6454 /// be generalized for floating point vectors if desirable.
6455 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6456                                             SDValue V2, ArrayRef<int> Mask,
6457                                             SelectionDAG &DAG) {
6458   assert(VT.isInteger() && "Only supports integer vector types!");
6459   MVT EltVT = VT.getScalarType();
6460   int NumEltBits = EltVT.getSizeInBits();
6461   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6462   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6463                                     EltVT);
6464   SmallVector<SDValue, 16> MaskOps;
6465   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6466     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6467       return SDValue(); // Shuffled input!
6468     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6469   }
6470
6471   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6472   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6473   // We have to cast V2 around.
6474   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6475   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6476                                       DAG.getBitcast(MaskVT, V1Mask),
6477                                       DAG.getBitcast(MaskVT, V2)));
6478   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6479 }
6480
6481 /// \brief Try to emit a blend instruction for a shuffle.
6482 ///
6483 /// This doesn't do any checks for the availability of instructions for blending
6484 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6485 /// be matched in the backend with the type given. What it does check for is
6486 /// that the shuffle mask is in fact a blend.
6487 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6488                                          SDValue V2, ArrayRef<int> Mask,
6489                                          const X86Subtarget *Subtarget,
6490                                          SelectionDAG &DAG) {
6491   unsigned BlendMask = 0;
6492   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6493     if (Mask[i] >= Size) {
6494       if (Mask[i] != i + Size)
6495         return SDValue(); // Shuffled V2 input!
6496       BlendMask |= 1u << i;
6497       continue;
6498     }
6499     if (Mask[i] >= 0 && Mask[i] != i)
6500       return SDValue(); // Shuffled V1 input!
6501   }
6502   switch (VT.SimpleTy) {
6503   case MVT::v2f64:
6504   case MVT::v4f32:
6505   case MVT::v4f64:
6506   case MVT::v8f32:
6507     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6508                        DAG.getConstant(BlendMask, DL, MVT::i8));
6509
6510   case MVT::v4i64:
6511   case MVT::v8i32:
6512     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6513     // FALLTHROUGH
6514   case MVT::v2i64:
6515   case MVT::v4i32:
6516     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6517     // that instruction.
6518     if (Subtarget->hasAVX2()) {
6519       // Scale the blend by the number of 32-bit dwords per element.
6520       int Scale =  VT.getScalarSizeInBits() / 32;
6521       BlendMask = 0;
6522       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6523         if (Mask[i] >= Size)
6524           for (int j = 0; j < Scale; ++j)
6525             BlendMask |= 1u << (i * Scale + j);
6526
6527       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6528       V1 = DAG.getBitcast(BlendVT, V1);
6529       V2 = DAG.getBitcast(BlendVT, V2);
6530       return DAG.getBitcast(
6531           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6532                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6533     }
6534     // FALLTHROUGH
6535   case MVT::v8i16: {
6536     // For integer shuffles we need to expand the mask and cast the inputs to
6537     // v8i16s prior to blending.
6538     int Scale = 8 / VT.getVectorNumElements();
6539     BlendMask = 0;
6540     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6541       if (Mask[i] >= Size)
6542         for (int j = 0; j < Scale; ++j)
6543           BlendMask |= 1u << (i * Scale + j);
6544
6545     V1 = DAG.getBitcast(MVT::v8i16, V1);
6546     V2 = DAG.getBitcast(MVT::v8i16, V2);
6547     return DAG.getBitcast(VT,
6548                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6549                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6550   }
6551
6552   case MVT::v16i16: {
6553     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6554     SmallVector<int, 8> RepeatedMask;
6555     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6556       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6557       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6558       BlendMask = 0;
6559       for (int i = 0; i < 8; ++i)
6560         if (RepeatedMask[i] >= 16)
6561           BlendMask |= 1u << i;
6562       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6563                          DAG.getConstant(BlendMask, DL, MVT::i8));
6564     }
6565   }
6566     // FALLTHROUGH
6567   case MVT::v16i8:
6568   case MVT::v32i8: {
6569     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6570            "256-bit byte-blends require AVX2 support!");
6571
6572     // Scale the blend by the number of bytes per element.
6573     int Scale = VT.getScalarSizeInBits() / 8;
6574
6575     // This form of blend is always done on bytes. Compute the byte vector
6576     // type.
6577     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6578
6579     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6580     // mix of LLVM's code generator and the x86 backend. We tell the code
6581     // generator that boolean values in the elements of an x86 vector register
6582     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6583     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6584     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6585     // of the element (the remaining are ignored) and 0 in that high bit would
6586     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6587     // the LLVM model for boolean values in vector elements gets the relevant
6588     // bit set, it is set backwards and over constrained relative to x86's
6589     // actual model.
6590     SmallVector<SDValue, 32> VSELECTMask;
6591     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6592       for (int j = 0; j < Scale; ++j)
6593         VSELECTMask.push_back(
6594             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6595                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6596                                           MVT::i8));
6597
6598     V1 = DAG.getBitcast(BlendVT, V1);
6599     V2 = DAG.getBitcast(BlendVT, V2);
6600     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6601                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6602                                                       BlendVT, VSELECTMask),
6603                                           V1, V2));
6604   }
6605
6606   default:
6607     llvm_unreachable("Not a supported integer vector type!");
6608   }
6609 }
6610
6611 /// \brief Try to lower as a blend of elements from two inputs followed by
6612 /// a single-input permutation.
6613 ///
6614 /// This matches the pattern where we can blend elements from two inputs and
6615 /// then reduce the shuffle to a single-input permutation.
6616 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6617                                                    SDValue V2,
6618                                                    ArrayRef<int> Mask,
6619                                                    SelectionDAG &DAG) {
6620   // We build up the blend mask while checking whether a blend is a viable way
6621   // to reduce the shuffle.
6622   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6623   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6624
6625   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6626     if (Mask[i] < 0)
6627       continue;
6628
6629     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6630
6631     if (BlendMask[Mask[i] % Size] == -1)
6632       BlendMask[Mask[i] % Size] = Mask[i];
6633     else if (BlendMask[Mask[i] % Size] != Mask[i])
6634       return SDValue(); // Can't blend in the needed input!
6635
6636     PermuteMask[i] = Mask[i] % Size;
6637   }
6638
6639   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6640   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6641 }
6642
6643 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6644 /// blends and permutes.
6645 ///
6646 /// This matches the extremely common pattern for handling combined
6647 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6648 /// operations. It will try to pick the best arrangement of shuffles and
6649 /// blends.
6650 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6651                                                           SDValue V1,
6652                                                           SDValue V2,
6653                                                           ArrayRef<int> Mask,
6654                                                           SelectionDAG &DAG) {
6655   // Shuffle the input elements into the desired positions in V1 and V2 and
6656   // blend them together.
6657   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6658   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6659   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6660   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6661     if (Mask[i] >= 0 && Mask[i] < Size) {
6662       V1Mask[i] = Mask[i];
6663       BlendMask[i] = i;
6664     } else if (Mask[i] >= Size) {
6665       V2Mask[i] = Mask[i] - Size;
6666       BlendMask[i] = i + Size;
6667     }
6668
6669   // Try to lower with the simpler initial blend strategy unless one of the
6670   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6671   // shuffle may be able to fold with a load or other benefit. However, when
6672   // we'll have to do 2x as many shuffles in order to achieve this, blending
6673   // first is a better strategy.
6674   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6675     if (SDValue BlendPerm =
6676             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6677       return BlendPerm;
6678
6679   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6680   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6681   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6682 }
6683
6684 /// \brief Try to lower a vector shuffle as a byte rotation.
6685 ///
6686 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6687 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6688 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6689 /// try to generically lower a vector shuffle through such an pattern. It
6690 /// does not check for the profitability of lowering either as PALIGNR or
6691 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6692 /// This matches shuffle vectors that look like:
6693 ///
6694 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6695 ///
6696 /// Essentially it concatenates V1 and V2, shifts right by some number of
6697 /// elements, and takes the low elements as the result. Note that while this is
6698 /// specified as a *right shift* because x86 is little-endian, it is a *left
6699 /// rotate* of the vector lanes.
6700 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6701                                               SDValue V2,
6702                                               ArrayRef<int> Mask,
6703                                               const X86Subtarget *Subtarget,
6704                                               SelectionDAG &DAG) {
6705   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6706
6707   int NumElts = Mask.size();
6708   int NumLanes = VT.getSizeInBits() / 128;
6709   int NumLaneElts = NumElts / NumLanes;
6710
6711   // We need to detect various ways of spelling a rotation:
6712   //   [11, 12, 13, 14, 15,  0,  1,  2]
6713   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6714   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6715   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6716   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6717   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6718   int Rotation = 0;
6719   SDValue Lo, Hi;
6720   for (int l = 0; l < NumElts; l += NumLaneElts) {
6721     for (int i = 0; i < NumLaneElts; ++i) {
6722       if (Mask[l + i] == -1)
6723         continue;
6724       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6725
6726       // Get the mod-Size index and lane correct it.
6727       int LaneIdx = (Mask[l + i] % NumElts) - l;
6728       // Make sure it was in this lane.
6729       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6730         return SDValue();
6731
6732       // Determine where a rotated vector would have started.
6733       int StartIdx = i - LaneIdx;
6734       if (StartIdx == 0)
6735         // The identity rotation isn't interesting, stop.
6736         return SDValue();
6737
6738       // If we found the tail of a vector the rotation must be the missing
6739       // front. If we found the head of a vector, it must be how much of the
6740       // head.
6741       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6742
6743       if (Rotation == 0)
6744         Rotation = CandidateRotation;
6745       else if (Rotation != CandidateRotation)
6746         // The rotations don't match, so we can't match this mask.
6747         return SDValue();
6748
6749       // Compute which value this mask is pointing at.
6750       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6751
6752       // Compute which of the two target values this index should be assigned
6753       // to. This reflects whether the high elements are remaining or the low
6754       // elements are remaining.
6755       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6756
6757       // Either set up this value if we've not encountered it before, or check
6758       // that it remains consistent.
6759       if (!TargetV)
6760         TargetV = MaskV;
6761       else if (TargetV != MaskV)
6762         // This may be a rotation, but it pulls from the inputs in some
6763         // unsupported interleaving.
6764         return SDValue();
6765     }
6766   }
6767
6768   // Check that we successfully analyzed the mask, and normalize the results.
6769   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6770   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6771   if (!Lo)
6772     Lo = Hi;
6773   else if (!Hi)
6774     Hi = Lo;
6775
6776   // The actual rotate instruction rotates bytes, so we need to scale the
6777   // rotation based on how many bytes are in the vector lane.
6778   int Scale = 16 / NumLaneElts;
6779
6780   // SSSE3 targets can use the palignr instruction.
6781   if (Subtarget->hasSSSE3()) {
6782     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6783     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6784     Lo = DAG.getBitcast(AlignVT, Lo);
6785     Hi = DAG.getBitcast(AlignVT, Hi);
6786
6787     return DAG.getBitcast(
6788         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6789                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6790   }
6791
6792   assert(VT.getSizeInBits() == 128 &&
6793          "Rotate-based lowering only supports 128-bit lowering!");
6794   assert(Mask.size() <= 16 &&
6795          "Can shuffle at most 16 bytes in a 128-bit vector!");
6796
6797   // Default SSE2 implementation
6798   int LoByteShift = 16 - Rotation * Scale;
6799   int HiByteShift = Rotation * Scale;
6800
6801   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6802   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6803   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6804
6805   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6806                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6807   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6808                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6809   return DAG.getBitcast(VT,
6810                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6811 }
6812
6813 /// \brief Compute whether each element of a shuffle is zeroable.
6814 ///
6815 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6816 /// Either it is an undef element in the shuffle mask, the element of the input
6817 /// referenced is undef, or the element of the input referenced is known to be
6818 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6819 /// as many lanes with this technique as possible to simplify the remaining
6820 /// shuffle.
6821 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6822                                                      SDValue V1, SDValue V2) {
6823   SmallBitVector Zeroable(Mask.size(), false);
6824
6825   while (V1.getOpcode() == ISD::BITCAST)
6826     V1 = V1->getOperand(0);
6827   while (V2.getOpcode() == ISD::BITCAST)
6828     V2 = V2->getOperand(0);
6829
6830   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6831   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6832
6833   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6834     int M = Mask[i];
6835     // Handle the easy cases.
6836     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6837       Zeroable[i] = true;
6838       continue;
6839     }
6840
6841     // If this is an index into a build_vector node (which has the same number
6842     // of elements), dig out the input value and use it.
6843     SDValue V = M < Size ? V1 : V2;
6844     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6845       continue;
6846
6847     SDValue Input = V.getOperand(M % Size);
6848     // The UNDEF opcode check really should be dead code here, but not quite
6849     // worth asserting on (it isn't invalid, just unexpected).
6850     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6851       Zeroable[i] = true;
6852   }
6853
6854   return Zeroable;
6855 }
6856
6857 /// \brief Try to emit a bitmask instruction for a shuffle.
6858 ///
6859 /// This handles cases where we can model a blend exactly as a bitmask due to
6860 /// one of the inputs being zeroable.
6861 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6862                                            SDValue V2, ArrayRef<int> Mask,
6863                                            SelectionDAG &DAG) {
6864   MVT EltVT = VT.getScalarType();
6865   int NumEltBits = EltVT.getSizeInBits();
6866   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6867   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6868   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6869                                     IntEltVT);
6870   if (EltVT.isFloatingPoint()) {
6871     Zero = DAG.getBitcast(EltVT, Zero);
6872     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6873   }
6874   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6875   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6876   SDValue V;
6877   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6878     if (Zeroable[i])
6879       continue;
6880     if (Mask[i] % Size != i)
6881       return SDValue(); // Not a blend.
6882     if (!V)
6883       V = Mask[i] < Size ? V1 : V2;
6884     else if (V != (Mask[i] < Size ? V1 : V2))
6885       return SDValue(); // Can only let one input through the mask.
6886
6887     VMaskOps[i] = AllOnes;
6888   }
6889   if (!V)
6890     return SDValue(); // No non-zeroable elements!
6891
6892   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6893   V = DAG.getNode(VT.isFloatingPoint()
6894                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6895                   DL, VT, V, VMask);
6896   return V;
6897 }
6898
6899 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6900 ///
6901 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6902 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6903 /// matches elements from one of the input vectors shuffled to the left or
6904 /// right with zeroable elements 'shifted in'. It handles both the strictly
6905 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6906 /// quad word lane.
6907 ///
6908 /// PSHL : (little-endian) left bit shift.
6909 /// [ zz, 0, zz,  2 ]
6910 /// [ -1, 4, zz, -1 ]
6911 /// PSRL : (little-endian) right bit shift.
6912 /// [  1, zz,  3, zz]
6913 /// [ -1, -1,  7, zz]
6914 /// PSLLDQ : (little-endian) left byte shift
6915 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6916 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6917 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6918 /// PSRLDQ : (little-endian) right byte shift
6919 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6920 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6921 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6922 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6923                                          SDValue V2, ArrayRef<int> Mask,
6924                                          SelectionDAG &DAG) {
6925   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6926
6927   int Size = Mask.size();
6928   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6929
6930   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6931     for (int i = 0; i < Size; i += Scale)
6932       for (int j = 0; j < Shift; ++j)
6933         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6934           return false;
6935
6936     return true;
6937   };
6938
6939   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6940     for (int i = 0; i != Size; i += Scale) {
6941       unsigned Pos = Left ? i + Shift : i;
6942       unsigned Low = Left ? i : i + Shift;
6943       unsigned Len = Scale - Shift;
6944       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6945                                       Low + (V == V1 ? 0 : Size)))
6946         return SDValue();
6947     }
6948
6949     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6950     bool ByteShift = ShiftEltBits > 64;
6951     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6952                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6953     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6954
6955     // Normalize the scale for byte shifts to still produce an i64 element
6956     // type.
6957     Scale = ByteShift ? Scale / 2 : Scale;
6958
6959     // We need to round trip through the appropriate type for the shift.
6960     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6961     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6962     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6963            "Illegal integer vector type");
6964     V = DAG.getBitcast(ShiftVT, V);
6965
6966     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6967                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6968     return DAG.getBitcast(VT, V);
6969   };
6970
6971   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6972   // keep doubling the size of the integer elements up to that. We can
6973   // then shift the elements of the integer vector by whole multiples of
6974   // their width within the elements of the larger integer vector. Test each
6975   // multiple to see if we can find a match with the moved element indices
6976   // and that the shifted in elements are all zeroable.
6977   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6978     for (int Shift = 1; Shift != Scale; ++Shift)
6979       for (bool Left : {true, false})
6980         if (CheckZeros(Shift, Scale, Left))
6981           for (SDValue V : {V1, V2})
6982             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6983               return Match;
6984
6985   // no match
6986   return SDValue();
6987 }
6988
6989 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
6990 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
6991                                            SDValue V2, ArrayRef<int> Mask,
6992                                            SelectionDAG &DAG) {
6993   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6994   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
6995
6996   int Size = Mask.size();
6997   int HalfSize = Size / 2;
6998   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6999
7000   // Upper half must be undefined.
7001   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7002     return SDValue();
7003
7004   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7005   // Remainder of lower half result is zero and upper half is all undef.
7006   auto LowerAsEXTRQ = [&]() {
7007     // Determine the extraction length from the part of the
7008     // lower half that isn't zeroable.
7009     int Len = HalfSize;
7010     for (; Len >= 0; --Len)
7011       if (!Zeroable[Len - 1])
7012         break;
7013     assert(Len > 0 && "Zeroable shuffle mask");
7014
7015     // Attempt to match first Len sequential elements from the lower half.
7016     SDValue Src;
7017     int Idx = -1;
7018     for (int i = 0; i != Len; ++i) {
7019       int M = Mask[i];
7020       if (M < 0)
7021         continue;
7022       SDValue &V = (M < Size ? V1 : V2);
7023       M = M % Size;
7024
7025       // All mask elements must be in the lower half.
7026       if (M > HalfSize)
7027         return SDValue();
7028
7029       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7030         Src = V;
7031         Idx = M - i;
7032         continue;
7033       }
7034       return SDValue();
7035     }
7036
7037     if (Idx < 0)
7038       return SDValue();
7039
7040     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7041     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7042     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7043     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7044                        DAG.getConstant(BitLen, DL, MVT::i8),
7045                        DAG.getConstant(BitIdx, DL, MVT::i8));
7046   };
7047
7048   if (SDValue ExtrQ = LowerAsEXTRQ())
7049     return ExtrQ;
7050
7051   // INSERTQ: Extract lowest Len elements from lower half of second source and
7052   // insert over first source, starting at Idx.
7053   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7054   auto LowerAsInsertQ = [&]() {
7055     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7056       SDValue Base;
7057
7058       // Attempt to match first source from mask before insertion point.
7059       if (isUndefInRange(Mask, 0, Idx)) {
7060         /* EMPTY */
7061       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7062         Base = V1;
7063       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7064         Base = V2;
7065       } else {
7066         continue;
7067       }
7068
7069       // Extend the extraction length looking to match both the insertion of
7070       // the second source and the remaining elements of the first.
7071       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7072         SDValue Insert;
7073         int Len = Hi - Idx;
7074
7075         // Match insertion.
7076         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7077           Insert = V1;
7078         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7079           Insert = V2;
7080         } else {
7081           continue;
7082         }
7083
7084         // Match the remaining elements of the lower half.
7085         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7086           /* EMPTY */
7087         } else if ((!Base || (Base == V1)) &&
7088                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7089           Base = V1;
7090         } else if ((!Base || (Base == V2)) &&
7091                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7092                                               Size + Hi)) {
7093           Base = V2;
7094         } else {
7095           continue;
7096         }
7097
7098         // We may not have a base (first source) - this can safely be undefined.
7099         if (!Base)
7100           Base = DAG.getUNDEF(VT);
7101
7102         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7103         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7104         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7105                            DAG.getConstant(BitLen, DL, MVT::i8),
7106                            DAG.getConstant(BitIdx, DL, MVT::i8));
7107       }
7108     }
7109
7110     return SDValue();
7111   };
7112
7113   if (SDValue InsertQ = LowerAsInsertQ())
7114     return InsertQ;
7115
7116   return SDValue();
7117 }
7118
7119 /// \brief Lower a vector shuffle as a zero or any extension.
7120 ///
7121 /// Given a specific number of elements, element bit width, and extension
7122 /// stride, produce either a zero or any extension based on the available
7123 /// features of the subtarget.
7124 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7125     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7126     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7127   assert(Scale > 1 && "Need a scale to extend.");
7128   int NumElements = VT.getVectorNumElements();
7129   int EltBits = VT.getScalarSizeInBits();
7130   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7131          "Only 8, 16, and 32 bit elements can be extended.");
7132   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7133
7134   // Found a valid zext mask! Try various lowering strategies based on the
7135   // input type and available ISA extensions.
7136   if (Subtarget->hasSSE41()) {
7137     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7138                                  NumElements / Scale);
7139     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7140   }
7141
7142   // For any extends we can cheat for larger element sizes and use shuffle
7143   // instructions that can fold with a load and/or copy.
7144   if (AnyExt && EltBits == 32) {
7145     int PSHUFDMask[4] = {0, -1, 1, -1};
7146     return DAG.getBitcast(
7147         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7148                         DAG.getBitcast(MVT::v4i32, InputV),
7149                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7150   }
7151   if (AnyExt && EltBits == 16 && Scale > 2) {
7152     int PSHUFDMask[4] = {0, -1, 0, -1};
7153     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7154                          DAG.getBitcast(MVT::v4i32, InputV),
7155                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7156     int PSHUFHWMask[4] = {1, -1, -1, -1};
7157     return DAG.getBitcast(
7158         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7159                         DAG.getBitcast(MVT::v8i16, InputV),
7160                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7161   }
7162
7163   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7164   // to 64-bits.
7165   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7166     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7167     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7168
7169     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7170                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7171                                          DAG.getConstant(EltBits, DL, MVT::i8),
7172                                          DAG.getConstant(0, DL, MVT::i8)));
7173     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7174       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7175
7176     SDValue Hi =
7177         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7178                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7179                                 DAG.getConstant(EltBits, DL, MVT::i8),
7180                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7181     return DAG.getNode(ISD::BITCAST, DL, VT,
7182                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7183   }
7184
7185   // If this would require more than 2 unpack instructions to expand, use
7186   // pshufb when available. We can only use more than 2 unpack instructions
7187   // when zero extending i8 elements which also makes it easier to use pshufb.
7188   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7189     assert(NumElements == 16 && "Unexpected byte vector width!");
7190     SDValue PSHUFBMask[16];
7191     for (int i = 0; i < 16; ++i)
7192       PSHUFBMask[i] =
7193           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7194     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7195     return DAG.getBitcast(VT,
7196                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7197                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7198                                                   MVT::v16i8, PSHUFBMask)));
7199   }
7200
7201   // Otherwise emit a sequence of unpacks.
7202   do {
7203     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7204     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7205                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7206     InputV = DAG.getBitcast(InputVT, InputV);
7207     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7208     Scale /= 2;
7209     EltBits *= 2;
7210     NumElements /= 2;
7211   } while (Scale > 1);
7212   return DAG.getBitcast(VT, InputV);
7213 }
7214
7215 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7216 ///
7217 /// This routine will try to do everything in its power to cleverly lower
7218 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7219 /// check for the profitability of this lowering,  it tries to aggressively
7220 /// match this pattern. It will use all of the micro-architectural details it
7221 /// can to emit an efficient lowering. It handles both blends with all-zero
7222 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7223 /// masking out later).
7224 ///
7225 /// The reason we have dedicated lowering for zext-style shuffles is that they
7226 /// are both incredibly common and often quite performance sensitive.
7227 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7228     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7229     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7230   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7231
7232   int Bits = VT.getSizeInBits();
7233   int NumElements = VT.getVectorNumElements();
7234   assert(VT.getScalarSizeInBits() <= 32 &&
7235          "Exceeds 32-bit integer zero extension limit");
7236   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7237
7238   // Define a helper function to check a particular ext-scale and lower to it if
7239   // valid.
7240   auto Lower = [&](int Scale) -> SDValue {
7241     SDValue InputV;
7242     bool AnyExt = true;
7243     for (int i = 0; i < NumElements; ++i) {
7244       if (Mask[i] == -1)
7245         continue; // Valid anywhere but doesn't tell us anything.
7246       if (i % Scale != 0) {
7247         // Each of the extended elements need to be zeroable.
7248         if (!Zeroable[i])
7249           return SDValue();
7250
7251         // We no longer are in the anyext case.
7252         AnyExt = false;
7253         continue;
7254       }
7255
7256       // Each of the base elements needs to be consecutive indices into the
7257       // same input vector.
7258       SDValue V = Mask[i] < NumElements ? V1 : V2;
7259       if (!InputV)
7260         InputV = V;
7261       else if (InputV != V)
7262         return SDValue(); // Flip-flopping inputs.
7263
7264       if (Mask[i] % NumElements != i / Scale)
7265         return SDValue(); // Non-consecutive strided elements.
7266     }
7267
7268     // If we fail to find an input, we have a zero-shuffle which should always
7269     // have already been handled.
7270     // FIXME: Maybe handle this here in case during blending we end up with one?
7271     if (!InputV)
7272       return SDValue();
7273
7274     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7275         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7276   };
7277
7278   // The widest scale possible for extending is to a 64-bit integer.
7279   assert(Bits % 64 == 0 &&
7280          "The number of bits in a vector must be divisible by 64 on x86!");
7281   int NumExtElements = Bits / 64;
7282
7283   // Each iteration, try extending the elements half as much, but into twice as
7284   // many elements.
7285   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7286     assert(NumElements % NumExtElements == 0 &&
7287            "The input vector size must be divisible by the extended size.");
7288     if (SDValue V = Lower(NumElements / NumExtElements))
7289       return V;
7290   }
7291
7292   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7293   if (Bits != 128)
7294     return SDValue();
7295
7296   // Returns one of the source operands if the shuffle can be reduced to a
7297   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7298   auto CanZExtLowHalf = [&]() {
7299     for (int i = NumElements / 2; i != NumElements; ++i)
7300       if (!Zeroable[i])
7301         return SDValue();
7302     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7303       return V1;
7304     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7305       return V2;
7306     return SDValue();
7307   };
7308
7309   if (SDValue V = CanZExtLowHalf()) {
7310     V = DAG.getBitcast(MVT::v2i64, V);
7311     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7312     return DAG.getBitcast(VT, V);
7313   }
7314
7315   // No viable ext lowering found.
7316   return SDValue();
7317 }
7318
7319 /// \brief Try to get a scalar value for a specific element of a vector.
7320 ///
7321 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7322 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7323                                               SelectionDAG &DAG) {
7324   MVT VT = V.getSimpleValueType();
7325   MVT EltVT = VT.getVectorElementType();
7326   while (V.getOpcode() == ISD::BITCAST)
7327     V = V.getOperand(0);
7328   // If the bitcasts shift the element size, we can't extract an equivalent
7329   // element from it.
7330   MVT NewVT = V.getSimpleValueType();
7331   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7332     return SDValue();
7333
7334   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7335       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7336     // Ensure the scalar operand is the same size as the destination.
7337     // FIXME: Add support for scalar truncation where possible.
7338     SDValue S = V.getOperand(Idx);
7339     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7340       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7341   }
7342
7343   return SDValue();
7344 }
7345
7346 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7347 ///
7348 /// This is particularly important because the set of instructions varies
7349 /// significantly based on whether the operand is a load or not.
7350 static bool isShuffleFoldableLoad(SDValue V) {
7351   while (V.getOpcode() == ISD::BITCAST)
7352     V = V.getOperand(0);
7353
7354   return ISD::isNON_EXTLoad(V.getNode());
7355 }
7356
7357 /// \brief Try to lower insertion of a single element into a zero vector.
7358 ///
7359 /// This is a common pattern that we have especially efficient patterns to lower
7360 /// across all subtarget feature sets.
7361 static SDValue lowerVectorShuffleAsElementInsertion(
7362     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7363     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7364   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7365   MVT ExtVT = VT;
7366   MVT EltVT = VT.getVectorElementType();
7367
7368   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7369                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7370                 Mask.begin();
7371   bool IsV1Zeroable = true;
7372   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7373     if (i != V2Index && !Zeroable[i]) {
7374       IsV1Zeroable = false;
7375       break;
7376     }
7377
7378   // Check for a single input from a SCALAR_TO_VECTOR node.
7379   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7380   // all the smarts here sunk into that routine. However, the current
7381   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7382   // vector shuffle lowering is dead.
7383   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7384                                                DAG);
7385   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7386     // We need to zext the scalar if it is smaller than an i32.
7387     V2S = DAG.getBitcast(EltVT, V2S);
7388     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7389       // Using zext to expand a narrow element won't work for non-zero
7390       // insertions.
7391       if (!IsV1Zeroable)
7392         return SDValue();
7393
7394       // Zero-extend directly to i32.
7395       ExtVT = MVT::v4i32;
7396       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7397     }
7398     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7399   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7400              EltVT == MVT::i16) {
7401     // Either not inserting from the low element of the input or the input
7402     // element size is too small to use VZEXT_MOVL to clear the high bits.
7403     return SDValue();
7404   }
7405
7406   if (!IsV1Zeroable) {
7407     // If V1 can't be treated as a zero vector we have fewer options to lower
7408     // this. We can't support integer vectors or non-zero targets cheaply, and
7409     // the V1 elements can't be permuted in any way.
7410     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7411     if (!VT.isFloatingPoint() || V2Index != 0)
7412       return SDValue();
7413     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7414     V1Mask[V2Index] = -1;
7415     if (!isNoopShuffleMask(V1Mask))
7416       return SDValue();
7417     // This is essentially a special case blend operation, but if we have
7418     // general purpose blend operations, they are always faster. Bail and let
7419     // the rest of the lowering handle these as blends.
7420     if (Subtarget->hasSSE41())
7421       return SDValue();
7422
7423     // Otherwise, use MOVSD or MOVSS.
7424     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7425            "Only two types of floating point element types to handle!");
7426     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7427                        ExtVT, V1, V2);
7428   }
7429
7430   // This lowering only works for the low element with floating point vectors.
7431   if (VT.isFloatingPoint() && V2Index != 0)
7432     return SDValue();
7433
7434   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7435   if (ExtVT != VT)
7436     V2 = DAG.getBitcast(VT, V2);
7437
7438   if (V2Index != 0) {
7439     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7440     // the desired position. Otherwise it is more efficient to do a vector
7441     // shift left. We know that we can do a vector shift left because all
7442     // the inputs are zero.
7443     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7444       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7445       V2Shuffle[V2Index] = 0;
7446       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7447     } else {
7448       V2 = DAG.getBitcast(MVT::v2i64, V2);
7449       V2 = DAG.getNode(
7450           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7451           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7452                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7453                               DAG.getDataLayout(), VT)));
7454       V2 = DAG.getBitcast(VT, V2);
7455     }
7456   }
7457   return V2;
7458 }
7459
7460 /// \brief Try to lower broadcast of a single element.
7461 ///
7462 /// For convenience, this code also bundles all of the subtarget feature set
7463 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7464 /// a convenient way to factor it out.
7465 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7466                                              ArrayRef<int> Mask,
7467                                              const X86Subtarget *Subtarget,
7468                                              SelectionDAG &DAG) {
7469   if (!Subtarget->hasAVX())
7470     return SDValue();
7471   if (VT.isInteger() && !Subtarget->hasAVX2())
7472     return SDValue();
7473
7474   // Check that the mask is a broadcast.
7475   int BroadcastIdx = -1;
7476   for (int M : Mask)
7477     if (M >= 0 && BroadcastIdx == -1)
7478       BroadcastIdx = M;
7479     else if (M >= 0 && M != BroadcastIdx)
7480       return SDValue();
7481
7482   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7483                                             "a sorted mask where the broadcast "
7484                                             "comes from V1.");
7485
7486   // Go up the chain of (vector) values to find a scalar load that we can
7487   // combine with the broadcast.
7488   for (;;) {
7489     switch (V.getOpcode()) {
7490     case ISD::CONCAT_VECTORS: {
7491       int OperandSize = Mask.size() / V.getNumOperands();
7492       V = V.getOperand(BroadcastIdx / OperandSize);
7493       BroadcastIdx %= OperandSize;
7494       continue;
7495     }
7496
7497     case ISD::INSERT_SUBVECTOR: {
7498       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7499       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7500       if (!ConstantIdx)
7501         break;
7502
7503       int BeginIdx = (int)ConstantIdx->getZExtValue();
7504       int EndIdx =
7505           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7506       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7507         BroadcastIdx -= BeginIdx;
7508         V = VInner;
7509       } else {
7510         V = VOuter;
7511       }
7512       continue;
7513     }
7514     }
7515     break;
7516   }
7517
7518   // Check if this is a broadcast of a scalar. We special case lowering
7519   // for scalars so that we can more effectively fold with loads.
7520   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7521       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7522     V = V.getOperand(BroadcastIdx);
7523
7524     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7525     // Only AVX2 has register broadcasts.
7526     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7527       return SDValue();
7528   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7529     // We can't broadcast from a vector register without AVX2, and we can only
7530     // broadcast from the zero-element of a vector register.
7531     return SDValue();
7532   }
7533
7534   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7535 }
7536
7537 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7538 // INSERTPS when the V1 elements are already in the correct locations
7539 // because otherwise we can just always use two SHUFPS instructions which
7540 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7541 // perform INSERTPS if a single V1 element is out of place and all V2
7542 // elements are zeroable.
7543 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7544                                             ArrayRef<int> Mask,
7545                                             SelectionDAG &DAG) {
7546   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7547   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7548   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7549   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7550
7551   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7552
7553   unsigned ZMask = 0;
7554   int V1DstIndex = -1;
7555   int V2DstIndex = -1;
7556   bool V1UsedInPlace = false;
7557
7558   for (int i = 0; i < 4; ++i) {
7559     // Synthesize a zero mask from the zeroable elements (includes undefs).
7560     if (Zeroable[i]) {
7561       ZMask |= 1 << i;
7562       continue;
7563     }
7564
7565     // Flag if we use any V1 inputs in place.
7566     if (i == Mask[i]) {
7567       V1UsedInPlace = true;
7568       continue;
7569     }
7570
7571     // We can only insert a single non-zeroable element.
7572     if (V1DstIndex != -1 || V2DstIndex != -1)
7573       return SDValue();
7574
7575     if (Mask[i] < 4) {
7576       // V1 input out of place for insertion.
7577       V1DstIndex = i;
7578     } else {
7579       // V2 input for insertion.
7580       V2DstIndex = i;
7581     }
7582   }
7583
7584   // Don't bother if we have no (non-zeroable) element for insertion.
7585   if (V1DstIndex == -1 && V2DstIndex == -1)
7586     return SDValue();
7587
7588   // Determine element insertion src/dst indices. The src index is from the
7589   // start of the inserted vector, not the start of the concatenated vector.
7590   unsigned V2SrcIndex = 0;
7591   if (V1DstIndex != -1) {
7592     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7593     // and don't use the original V2 at all.
7594     V2SrcIndex = Mask[V1DstIndex];
7595     V2DstIndex = V1DstIndex;
7596     V2 = V1;
7597   } else {
7598     V2SrcIndex = Mask[V2DstIndex] - 4;
7599   }
7600
7601   // If no V1 inputs are used in place, then the result is created only from
7602   // the zero mask and the V2 insertion - so remove V1 dependency.
7603   if (!V1UsedInPlace)
7604     V1 = DAG.getUNDEF(MVT::v4f32);
7605
7606   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7607   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7608
7609   // Insert the V2 element into the desired position.
7610   SDLoc DL(Op);
7611   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7612                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7613 }
7614
7615 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7616 /// UNPCK instruction.
7617 ///
7618 /// This specifically targets cases where we end up with alternating between
7619 /// the two inputs, and so can permute them into something that feeds a single
7620 /// UNPCK instruction. Note that this routine only targets integer vectors
7621 /// because for floating point vectors we have a generalized SHUFPS lowering
7622 /// strategy that handles everything that doesn't *exactly* match an unpack,
7623 /// making this clever lowering unnecessary.
7624 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7625                                           SDValue V2, ArrayRef<int> Mask,
7626                                           SelectionDAG &DAG) {
7627   assert(!VT.isFloatingPoint() &&
7628          "This routine only supports integer vectors.");
7629   assert(!isSingleInputShuffleMask(Mask) &&
7630          "This routine should only be used when blending two inputs.");
7631   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7632
7633   int Size = Mask.size();
7634
7635   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7636     return M >= 0 && M % Size < Size / 2;
7637   });
7638   int NumHiInputs = std::count_if(
7639       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7640
7641   bool UnpackLo = NumLoInputs >= NumHiInputs;
7642
7643   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7644     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7645     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7646
7647     for (int i = 0; i < Size; ++i) {
7648       if (Mask[i] < 0)
7649         continue;
7650
7651       // Each element of the unpack contains Scale elements from this mask.
7652       int UnpackIdx = i / Scale;
7653
7654       // We only handle the case where V1 feeds the first slots of the unpack.
7655       // We rely on canonicalization to ensure this is the case.
7656       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7657         return SDValue();
7658
7659       // Setup the mask for this input. The indexing is tricky as we have to
7660       // handle the unpack stride.
7661       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7662       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7663           Mask[i] % Size;
7664     }
7665
7666     // If we will have to shuffle both inputs to use the unpack, check whether
7667     // we can just unpack first and shuffle the result. If so, skip this unpack.
7668     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7669         !isNoopShuffleMask(V2Mask))
7670       return SDValue();
7671
7672     // Shuffle the inputs into place.
7673     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7674     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7675
7676     // Cast the inputs to the type we will use to unpack them.
7677     V1 = DAG.getBitcast(UnpackVT, V1);
7678     V2 = DAG.getBitcast(UnpackVT, V2);
7679
7680     // Unpack the inputs and cast the result back to the desired type.
7681     return DAG.getBitcast(
7682         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7683                         UnpackVT, V1, V2));
7684   };
7685
7686   // We try each unpack from the largest to the smallest to try and find one
7687   // that fits this mask.
7688   int OrigNumElements = VT.getVectorNumElements();
7689   int OrigScalarSize = VT.getScalarSizeInBits();
7690   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7691     int Scale = ScalarSize / OrigScalarSize;
7692     int NumElements = OrigNumElements / Scale;
7693     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7694     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7695       return Unpack;
7696   }
7697
7698   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7699   // initial unpack.
7700   if (NumLoInputs == 0 || NumHiInputs == 0) {
7701     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7702            "We have to have *some* inputs!");
7703     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7704
7705     // FIXME: We could consider the total complexity of the permute of each
7706     // possible unpacking. Or at the least we should consider how many
7707     // half-crossings are created.
7708     // FIXME: We could consider commuting the unpacks.
7709
7710     SmallVector<int, 32> PermMask;
7711     PermMask.assign(Size, -1);
7712     for (int i = 0; i < Size; ++i) {
7713       if (Mask[i] < 0)
7714         continue;
7715
7716       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7717
7718       PermMask[i] =
7719           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7720     }
7721     return DAG.getVectorShuffle(
7722         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7723                             DL, VT, V1, V2),
7724         DAG.getUNDEF(VT), PermMask);
7725   }
7726
7727   return SDValue();
7728 }
7729
7730 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7731 ///
7732 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7733 /// support for floating point shuffles but not integer shuffles. These
7734 /// instructions will incur a domain crossing penalty on some chips though so
7735 /// it is better to avoid lowering through this for integer vectors where
7736 /// possible.
7737 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7738                                        const X86Subtarget *Subtarget,
7739                                        SelectionDAG &DAG) {
7740   SDLoc DL(Op);
7741   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7742   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7743   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7744   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7745   ArrayRef<int> Mask = SVOp->getMask();
7746   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7747
7748   if (isSingleInputShuffleMask(Mask)) {
7749     // Use low duplicate instructions for masks that match their pattern.
7750     if (Subtarget->hasSSE3())
7751       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7752         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7753
7754     // Straight shuffle of a single input vector. Simulate this by using the
7755     // single input as both of the "inputs" to this instruction..
7756     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7757
7758     if (Subtarget->hasAVX()) {
7759       // If we have AVX, we can use VPERMILPS which will allow folding a load
7760       // into the shuffle.
7761       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7762                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7763     }
7764
7765     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7766                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7767   }
7768   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7769   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7770
7771   // If we have a single input, insert that into V1 if we can do so cheaply.
7772   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7773     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7774             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7775       return Insertion;
7776     // Try inverting the insertion since for v2 masks it is easy to do and we
7777     // can't reliably sort the mask one way or the other.
7778     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7779                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7780     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7781             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7782       return Insertion;
7783   }
7784
7785   // Try to use one of the special instruction patterns to handle two common
7786   // blend patterns if a zero-blend above didn't work.
7787   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7788       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7789     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7790       // We can either use a special instruction to load over the low double or
7791       // to move just the low double.
7792       return DAG.getNode(
7793           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7794           DL, MVT::v2f64, V2,
7795           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7796
7797   if (Subtarget->hasSSE41())
7798     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7799                                                   Subtarget, DAG))
7800       return Blend;
7801
7802   // Use dedicated unpack instructions for masks that match their pattern.
7803   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7804     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7805   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7806     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7807
7808   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7809   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7810                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7811 }
7812
7813 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7814 ///
7815 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7816 /// the integer unit to minimize domain crossing penalties. However, for blends
7817 /// it falls back to the floating point shuffle operation with appropriate bit
7818 /// casting.
7819 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7820                                        const X86Subtarget *Subtarget,
7821                                        SelectionDAG &DAG) {
7822   SDLoc DL(Op);
7823   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7824   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7825   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7826   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7827   ArrayRef<int> Mask = SVOp->getMask();
7828   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7829
7830   if (isSingleInputShuffleMask(Mask)) {
7831     // Check for being able to broadcast a single element.
7832     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7833                                                           Mask, Subtarget, DAG))
7834       return Broadcast;
7835
7836     // Straight shuffle of a single input vector. For everything from SSE2
7837     // onward this has a single fast instruction with no scary immediates.
7838     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7839     V1 = DAG.getBitcast(MVT::v4i32, V1);
7840     int WidenedMask[4] = {
7841         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7842         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7843     return DAG.getBitcast(
7844         MVT::v2i64,
7845         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7846                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7847   }
7848   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7849   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7850   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7851   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7852
7853   // If we have a blend of two PACKUS operations an the blend aligns with the
7854   // low and half halves, we can just merge the PACKUS operations. This is
7855   // particularly important as it lets us merge shuffles that this routine itself
7856   // creates.
7857   auto GetPackNode = [](SDValue V) {
7858     while (V.getOpcode() == ISD::BITCAST)
7859       V = V.getOperand(0);
7860
7861     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7862   };
7863   if (SDValue V1Pack = GetPackNode(V1))
7864     if (SDValue V2Pack = GetPackNode(V2))
7865       return DAG.getBitcast(MVT::v2i64,
7866                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7867                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7868                                                      : V1Pack.getOperand(1),
7869                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7870                                                      : V2Pack.getOperand(1)));
7871
7872   // Try to use shift instructions.
7873   if (SDValue Shift =
7874           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7875     return Shift;
7876
7877   // When loading a scalar and then shuffling it into a vector we can often do
7878   // the insertion cheaply.
7879   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7880           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7881     return Insertion;
7882   // Try inverting the insertion since for v2 masks it is easy to do and we
7883   // can't reliably sort the mask one way or the other.
7884   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7885   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7886           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7887     return Insertion;
7888
7889   // We have different paths for blend lowering, but they all must use the
7890   // *exact* same predicate.
7891   bool IsBlendSupported = Subtarget->hasSSE41();
7892   if (IsBlendSupported)
7893     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7894                                                   Subtarget, DAG))
7895       return Blend;
7896
7897   // Use dedicated unpack instructions for masks that match their pattern.
7898   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7899     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7900   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7901     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7902
7903   // Try to use byte rotation instructions.
7904   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7905   if (Subtarget->hasSSSE3())
7906     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7907             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7908       return Rotate;
7909
7910   // If we have direct support for blends, we should lower by decomposing into
7911   // a permute. That will be faster than the domain cross.
7912   if (IsBlendSupported)
7913     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7914                                                       Mask, DAG);
7915
7916   // We implement this with SHUFPD which is pretty lame because it will likely
7917   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7918   // However, all the alternatives are still more cycles and newer chips don't
7919   // have this problem. It would be really nice if x86 had better shuffles here.
7920   V1 = DAG.getBitcast(MVT::v2f64, V1);
7921   V2 = DAG.getBitcast(MVT::v2f64, V2);
7922   return DAG.getBitcast(MVT::v2i64,
7923                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7924 }
7925
7926 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7927 ///
7928 /// This is used to disable more specialized lowerings when the shufps lowering
7929 /// will happen to be efficient.
7930 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7931   // This routine only handles 128-bit shufps.
7932   assert(Mask.size() == 4 && "Unsupported mask size!");
7933
7934   // To lower with a single SHUFPS we need to have the low half and high half
7935   // each requiring a single input.
7936   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7937     return false;
7938   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7939     return false;
7940
7941   return true;
7942 }
7943
7944 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7945 ///
7946 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7947 /// It makes no assumptions about whether this is the *best* lowering, it simply
7948 /// uses it.
7949 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7950                                             ArrayRef<int> Mask, SDValue V1,
7951                                             SDValue V2, SelectionDAG &DAG) {
7952   SDValue LowV = V1, HighV = V2;
7953   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7954
7955   int NumV2Elements =
7956       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7957
7958   if (NumV2Elements == 1) {
7959     int V2Index =
7960         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7961         Mask.begin();
7962
7963     // Compute the index adjacent to V2Index and in the same half by toggling
7964     // the low bit.
7965     int V2AdjIndex = V2Index ^ 1;
7966
7967     if (Mask[V2AdjIndex] == -1) {
7968       // Handles all the cases where we have a single V2 element and an undef.
7969       // This will only ever happen in the high lanes because we commute the
7970       // vector otherwise.
7971       if (V2Index < 2)
7972         std::swap(LowV, HighV);
7973       NewMask[V2Index] -= 4;
7974     } else {
7975       // Handle the case where the V2 element ends up adjacent to a V1 element.
7976       // To make this work, blend them together as the first step.
7977       int V1Index = V2AdjIndex;
7978       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7979       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7980                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7981
7982       // Now proceed to reconstruct the final blend as we have the necessary
7983       // high or low half formed.
7984       if (V2Index < 2) {
7985         LowV = V2;
7986         HighV = V1;
7987       } else {
7988         HighV = V2;
7989       }
7990       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7991       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7992     }
7993   } else if (NumV2Elements == 2) {
7994     if (Mask[0] < 4 && Mask[1] < 4) {
7995       // Handle the easy case where we have V1 in the low lanes and V2 in the
7996       // high lanes.
7997       NewMask[2] -= 4;
7998       NewMask[3] -= 4;
7999     } else if (Mask[2] < 4 && Mask[3] < 4) {
8000       // We also handle the reversed case because this utility may get called
8001       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8002       // arrange things in the right direction.
8003       NewMask[0] -= 4;
8004       NewMask[1] -= 4;
8005       HighV = V1;
8006       LowV = V2;
8007     } else {
8008       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8009       // trying to place elements directly, just blend them and set up the final
8010       // shuffle to place them.
8011
8012       // The first two blend mask elements are for V1, the second two are for
8013       // V2.
8014       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8015                           Mask[2] < 4 ? Mask[2] : Mask[3],
8016                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8017                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8018       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8019                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8020
8021       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8022       // a blend.
8023       LowV = HighV = V1;
8024       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8025       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8026       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8027       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8028     }
8029   }
8030   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8031                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8032 }
8033
8034 /// \brief Lower 4-lane 32-bit floating point shuffles.
8035 ///
8036 /// Uses instructions exclusively from the floating point unit to minimize
8037 /// domain crossing penalties, as these are sufficient to implement all v4f32
8038 /// shuffles.
8039 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8040                                        const X86Subtarget *Subtarget,
8041                                        SelectionDAG &DAG) {
8042   SDLoc DL(Op);
8043   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8044   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8045   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8046   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8047   ArrayRef<int> Mask = SVOp->getMask();
8048   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8049
8050   int NumV2Elements =
8051       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8052
8053   if (NumV2Elements == 0) {
8054     // Check for being able to broadcast a single element.
8055     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8056                                                           Mask, Subtarget, DAG))
8057       return Broadcast;
8058
8059     // Use even/odd duplicate instructions for masks that match their pattern.
8060     if (Subtarget->hasSSE3()) {
8061       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8062         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8063       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8064         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8065     }
8066
8067     if (Subtarget->hasAVX()) {
8068       // If we have AVX, we can use VPERMILPS which will allow folding a load
8069       // into the shuffle.
8070       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8071                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8072     }
8073
8074     // Otherwise, use a straight shuffle of a single input vector. We pass the
8075     // input vector to both operands to simulate this with a SHUFPS.
8076     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8077                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8078   }
8079
8080   // There are special ways we can lower some single-element blends. However, we
8081   // have custom ways we can lower more complex single-element blends below that
8082   // we defer to if both this and BLENDPS fail to match, so restrict this to
8083   // when the V2 input is targeting element 0 of the mask -- that is the fast
8084   // case here.
8085   if (NumV2Elements == 1 && Mask[0] >= 4)
8086     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8087                                                          Mask, Subtarget, DAG))
8088       return V;
8089
8090   if (Subtarget->hasSSE41()) {
8091     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8092                                                   Subtarget, DAG))
8093       return Blend;
8094
8095     // Use INSERTPS if we can complete the shuffle efficiently.
8096     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8097       return V;
8098
8099     if (!isSingleSHUFPSMask(Mask))
8100       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8101               DL, MVT::v4f32, V1, V2, Mask, DAG))
8102         return BlendPerm;
8103   }
8104
8105   // Use dedicated unpack instructions for masks that match their pattern.
8106   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8107     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8108   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8109     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8110   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8111     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8112   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8113     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8114
8115   // Otherwise fall back to a SHUFPS lowering strategy.
8116   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8117 }
8118
8119 /// \brief Lower 4-lane i32 vector shuffles.
8120 ///
8121 /// We try to handle these with integer-domain shuffles where we can, but for
8122 /// blends we use the floating point domain blend instructions.
8123 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8124                                        const X86Subtarget *Subtarget,
8125                                        SelectionDAG &DAG) {
8126   SDLoc DL(Op);
8127   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8128   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8129   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8130   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8131   ArrayRef<int> Mask = SVOp->getMask();
8132   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8133
8134   // Whenever we can lower this as a zext, that instruction is strictly faster
8135   // than any alternative. It also allows us to fold memory operands into the
8136   // shuffle in many cases.
8137   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8138                                                          Mask, Subtarget, DAG))
8139     return ZExt;
8140
8141   int NumV2Elements =
8142       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8143
8144   if (NumV2Elements == 0) {
8145     // Check for being able to broadcast a single element.
8146     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8147                                                           Mask, Subtarget, DAG))
8148       return Broadcast;
8149
8150     // Straight shuffle of a single input vector. For everything from SSE2
8151     // onward this has a single fast instruction with no scary immediates.
8152     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8153     // but we aren't actually going to use the UNPCK instruction because doing
8154     // so prevents folding a load into this instruction or making a copy.
8155     const int UnpackLoMask[] = {0, 0, 1, 1};
8156     const int UnpackHiMask[] = {2, 2, 3, 3};
8157     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8158       Mask = UnpackLoMask;
8159     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8160       Mask = UnpackHiMask;
8161
8162     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8163                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8164   }
8165
8166   // Try to use shift instructions.
8167   if (SDValue Shift =
8168           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8169     return Shift;
8170
8171   // There are special ways we can lower some single-element blends.
8172   if (NumV2Elements == 1)
8173     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8174                                                          Mask, Subtarget, DAG))
8175       return V;
8176
8177   // We have different paths for blend lowering, but they all must use the
8178   // *exact* same predicate.
8179   bool IsBlendSupported = Subtarget->hasSSE41();
8180   if (IsBlendSupported)
8181     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8182                                                   Subtarget, DAG))
8183       return Blend;
8184
8185   if (SDValue Masked =
8186           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8187     return Masked;
8188
8189   // Use dedicated unpack instructions for masks that match their pattern.
8190   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8191     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8192   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8193     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8194   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8195     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8196   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8197     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8198
8199   // Try to use byte rotation instructions.
8200   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8201   if (Subtarget->hasSSSE3())
8202     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8203             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8204       return Rotate;
8205
8206   // If we have direct support for blends, we should lower by decomposing into
8207   // a permute. That will be faster than the domain cross.
8208   if (IsBlendSupported)
8209     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8210                                                       Mask, DAG);
8211
8212   // Try to lower by permuting the inputs into an unpack instruction.
8213   if (SDValue Unpack =
8214           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8215     return Unpack;
8216
8217   // We implement this with SHUFPS because it can blend from two vectors.
8218   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8219   // up the inputs, bypassing domain shift penalties that we would encur if we
8220   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8221   // relevant.
8222   return DAG.getBitcast(
8223       MVT::v4i32,
8224       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8225                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8226 }
8227
8228 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8229 /// shuffle lowering, and the most complex part.
8230 ///
8231 /// The lowering strategy is to try to form pairs of input lanes which are
8232 /// targeted at the same half of the final vector, and then use a dword shuffle
8233 /// to place them onto the right half, and finally unpack the paired lanes into
8234 /// their final position.
8235 ///
8236 /// The exact breakdown of how to form these dword pairs and align them on the
8237 /// correct sides is really tricky. See the comments within the function for
8238 /// more of the details.
8239 ///
8240 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8241 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8242 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8243 /// vector, form the analogous 128-bit 8-element Mask.
8244 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8245     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8246     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8247   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8248   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8249
8250   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8251   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8252   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8253
8254   SmallVector<int, 4> LoInputs;
8255   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8256                [](int M) { return M >= 0; });
8257   std::sort(LoInputs.begin(), LoInputs.end());
8258   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8259   SmallVector<int, 4> HiInputs;
8260   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8261                [](int M) { return M >= 0; });
8262   std::sort(HiInputs.begin(), HiInputs.end());
8263   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8264   int NumLToL =
8265       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8266   int NumHToL = LoInputs.size() - NumLToL;
8267   int NumLToH =
8268       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8269   int NumHToH = HiInputs.size() - NumLToH;
8270   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8271   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8272   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8273   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8274
8275   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8276   // such inputs we can swap two of the dwords across the half mark and end up
8277   // with <=2 inputs to each half in each half. Once there, we can fall through
8278   // to the generic code below. For example:
8279   //
8280   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8281   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8282   //
8283   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8284   // and an existing 2-into-2 on the other half. In this case we may have to
8285   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8286   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8287   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8288   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8289   // half than the one we target for fixing) will be fixed when we re-enter this
8290   // path. We will also combine away any sequence of PSHUFD instructions that
8291   // result into a single instruction. Here is an example of the tricky case:
8292   //
8293   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8294   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8295   //
8296   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8297   //
8298   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8299   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8300   //
8301   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8302   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8303   //
8304   // The result is fine to be handled by the generic logic.
8305   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8306                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8307                           int AOffset, int BOffset) {
8308     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8309            "Must call this with A having 3 or 1 inputs from the A half.");
8310     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8311            "Must call this with B having 1 or 3 inputs from the B half.");
8312     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8313            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8314
8315     // Compute the index of dword with only one word among the three inputs in
8316     // a half by taking the sum of the half with three inputs and subtracting
8317     // the sum of the actual three inputs. The difference is the remaining
8318     // slot.
8319     int ADWord, BDWord;
8320     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8321     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8322     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8323     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8324     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8325     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8326     int TripleNonInputIdx =
8327         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8328     TripleDWord = TripleNonInputIdx / 2;
8329
8330     // We use xor with one to compute the adjacent DWord to whichever one the
8331     // OneInput is in.
8332     OneInputDWord = (OneInput / 2) ^ 1;
8333
8334     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8335     // and BToA inputs. If there is also such a problem with the BToB and AToB
8336     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8337     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8338     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8339     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8340       // Compute how many inputs will be flipped by swapping these DWords. We
8341       // need
8342       // to balance this to ensure we don't form a 3-1 shuffle in the other
8343       // half.
8344       int NumFlippedAToBInputs =
8345           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8346           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8347       int NumFlippedBToBInputs =
8348           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8349           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8350       if ((NumFlippedAToBInputs == 1 &&
8351            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8352           (NumFlippedBToBInputs == 1 &&
8353            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8354         // We choose whether to fix the A half or B half based on whether that
8355         // half has zero flipped inputs. At zero, we may not be able to fix it
8356         // with that half. We also bias towards fixing the B half because that
8357         // will more commonly be the high half, and we have to bias one way.
8358         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8359                                                        ArrayRef<int> Inputs) {
8360           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8361           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8362                                          PinnedIdx ^ 1) != Inputs.end();
8363           // Determine whether the free index is in the flipped dword or the
8364           // unflipped dword based on where the pinned index is. We use this bit
8365           // in an xor to conditionally select the adjacent dword.
8366           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8367           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8368                                              FixFreeIdx) != Inputs.end();
8369           if (IsFixIdxInput == IsFixFreeIdxInput)
8370             FixFreeIdx += 1;
8371           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8372                                         FixFreeIdx) != Inputs.end();
8373           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8374                  "We need to be changing the number of flipped inputs!");
8375           int PSHUFHalfMask[] = {0, 1, 2, 3};
8376           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8377           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8378                           MVT::v8i16, V,
8379                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8380
8381           for (int &M : Mask)
8382             if (M != -1 && M == FixIdx)
8383               M = FixFreeIdx;
8384             else if (M != -1 && M == FixFreeIdx)
8385               M = FixIdx;
8386         };
8387         if (NumFlippedBToBInputs != 0) {
8388           int BPinnedIdx =
8389               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8390           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8391         } else {
8392           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8393           int APinnedIdx =
8394               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8395           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8396         }
8397       }
8398     }
8399
8400     int PSHUFDMask[] = {0, 1, 2, 3};
8401     PSHUFDMask[ADWord] = BDWord;
8402     PSHUFDMask[BDWord] = ADWord;
8403     V = DAG.getBitcast(
8404         VT,
8405         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8406                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8407
8408     // Adjust the mask to match the new locations of A and B.
8409     for (int &M : Mask)
8410       if (M != -1 && M/2 == ADWord)
8411         M = 2 * BDWord + M % 2;
8412       else if (M != -1 && M/2 == BDWord)
8413         M = 2 * ADWord + M % 2;
8414
8415     // Recurse back into this routine to re-compute state now that this isn't
8416     // a 3 and 1 problem.
8417     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8418                                                      DAG);
8419   };
8420   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8421     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8422   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8423     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8424
8425   // At this point there are at most two inputs to the low and high halves from
8426   // each half. That means the inputs can always be grouped into dwords and
8427   // those dwords can then be moved to the correct half with a dword shuffle.
8428   // We use at most one low and one high word shuffle to collect these paired
8429   // inputs into dwords, and finally a dword shuffle to place them.
8430   int PSHUFLMask[4] = {-1, -1, -1, -1};
8431   int PSHUFHMask[4] = {-1, -1, -1, -1};
8432   int PSHUFDMask[4] = {-1, -1, -1, -1};
8433
8434   // First fix the masks for all the inputs that are staying in their
8435   // original halves. This will then dictate the targets of the cross-half
8436   // shuffles.
8437   auto fixInPlaceInputs =
8438       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8439                     MutableArrayRef<int> SourceHalfMask,
8440                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8441     if (InPlaceInputs.empty())
8442       return;
8443     if (InPlaceInputs.size() == 1) {
8444       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8445           InPlaceInputs[0] - HalfOffset;
8446       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8447       return;
8448     }
8449     if (IncomingInputs.empty()) {
8450       // Just fix all of the in place inputs.
8451       for (int Input : InPlaceInputs) {
8452         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8453         PSHUFDMask[Input / 2] = Input / 2;
8454       }
8455       return;
8456     }
8457
8458     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8459     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8460         InPlaceInputs[0] - HalfOffset;
8461     // Put the second input next to the first so that they are packed into
8462     // a dword. We find the adjacent index by toggling the low bit.
8463     int AdjIndex = InPlaceInputs[0] ^ 1;
8464     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8465     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8466     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8467   };
8468   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8469   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8470
8471   // Now gather the cross-half inputs and place them into a free dword of
8472   // their target half.
8473   // FIXME: This operation could almost certainly be simplified dramatically to
8474   // look more like the 3-1 fixing operation.
8475   auto moveInputsToRightHalf = [&PSHUFDMask](
8476       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8477       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8478       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8479       int DestOffset) {
8480     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8481       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8482     };
8483     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8484                                                int Word) {
8485       int LowWord = Word & ~1;
8486       int HighWord = Word | 1;
8487       return isWordClobbered(SourceHalfMask, LowWord) ||
8488              isWordClobbered(SourceHalfMask, HighWord);
8489     };
8490
8491     if (IncomingInputs.empty())
8492       return;
8493
8494     if (ExistingInputs.empty()) {
8495       // Map any dwords with inputs from them into the right half.
8496       for (int Input : IncomingInputs) {
8497         // If the source half mask maps over the inputs, turn those into
8498         // swaps and use the swapped lane.
8499         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8500           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8501             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8502                 Input - SourceOffset;
8503             // We have to swap the uses in our half mask in one sweep.
8504             for (int &M : HalfMask)
8505               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8506                 M = Input;
8507               else if (M == Input)
8508                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8509           } else {
8510             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8511                        Input - SourceOffset &&
8512                    "Previous placement doesn't match!");
8513           }
8514           // Note that this correctly re-maps both when we do a swap and when
8515           // we observe the other side of the swap above. We rely on that to
8516           // avoid swapping the members of the input list directly.
8517           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8518         }
8519
8520         // Map the input's dword into the correct half.
8521         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8522           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8523         else
8524           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8525                      Input / 2 &&
8526                  "Previous placement doesn't match!");
8527       }
8528
8529       // And just directly shift any other-half mask elements to be same-half
8530       // as we will have mirrored the dword containing the element into the
8531       // same position within that half.
8532       for (int &M : HalfMask)
8533         if (M >= SourceOffset && M < SourceOffset + 4) {
8534           M = M - SourceOffset + DestOffset;
8535           assert(M >= 0 && "This should never wrap below zero!");
8536         }
8537       return;
8538     }
8539
8540     // Ensure we have the input in a viable dword of its current half. This
8541     // is particularly tricky because the original position may be clobbered
8542     // by inputs being moved and *staying* in that half.
8543     if (IncomingInputs.size() == 1) {
8544       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8545         int InputFixed = std::find(std::begin(SourceHalfMask),
8546                                    std::end(SourceHalfMask), -1) -
8547                          std::begin(SourceHalfMask) + SourceOffset;
8548         SourceHalfMask[InputFixed - SourceOffset] =
8549             IncomingInputs[0] - SourceOffset;
8550         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8551                      InputFixed);
8552         IncomingInputs[0] = InputFixed;
8553       }
8554     } else if (IncomingInputs.size() == 2) {
8555       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8556           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8557         // We have two non-adjacent or clobbered inputs we need to extract from
8558         // the source half. To do this, we need to map them into some adjacent
8559         // dword slot in the source mask.
8560         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8561                               IncomingInputs[1] - SourceOffset};
8562
8563         // If there is a free slot in the source half mask adjacent to one of
8564         // the inputs, place the other input in it. We use (Index XOR 1) to
8565         // compute an adjacent index.
8566         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8567             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8568           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8569           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8570           InputsFixed[1] = InputsFixed[0] ^ 1;
8571         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8572                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8573           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8574           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8575           InputsFixed[0] = InputsFixed[1] ^ 1;
8576         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8577                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8578           // The two inputs are in the same DWord but it is clobbered and the
8579           // adjacent DWord isn't used at all. Move both inputs to the free
8580           // slot.
8581           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8582           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8583           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8584           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8585         } else {
8586           // The only way we hit this point is if there is no clobbering
8587           // (because there are no off-half inputs to this half) and there is no
8588           // free slot adjacent to one of the inputs. In this case, we have to
8589           // swap an input with a non-input.
8590           for (int i = 0; i < 4; ++i)
8591             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8592                    "We can't handle any clobbers here!");
8593           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8594                  "Cannot have adjacent inputs here!");
8595
8596           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8597           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8598
8599           // We also have to update the final source mask in this case because
8600           // it may need to undo the above swap.
8601           for (int &M : FinalSourceHalfMask)
8602             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8603               M = InputsFixed[1] + SourceOffset;
8604             else if (M == InputsFixed[1] + SourceOffset)
8605               M = (InputsFixed[0] ^ 1) + SourceOffset;
8606
8607           InputsFixed[1] = InputsFixed[0] ^ 1;
8608         }
8609
8610         // Point everything at the fixed inputs.
8611         for (int &M : HalfMask)
8612           if (M == IncomingInputs[0])
8613             M = InputsFixed[0] + SourceOffset;
8614           else if (M == IncomingInputs[1])
8615             M = InputsFixed[1] + SourceOffset;
8616
8617         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8618         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8619       }
8620     } else {
8621       llvm_unreachable("Unhandled input size!");
8622     }
8623
8624     // Now hoist the DWord down to the right half.
8625     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8626     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8627     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8628     for (int &M : HalfMask)
8629       for (int Input : IncomingInputs)
8630         if (M == Input)
8631           M = FreeDWord * 2 + Input % 2;
8632   };
8633   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8634                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8635   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8636                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8637
8638   // Now enact all the shuffles we've computed to move the inputs into their
8639   // target half.
8640   if (!isNoopShuffleMask(PSHUFLMask))
8641     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8642                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8643   if (!isNoopShuffleMask(PSHUFHMask))
8644     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8645                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8646   if (!isNoopShuffleMask(PSHUFDMask))
8647     V = DAG.getBitcast(
8648         VT,
8649         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8650                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8651
8652   // At this point, each half should contain all its inputs, and we can then
8653   // just shuffle them into their final position.
8654   assert(std::count_if(LoMask.begin(), LoMask.end(),
8655                        [](int M) { return M >= 4; }) == 0 &&
8656          "Failed to lift all the high half inputs to the low mask!");
8657   assert(std::count_if(HiMask.begin(), HiMask.end(),
8658                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8659          "Failed to lift all the low half inputs to the high mask!");
8660
8661   // Do a half shuffle for the low mask.
8662   if (!isNoopShuffleMask(LoMask))
8663     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8664                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8665
8666   // Do a half shuffle with the high mask after shifting its values down.
8667   for (int &M : HiMask)
8668     if (M >= 0)
8669       M -= 4;
8670   if (!isNoopShuffleMask(HiMask))
8671     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8672                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8673
8674   return V;
8675 }
8676
8677 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8678 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8679                                           SDValue V2, ArrayRef<int> Mask,
8680                                           SelectionDAG &DAG, bool &V1InUse,
8681                                           bool &V2InUse) {
8682   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8683   SDValue V1Mask[16];
8684   SDValue V2Mask[16];
8685   V1InUse = false;
8686   V2InUse = false;
8687
8688   int Size = Mask.size();
8689   int Scale = 16 / Size;
8690   for (int i = 0; i < 16; ++i) {
8691     if (Mask[i / Scale] == -1) {
8692       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8693     } else {
8694       const int ZeroMask = 0x80;
8695       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8696                                           : ZeroMask;
8697       int V2Idx = Mask[i / Scale] < Size
8698                       ? ZeroMask
8699                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8700       if (Zeroable[i / Scale])
8701         V1Idx = V2Idx = ZeroMask;
8702       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8703       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8704       V1InUse |= (ZeroMask != V1Idx);
8705       V2InUse |= (ZeroMask != V2Idx);
8706     }
8707   }
8708
8709   if (V1InUse)
8710     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8711                      DAG.getBitcast(MVT::v16i8, V1),
8712                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8713   if (V2InUse)
8714     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8715                      DAG.getBitcast(MVT::v16i8, V2),
8716                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8717
8718   // If we need shuffled inputs from both, blend the two.
8719   SDValue V;
8720   if (V1InUse && V2InUse)
8721     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8722   else
8723     V = V1InUse ? V1 : V2;
8724
8725   // Cast the result back to the correct type.
8726   return DAG.getBitcast(VT, V);
8727 }
8728
8729 /// \brief Generic lowering of 8-lane i16 shuffles.
8730 ///
8731 /// This handles both single-input shuffles and combined shuffle/blends with
8732 /// two inputs. The single input shuffles are immediately delegated to
8733 /// a dedicated lowering routine.
8734 ///
8735 /// The blends are lowered in one of three fundamental ways. If there are few
8736 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8737 /// of the input is significantly cheaper when lowered as an interleaving of
8738 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8739 /// halves of the inputs separately (making them have relatively few inputs)
8740 /// and then concatenate them.
8741 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8742                                        const X86Subtarget *Subtarget,
8743                                        SelectionDAG &DAG) {
8744   SDLoc DL(Op);
8745   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8746   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8747   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8748   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8749   ArrayRef<int> OrigMask = SVOp->getMask();
8750   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8751                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8752   MutableArrayRef<int> Mask(MaskStorage);
8753
8754   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8755
8756   // Whenever we can lower this as a zext, that instruction is strictly faster
8757   // than any alternative.
8758   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8759           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8760     return ZExt;
8761
8762   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8763   (void)isV1;
8764   auto isV2 = [](int M) { return M >= 8; };
8765
8766   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8767
8768   if (NumV2Inputs == 0) {
8769     // Check for being able to broadcast a single element.
8770     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8771                                                           Mask, Subtarget, DAG))
8772       return Broadcast;
8773
8774     // Try to use shift instructions.
8775     if (SDValue Shift =
8776             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8777       return Shift;
8778
8779     // Use dedicated unpack instructions for masks that match their pattern.
8780     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8781       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8782     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8783       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8784
8785     // Try to use byte rotation instructions.
8786     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8787                                                         Mask, Subtarget, DAG))
8788       return Rotate;
8789
8790     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8791                                                      Subtarget, DAG);
8792   }
8793
8794   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8795          "All single-input shuffles should be canonicalized to be V1-input "
8796          "shuffles.");
8797
8798   // Try to use shift instructions.
8799   if (SDValue Shift =
8800           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8801     return Shift;
8802
8803   // See if we can use SSE4A Extraction / Insertion.
8804   if (Subtarget->hasSSE4A())
8805     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8806       return V;
8807
8808   // There are special ways we can lower some single-element blends.
8809   if (NumV2Inputs == 1)
8810     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8811                                                          Mask, Subtarget, DAG))
8812       return V;
8813
8814   // We have different paths for blend lowering, but they all must use the
8815   // *exact* same predicate.
8816   bool IsBlendSupported = Subtarget->hasSSE41();
8817   if (IsBlendSupported)
8818     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8819                                                   Subtarget, DAG))
8820       return Blend;
8821
8822   if (SDValue Masked =
8823           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8824     return Masked;
8825
8826   // Use dedicated unpack instructions for masks that match their pattern.
8827   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8828     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8829   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8830     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8831
8832   // Try to use byte rotation instructions.
8833   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8834           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8835     return Rotate;
8836
8837   if (SDValue BitBlend =
8838           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8839     return BitBlend;
8840
8841   if (SDValue Unpack =
8842           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8843     return Unpack;
8844
8845   // If we can't directly blend but can use PSHUFB, that will be better as it
8846   // can both shuffle and set up the inefficient blend.
8847   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8848     bool V1InUse, V2InUse;
8849     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8850                                       V1InUse, V2InUse);
8851   }
8852
8853   // We can always bit-blend if we have to so the fallback strategy is to
8854   // decompose into single-input permutes and blends.
8855   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8856                                                       Mask, DAG);
8857 }
8858
8859 /// \brief Check whether a compaction lowering can be done by dropping even
8860 /// elements and compute how many times even elements must be dropped.
8861 ///
8862 /// This handles shuffles which take every Nth element where N is a power of
8863 /// two. Example shuffle masks:
8864 ///
8865 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8866 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8867 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8868 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8869 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8870 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8871 ///
8872 /// Any of these lanes can of course be undef.
8873 ///
8874 /// This routine only supports N <= 3.
8875 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8876 /// for larger N.
8877 ///
8878 /// \returns N above, or the number of times even elements must be dropped if
8879 /// there is such a number. Otherwise returns zero.
8880 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8881   // Figure out whether we're looping over two inputs or just one.
8882   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8883
8884   // The modulus for the shuffle vector entries is based on whether this is
8885   // a single input or not.
8886   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8887   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8888          "We should only be called with masks with a power-of-2 size!");
8889
8890   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8891
8892   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8893   // and 2^3 simultaneously. This is because we may have ambiguity with
8894   // partially undef inputs.
8895   bool ViableForN[3] = {true, true, true};
8896
8897   for (int i = 0, e = Mask.size(); i < e; ++i) {
8898     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8899     // want.
8900     if (Mask[i] == -1)
8901       continue;
8902
8903     bool IsAnyViable = false;
8904     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8905       if (ViableForN[j]) {
8906         uint64_t N = j + 1;
8907
8908         // The shuffle mask must be equal to (i * 2^N) % M.
8909         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8910           IsAnyViable = true;
8911         else
8912           ViableForN[j] = false;
8913       }
8914     // Early exit if we exhaust the possible powers of two.
8915     if (!IsAnyViable)
8916       break;
8917   }
8918
8919   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8920     if (ViableForN[j])
8921       return j + 1;
8922
8923   // Return 0 as there is no viable power of two.
8924   return 0;
8925 }
8926
8927 /// \brief Generic lowering of v16i8 shuffles.
8928 ///
8929 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8930 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8931 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8932 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8933 /// back together.
8934 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8935                                        const X86Subtarget *Subtarget,
8936                                        SelectionDAG &DAG) {
8937   SDLoc DL(Op);
8938   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8939   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8940   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8941   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8942   ArrayRef<int> Mask = SVOp->getMask();
8943   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8944
8945   // Try to use shift instructions.
8946   if (SDValue Shift =
8947           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8948     return Shift;
8949
8950   // Try to use byte rotation instructions.
8951   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8952           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8953     return Rotate;
8954
8955   // Try to use a zext lowering.
8956   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8957           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8958     return ZExt;
8959
8960   // See if we can use SSE4A Extraction / Insertion.
8961   if (Subtarget->hasSSE4A())
8962     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8963       return V;
8964
8965   int NumV2Elements =
8966       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8967
8968   // For single-input shuffles, there are some nicer lowering tricks we can use.
8969   if (NumV2Elements == 0) {
8970     // Check for being able to broadcast a single element.
8971     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8972                                                           Mask, Subtarget, DAG))
8973       return Broadcast;
8974
8975     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8976     // Notably, this handles splat and partial-splat shuffles more efficiently.
8977     // However, it only makes sense if the pre-duplication shuffle simplifies
8978     // things significantly. Currently, this means we need to be able to
8979     // express the pre-duplication shuffle as an i16 shuffle.
8980     //
8981     // FIXME: We should check for other patterns which can be widened into an
8982     // i16 shuffle as well.
8983     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8984       for (int i = 0; i < 16; i += 2)
8985         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8986           return false;
8987
8988       return true;
8989     };
8990     auto tryToWidenViaDuplication = [&]() -> SDValue {
8991       if (!canWidenViaDuplication(Mask))
8992         return SDValue();
8993       SmallVector<int, 4> LoInputs;
8994       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8995                    [](int M) { return M >= 0 && M < 8; });
8996       std::sort(LoInputs.begin(), LoInputs.end());
8997       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8998                      LoInputs.end());
8999       SmallVector<int, 4> HiInputs;
9000       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9001                    [](int M) { return M >= 8; });
9002       std::sort(HiInputs.begin(), HiInputs.end());
9003       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9004                      HiInputs.end());
9005
9006       bool TargetLo = LoInputs.size() >= HiInputs.size();
9007       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9008       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9009
9010       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9011       SmallDenseMap<int, int, 8> LaneMap;
9012       for (int I : InPlaceInputs) {
9013         PreDupI16Shuffle[I/2] = I/2;
9014         LaneMap[I] = I;
9015       }
9016       int j = TargetLo ? 0 : 4, je = j + 4;
9017       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9018         // Check if j is already a shuffle of this input. This happens when
9019         // there are two adjacent bytes after we move the low one.
9020         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9021           // If we haven't yet mapped the input, search for a slot into which
9022           // we can map it.
9023           while (j < je && PreDupI16Shuffle[j] != -1)
9024             ++j;
9025
9026           if (j == je)
9027             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9028             return SDValue();
9029
9030           // Map this input with the i16 shuffle.
9031           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9032         }
9033
9034         // Update the lane map based on the mapping we ended up with.
9035         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9036       }
9037       V1 = DAG.getBitcast(
9038           MVT::v16i8,
9039           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9040                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9041
9042       // Unpack the bytes to form the i16s that will be shuffled into place.
9043       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9044                        MVT::v16i8, V1, V1);
9045
9046       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9047       for (int i = 0; i < 16; ++i)
9048         if (Mask[i] != -1) {
9049           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9050           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9051           if (PostDupI16Shuffle[i / 2] == -1)
9052             PostDupI16Shuffle[i / 2] = MappedMask;
9053           else
9054             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9055                    "Conflicting entrties in the original shuffle!");
9056         }
9057       return DAG.getBitcast(
9058           MVT::v16i8,
9059           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9060                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9061     };
9062     if (SDValue V = tryToWidenViaDuplication())
9063       return V;
9064   }
9065
9066   // Use dedicated unpack instructions for masks that match their pattern.
9067   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9068                                          0, 16, 1, 17, 2, 18, 3, 19,
9069                                          // High half.
9070                                          4, 20, 5, 21, 6, 22, 7, 23}))
9071     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9072   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9073                                          8, 24, 9, 25, 10, 26, 11, 27,
9074                                          // High half.
9075                                          12, 28, 13, 29, 14, 30, 15, 31}))
9076     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9077
9078   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9079   // with PSHUFB. It is important to do this before we attempt to generate any
9080   // blends but after all of the single-input lowerings. If the single input
9081   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9082   // want to preserve that and we can DAG combine any longer sequences into
9083   // a PSHUFB in the end. But once we start blending from multiple inputs,
9084   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9085   // and there are *very* few patterns that would actually be faster than the
9086   // PSHUFB approach because of its ability to zero lanes.
9087   //
9088   // FIXME: The only exceptions to the above are blends which are exact
9089   // interleavings with direct instructions supporting them. We currently don't
9090   // handle those well here.
9091   if (Subtarget->hasSSSE3()) {
9092     bool V1InUse = false;
9093     bool V2InUse = false;
9094
9095     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9096                                                 DAG, V1InUse, V2InUse);
9097
9098     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9099     // do so. This avoids using them to handle blends-with-zero which is
9100     // important as a single pshufb is significantly faster for that.
9101     if (V1InUse && V2InUse) {
9102       if (Subtarget->hasSSE41())
9103         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9104                                                       Mask, Subtarget, DAG))
9105           return Blend;
9106
9107       // We can use an unpack to do the blending rather than an or in some
9108       // cases. Even though the or may be (very minorly) more efficient, we
9109       // preference this lowering because there are common cases where part of
9110       // the complexity of the shuffles goes away when we do the final blend as
9111       // an unpack.
9112       // FIXME: It might be worth trying to detect if the unpack-feeding
9113       // shuffles will both be pshufb, in which case we shouldn't bother with
9114       // this.
9115       if (SDValue Unpack =
9116               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9117         return Unpack;
9118     }
9119
9120     return PSHUFB;
9121   }
9122
9123   // There are special ways we can lower some single-element blends.
9124   if (NumV2Elements == 1)
9125     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9126                                                          Mask, Subtarget, DAG))
9127       return V;
9128
9129   if (SDValue BitBlend =
9130           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9131     return BitBlend;
9132
9133   // Check whether a compaction lowering can be done. This handles shuffles
9134   // which take every Nth element for some even N. See the helper function for
9135   // details.
9136   //
9137   // We special case these as they can be particularly efficiently handled with
9138   // the PACKUSB instruction on x86 and they show up in common patterns of
9139   // rearranging bytes to truncate wide elements.
9140   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9141     // NumEvenDrops is the power of two stride of the elements. Another way of
9142     // thinking about it is that we need to drop the even elements this many
9143     // times to get the original input.
9144     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9145
9146     // First we need to zero all the dropped bytes.
9147     assert(NumEvenDrops <= 3 &&
9148            "No support for dropping even elements more than 3 times.");
9149     // We use the mask type to pick which bytes are preserved based on how many
9150     // elements are dropped.
9151     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9152     SDValue ByteClearMask = DAG.getBitcast(
9153         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9154     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9155     if (!IsSingleInput)
9156       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9157
9158     // Now pack things back together.
9159     V1 = DAG.getBitcast(MVT::v8i16, V1);
9160     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9161     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9162     for (int i = 1; i < NumEvenDrops; ++i) {
9163       Result = DAG.getBitcast(MVT::v8i16, Result);
9164       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9165     }
9166
9167     return Result;
9168   }
9169
9170   // Handle multi-input cases by blending single-input shuffles.
9171   if (NumV2Elements > 0)
9172     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9173                                                       Mask, DAG);
9174
9175   // The fallback path for single-input shuffles widens this into two v8i16
9176   // vectors with unpacks, shuffles those, and then pulls them back together
9177   // with a pack.
9178   SDValue V = V1;
9179
9180   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9181   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9182   for (int i = 0; i < 16; ++i)
9183     if (Mask[i] >= 0)
9184       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9185
9186   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9187
9188   SDValue VLoHalf, VHiHalf;
9189   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9190   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9191   // i16s.
9192   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9193                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9194       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9195                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9196     // Use a mask to drop the high bytes.
9197     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9198     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9199                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9200
9201     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9202     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9203
9204     // Squash the masks to point directly into VLoHalf.
9205     for (int &M : LoBlendMask)
9206       if (M >= 0)
9207         M /= 2;
9208     for (int &M : HiBlendMask)
9209       if (M >= 0)
9210         M /= 2;
9211   } else {
9212     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9213     // VHiHalf so that we can blend them as i16s.
9214     VLoHalf = DAG.getBitcast(
9215         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9216     VHiHalf = DAG.getBitcast(
9217         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9218   }
9219
9220   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9221   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9222
9223   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9224 }
9225
9226 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9227 ///
9228 /// This routine breaks down the specific type of 128-bit shuffle and
9229 /// dispatches to the lowering routines accordingly.
9230 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9231                                         MVT VT, const X86Subtarget *Subtarget,
9232                                         SelectionDAG &DAG) {
9233   switch (VT.SimpleTy) {
9234   case MVT::v2i64:
9235     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9236   case MVT::v2f64:
9237     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9238   case MVT::v4i32:
9239     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9240   case MVT::v4f32:
9241     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9242   case MVT::v8i16:
9243     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9244   case MVT::v16i8:
9245     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9246
9247   default:
9248     llvm_unreachable("Unimplemented!");
9249   }
9250 }
9251
9252 /// \brief Helper function to test whether a shuffle mask could be
9253 /// simplified by widening the elements being shuffled.
9254 ///
9255 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9256 /// leaves it in an unspecified state.
9257 ///
9258 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9259 /// shuffle masks. The latter have the special property of a '-2' representing
9260 /// a zero-ed lane of a vector.
9261 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9262                                     SmallVectorImpl<int> &WidenedMask) {
9263   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9264     // If both elements are undef, its trivial.
9265     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9266       WidenedMask.push_back(SM_SentinelUndef);
9267       continue;
9268     }
9269
9270     // Check for an undef mask and a mask value properly aligned to fit with
9271     // a pair of values. If we find such a case, use the non-undef mask's value.
9272     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9273       WidenedMask.push_back(Mask[i + 1] / 2);
9274       continue;
9275     }
9276     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9277       WidenedMask.push_back(Mask[i] / 2);
9278       continue;
9279     }
9280
9281     // When zeroing, we need to spread the zeroing across both lanes to widen.
9282     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9283       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9284           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9285         WidenedMask.push_back(SM_SentinelZero);
9286         continue;
9287       }
9288       return false;
9289     }
9290
9291     // Finally check if the two mask values are adjacent and aligned with
9292     // a pair.
9293     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9294       WidenedMask.push_back(Mask[i] / 2);
9295       continue;
9296     }
9297
9298     // Otherwise we can't safely widen the elements used in this shuffle.
9299     return false;
9300   }
9301   assert(WidenedMask.size() == Mask.size() / 2 &&
9302          "Incorrect size of mask after widening the elements!");
9303
9304   return true;
9305 }
9306
9307 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9308 ///
9309 /// This routine just extracts two subvectors, shuffles them independently, and
9310 /// then concatenates them back together. This should work effectively with all
9311 /// AVX vector shuffle types.
9312 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9313                                           SDValue V2, ArrayRef<int> Mask,
9314                                           SelectionDAG &DAG) {
9315   assert(VT.getSizeInBits() >= 256 &&
9316          "Only for 256-bit or wider vector shuffles!");
9317   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9318   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9319
9320   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9321   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9322
9323   int NumElements = VT.getVectorNumElements();
9324   int SplitNumElements = NumElements / 2;
9325   MVT ScalarVT = VT.getScalarType();
9326   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9327
9328   // Rather than splitting build-vectors, just build two narrower build
9329   // vectors. This helps shuffling with splats and zeros.
9330   auto SplitVector = [&](SDValue V) {
9331     while (V.getOpcode() == ISD::BITCAST)
9332       V = V->getOperand(0);
9333
9334     MVT OrigVT = V.getSimpleValueType();
9335     int OrigNumElements = OrigVT.getVectorNumElements();
9336     int OrigSplitNumElements = OrigNumElements / 2;
9337     MVT OrigScalarVT = OrigVT.getScalarType();
9338     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9339
9340     SDValue LoV, HiV;
9341
9342     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9343     if (!BV) {
9344       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9345                         DAG.getIntPtrConstant(0, DL));
9346       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9347                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9348     } else {
9349
9350       SmallVector<SDValue, 16> LoOps, HiOps;
9351       for (int i = 0; i < OrigSplitNumElements; ++i) {
9352         LoOps.push_back(BV->getOperand(i));
9353         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9354       }
9355       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9356       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9357     }
9358     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9359                           DAG.getBitcast(SplitVT, HiV));
9360   };
9361
9362   SDValue LoV1, HiV1, LoV2, HiV2;
9363   std::tie(LoV1, HiV1) = SplitVector(V1);
9364   std::tie(LoV2, HiV2) = SplitVector(V2);
9365
9366   // Now create two 4-way blends of these half-width vectors.
9367   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9368     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9369     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9370     for (int i = 0; i < SplitNumElements; ++i) {
9371       int M = HalfMask[i];
9372       if (M >= NumElements) {
9373         if (M >= NumElements + SplitNumElements)
9374           UseHiV2 = true;
9375         else
9376           UseLoV2 = true;
9377         V2BlendMask.push_back(M - NumElements);
9378         V1BlendMask.push_back(-1);
9379         BlendMask.push_back(SplitNumElements + i);
9380       } else if (M >= 0) {
9381         if (M >= SplitNumElements)
9382           UseHiV1 = true;
9383         else
9384           UseLoV1 = true;
9385         V2BlendMask.push_back(-1);
9386         V1BlendMask.push_back(M);
9387         BlendMask.push_back(i);
9388       } else {
9389         V2BlendMask.push_back(-1);
9390         V1BlendMask.push_back(-1);
9391         BlendMask.push_back(-1);
9392       }
9393     }
9394
9395     // Because the lowering happens after all combining takes place, we need to
9396     // manually combine these blend masks as much as possible so that we create
9397     // a minimal number of high-level vector shuffle nodes.
9398
9399     // First try just blending the halves of V1 or V2.
9400     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9401       return DAG.getUNDEF(SplitVT);
9402     if (!UseLoV2 && !UseHiV2)
9403       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9404     if (!UseLoV1 && !UseHiV1)
9405       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9406
9407     SDValue V1Blend, V2Blend;
9408     if (UseLoV1 && UseHiV1) {
9409       V1Blend =
9410         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9411     } else {
9412       // We only use half of V1 so map the usage down into the final blend mask.
9413       V1Blend = UseLoV1 ? LoV1 : HiV1;
9414       for (int i = 0; i < SplitNumElements; ++i)
9415         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9416           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9417     }
9418     if (UseLoV2 && UseHiV2) {
9419       V2Blend =
9420         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9421     } else {
9422       // We only use half of V2 so map the usage down into the final blend mask.
9423       V2Blend = UseLoV2 ? LoV2 : HiV2;
9424       for (int i = 0; i < SplitNumElements; ++i)
9425         if (BlendMask[i] >= SplitNumElements)
9426           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9427     }
9428     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9429   };
9430   SDValue Lo = HalfBlend(LoMask);
9431   SDValue Hi = HalfBlend(HiMask);
9432   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9433 }
9434
9435 /// \brief Either split a vector in halves or decompose the shuffles and the
9436 /// blend.
9437 ///
9438 /// This is provided as a good fallback for many lowerings of non-single-input
9439 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9440 /// between splitting the shuffle into 128-bit components and stitching those
9441 /// back together vs. extracting the single-input shuffles and blending those
9442 /// results.
9443 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9444                                                 SDValue V2, ArrayRef<int> Mask,
9445                                                 SelectionDAG &DAG) {
9446   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9447                                             "lower single-input shuffles as it "
9448                                             "could then recurse on itself.");
9449   int Size = Mask.size();
9450
9451   // If this can be modeled as a broadcast of two elements followed by a blend,
9452   // prefer that lowering. This is especially important because broadcasts can
9453   // often fold with memory operands.
9454   auto DoBothBroadcast = [&] {
9455     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9456     for (int M : Mask)
9457       if (M >= Size) {
9458         if (V2BroadcastIdx == -1)
9459           V2BroadcastIdx = M - Size;
9460         else if (M - Size != V2BroadcastIdx)
9461           return false;
9462       } else if (M >= 0) {
9463         if (V1BroadcastIdx == -1)
9464           V1BroadcastIdx = M;
9465         else if (M != V1BroadcastIdx)
9466           return false;
9467       }
9468     return true;
9469   };
9470   if (DoBothBroadcast())
9471     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9472                                                       DAG);
9473
9474   // If the inputs all stem from a single 128-bit lane of each input, then we
9475   // split them rather than blending because the split will decompose to
9476   // unusually few instructions.
9477   int LaneCount = VT.getSizeInBits() / 128;
9478   int LaneSize = Size / LaneCount;
9479   SmallBitVector LaneInputs[2];
9480   LaneInputs[0].resize(LaneCount, false);
9481   LaneInputs[1].resize(LaneCount, false);
9482   for (int i = 0; i < Size; ++i)
9483     if (Mask[i] >= 0)
9484       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9485   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9486     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9487
9488   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9489   // that the decomposed single-input shuffles don't end up here.
9490   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9491 }
9492
9493 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9494 /// a permutation and blend of those lanes.
9495 ///
9496 /// This essentially blends the out-of-lane inputs to each lane into the lane
9497 /// from a permuted copy of the vector. This lowering strategy results in four
9498 /// instructions in the worst case for a single-input cross lane shuffle which
9499 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9500 /// of. Special cases for each particular shuffle pattern should be handled
9501 /// prior to trying this lowering.
9502 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9503                                                        SDValue V1, SDValue V2,
9504                                                        ArrayRef<int> Mask,
9505                                                        SelectionDAG &DAG) {
9506   // FIXME: This should probably be generalized for 512-bit vectors as well.
9507   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9508   int LaneSize = Mask.size() / 2;
9509
9510   // If there are only inputs from one 128-bit lane, splitting will in fact be
9511   // less expensive. The flags track whether the given lane contains an element
9512   // that crosses to another lane.
9513   bool LaneCrossing[2] = {false, false};
9514   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9515     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9516       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9517   if (!LaneCrossing[0] || !LaneCrossing[1])
9518     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9519
9520   if (isSingleInputShuffleMask(Mask)) {
9521     SmallVector<int, 32> FlippedBlendMask;
9522     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9523       FlippedBlendMask.push_back(
9524           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9525                                   ? Mask[i]
9526                                   : Mask[i] % LaneSize +
9527                                         (i / LaneSize) * LaneSize + Size));
9528
9529     // Flip the vector, and blend the results which should now be in-lane. The
9530     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9531     // 5 for the high source. The value 3 selects the high half of source 2 and
9532     // the value 2 selects the low half of source 2. We only use source 2 to
9533     // allow folding it into a memory operand.
9534     unsigned PERMMask = 3 | 2 << 4;
9535     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9536                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9537     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9538   }
9539
9540   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9541   // will be handled by the above logic and a blend of the results, much like
9542   // other patterns in AVX.
9543   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9544 }
9545
9546 /// \brief Handle lowering 2-lane 128-bit shuffles.
9547 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9548                                         SDValue V2, ArrayRef<int> Mask,
9549                                         const X86Subtarget *Subtarget,
9550                                         SelectionDAG &DAG) {
9551   // TODO: If minimizing size and one of the inputs is a zero vector and the
9552   // the zero vector has only one use, we could use a VPERM2X128 to save the
9553   // instruction bytes needed to explicitly generate the zero vector.
9554
9555   // Blends are faster and handle all the non-lane-crossing cases.
9556   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9557                                                 Subtarget, DAG))
9558     return Blend;
9559
9560   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9561   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9562
9563   // If either input operand is a zero vector, use VPERM2X128 because its mask
9564   // allows us to replace the zero input with an implicit zero.
9565   if (!IsV1Zero && !IsV2Zero) {
9566     // Check for patterns which can be matched with a single insert of a 128-bit
9567     // subvector.
9568     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9569     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9570       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9571                                    VT.getVectorNumElements() / 2);
9572       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9573                                 DAG.getIntPtrConstant(0, DL));
9574       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9575                                 OnlyUsesV1 ? V1 : V2,
9576                                 DAG.getIntPtrConstant(0, DL));
9577       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9578     }
9579   }
9580
9581   // Otherwise form a 128-bit permutation. After accounting for undefs,
9582   // convert the 64-bit shuffle mask selection values into 128-bit
9583   // selection bits by dividing the indexes by 2 and shifting into positions
9584   // defined by a vperm2*128 instruction's immediate control byte.
9585
9586   // The immediate permute control byte looks like this:
9587   //    [1:0] - select 128 bits from sources for low half of destination
9588   //    [2]   - ignore
9589   //    [3]   - zero low half of destination
9590   //    [5:4] - select 128 bits from sources for high half of destination
9591   //    [6]   - ignore
9592   //    [7]   - zero high half of destination
9593
9594   int MaskLO = Mask[0];
9595   if (MaskLO == SM_SentinelUndef)
9596     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9597
9598   int MaskHI = Mask[2];
9599   if (MaskHI == SM_SentinelUndef)
9600     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9601
9602   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9603
9604   // If either input is a zero vector, replace it with an undef input.
9605   // Shuffle mask values <  4 are selecting elements of V1.
9606   // Shuffle mask values >= 4 are selecting elements of V2.
9607   // Adjust each half of the permute mask by clearing the half that was
9608   // selecting the zero vector and setting the zero mask bit.
9609   if (IsV1Zero) {
9610     V1 = DAG.getUNDEF(VT);
9611     if (MaskLO < 4)
9612       PermMask = (PermMask & 0xf0) | 0x08;
9613     if (MaskHI < 4)
9614       PermMask = (PermMask & 0x0f) | 0x80;
9615   }
9616   if (IsV2Zero) {
9617     V2 = DAG.getUNDEF(VT);
9618     if (MaskLO >= 4)
9619       PermMask = (PermMask & 0xf0) | 0x08;
9620     if (MaskHI >= 4)
9621       PermMask = (PermMask & 0x0f) | 0x80;
9622   }
9623
9624   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9625                      DAG.getConstant(PermMask, DL, MVT::i8));
9626 }
9627
9628 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9629 /// shuffling each lane.
9630 ///
9631 /// This will only succeed when the result of fixing the 128-bit lanes results
9632 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9633 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9634 /// the lane crosses early and then use simpler shuffles within each lane.
9635 ///
9636 /// FIXME: It might be worthwhile at some point to support this without
9637 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9638 /// in x86 only floating point has interesting non-repeating shuffles, and even
9639 /// those are still *marginally* more expensive.
9640 static SDValue lowerVectorShuffleByMerging128BitLanes(
9641     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9642     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9643   assert(!isSingleInputShuffleMask(Mask) &&
9644          "This is only useful with multiple inputs.");
9645
9646   int Size = Mask.size();
9647   int LaneSize = 128 / VT.getScalarSizeInBits();
9648   int NumLanes = Size / LaneSize;
9649   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9650
9651   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9652   // check whether the in-128-bit lane shuffles share a repeating pattern.
9653   SmallVector<int, 4> Lanes;
9654   Lanes.resize(NumLanes, -1);
9655   SmallVector<int, 4> InLaneMask;
9656   InLaneMask.resize(LaneSize, -1);
9657   for (int i = 0; i < Size; ++i) {
9658     if (Mask[i] < 0)
9659       continue;
9660
9661     int j = i / LaneSize;
9662
9663     if (Lanes[j] < 0) {
9664       // First entry we've seen for this lane.
9665       Lanes[j] = Mask[i] / LaneSize;
9666     } else if (Lanes[j] != Mask[i] / LaneSize) {
9667       // This doesn't match the lane selected previously!
9668       return SDValue();
9669     }
9670
9671     // Check that within each lane we have a consistent shuffle mask.
9672     int k = i % LaneSize;
9673     if (InLaneMask[k] < 0) {
9674       InLaneMask[k] = Mask[i] % LaneSize;
9675     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9676       // This doesn't fit a repeating in-lane mask.
9677       return SDValue();
9678     }
9679   }
9680
9681   // First shuffle the lanes into place.
9682   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9683                                 VT.getSizeInBits() / 64);
9684   SmallVector<int, 8> LaneMask;
9685   LaneMask.resize(NumLanes * 2, -1);
9686   for (int i = 0; i < NumLanes; ++i)
9687     if (Lanes[i] >= 0) {
9688       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9689       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9690     }
9691
9692   V1 = DAG.getBitcast(LaneVT, V1);
9693   V2 = DAG.getBitcast(LaneVT, V2);
9694   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9695
9696   // Cast it back to the type we actually want.
9697   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9698
9699   // Now do a simple shuffle that isn't lane crossing.
9700   SmallVector<int, 8> NewMask;
9701   NewMask.resize(Size, -1);
9702   for (int i = 0; i < Size; ++i)
9703     if (Mask[i] >= 0)
9704       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9705   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9706          "Must not introduce lane crosses at this point!");
9707
9708   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9709 }
9710
9711 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9712 /// given mask.
9713 ///
9714 /// This returns true if the elements from a particular input are already in the
9715 /// slot required by the given mask and require no permutation.
9716 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9717   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9718   int Size = Mask.size();
9719   for (int i = 0; i < Size; ++i)
9720     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9721       return false;
9722
9723   return true;
9724 }
9725
9726 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9727                                             ArrayRef<int> Mask, SDValue V1,
9728                                             SDValue V2, SelectionDAG &DAG) {
9729
9730   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9731   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9732   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9733   int NumElts = VT.getVectorNumElements();
9734   bool ShufpdMask = true;
9735   bool CommutableMask = true;
9736   unsigned Immediate = 0;
9737   for (int i = 0; i < NumElts; ++i) {
9738     if (Mask[i] < 0)
9739       continue;
9740     int Val = (i & 6) + NumElts * (i & 1);
9741     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9742     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9743       ShufpdMask = false;
9744     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9745       CommutableMask = false;
9746     Immediate |= (Mask[i] % 2) << i;
9747   }
9748   if (ShufpdMask)
9749     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9750                        DAG.getConstant(Immediate, DL, MVT::i8));
9751   if (CommutableMask)
9752     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9753                        DAG.getConstant(Immediate, DL, MVT::i8));
9754   return SDValue();
9755 }
9756
9757 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9758 ///
9759 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9760 /// isn't available.
9761 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9762                                        const X86Subtarget *Subtarget,
9763                                        SelectionDAG &DAG) {
9764   SDLoc DL(Op);
9765   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9766   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9767   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9768   ArrayRef<int> Mask = SVOp->getMask();
9769   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9770
9771   SmallVector<int, 4> WidenedMask;
9772   if (canWidenShuffleElements(Mask, WidenedMask))
9773     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9774                                     DAG);
9775
9776   if (isSingleInputShuffleMask(Mask)) {
9777     // Check for being able to broadcast a single element.
9778     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9779                                                           Mask, Subtarget, DAG))
9780       return Broadcast;
9781
9782     // Use low duplicate instructions for masks that match their pattern.
9783     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9784       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9785
9786     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9787       // Non-half-crossing single input shuffles can be lowerid with an
9788       // interleaved permutation.
9789       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9790                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9791       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9792                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9793     }
9794
9795     // With AVX2 we have direct support for this permutation.
9796     if (Subtarget->hasAVX2())
9797       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9798                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9799
9800     // Otherwise, fall back.
9801     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9802                                                    DAG);
9803   }
9804
9805   // X86 has dedicated unpack instructions that can handle specific blend
9806   // operations: UNPCKH and UNPCKL.
9807   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9808     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9809   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9810     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9811   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9812     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9813   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9814     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9815
9816   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9817                                                 Subtarget, DAG))
9818     return Blend;
9819
9820   // Check if the blend happens to exactly fit that of SHUFPD.
9821   if (SDValue Op =
9822       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9823     return Op;
9824
9825   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9826   // shuffle. However, if we have AVX2 and either inputs are already in place,
9827   // we will be able to shuffle even across lanes the other input in a single
9828   // instruction so skip this pattern.
9829   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9830                                  isShuffleMaskInputInPlace(1, Mask))))
9831     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9832             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9833       return Result;
9834
9835   // If we have AVX2 then we always want to lower with a blend because an v4 we
9836   // can fully permute the elements.
9837   if (Subtarget->hasAVX2())
9838     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9839                                                       Mask, DAG);
9840
9841   // Otherwise fall back on generic lowering.
9842   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9843 }
9844
9845 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9846 ///
9847 /// This routine is only called when we have AVX2 and thus a reasonable
9848 /// instruction set for v4i64 shuffling..
9849 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9850                                        const X86Subtarget *Subtarget,
9851                                        SelectionDAG &DAG) {
9852   SDLoc DL(Op);
9853   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9854   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9855   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9856   ArrayRef<int> Mask = SVOp->getMask();
9857   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9858   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9859
9860   SmallVector<int, 4> WidenedMask;
9861   if (canWidenShuffleElements(Mask, WidenedMask))
9862     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9863                                     DAG);
9864
9865   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9866                                                 Subtarget, DAG))
9867     return Blend;
9868
9869   // Check for being able to broadcast a single element.
9870   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9871                                                         Mask, Subtarget, DAG))
9872     return Broadcast;
9873
9874   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9875   // use lower latency instructions that will operate on both 128-bit lanes.
9876   SmallVector<int, 2> RepeatedMask;
9877   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9878     if (isSingleInputShuffleMask(Mask)) {
9879       int PSHUFDMask[] = {-1, -1, -1, -1};
9880       for (int i = 0; i < 2; ++i)
9881         if (RepeatedMask[i] >= 0) {
9882           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9883           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9884         }
9885       return DAG.getBitcast(
9886           MVT::v4i64,
9887           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9888                       DAG.getBitcast(MVT::v8i32, V1),
9889                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9890     }
9891   }
9892
9893   // AVX2 provides a direct instruction for permuting a single input across
9894   // lanes.
9895   if (isSingleInputShuffleMask(Mask))
9896     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9897                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9898
9899   // Try to use shift instructions.
9900   if (SDValue Shift =
9901           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9902     return Shift;
9903
9904   // Use dedicated unpack instructions for masks that match their pattern.
9905   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9906     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9907   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9908     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9909   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9910     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9911   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9912     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9913
9914   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9915   // shuffle. However, if we have AVX2 and either inputs are already in place,
9916   // we will be able to shuffle even across lanes the other input in a single
9917   // instruction so skip this pattern.
9918   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9919                                  isShuffleMaskInputInPlace(1, Mask))))
9920     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9921             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9922       return Result;
9923
9924   // Otherwise fall back on generic blend lowering.
9925   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9926                                                     Mask, DAG);
9927 }
9928
9929 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9930 ///
9931 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9932 /// isn't available.
9933 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9934                                        const X86Subtarget *Subtarget,
9935                                        SelectionDAG &DAG) {
9936   SDLoc DL(Op);
9937   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9938   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9939   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9940   ArrayRef<int> Mask = SVOp->getMask();
9941   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9942
9943   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9944                                                 Subtarget, DAG))
9945     return Blend;
9946
9947   // Check for being able to broadcast a single element.
9948   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9949                                                         Mask, Subtarget, DAG))
9950     return Broadcast;
9951
9952   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9953   // options to efficiently lower the shuffle.
9954   SmallVector<int, 4> RepeatedMask;
9955   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9956     assert(RepeatedMask.size() == 4 &&
9957            "Repeated masks must be half the mask width!");
9958
9959     // Use even/odd duplicate instructions for masks that match their pattern.
9960     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9961       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9962     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9963       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9964
9965     if (isSingleInputShuffleMask(Mask))
9966       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9967                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9968
9969     // Use dedicated unpack instructions for masks that match their pattern.
9970     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9971       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9972     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9973       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9974     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9975       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9976     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9977       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9978
9979     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9980     // have already handled any direct blends. We also need to squash the
9981     // repeated mask into a simulated v4f32 mask.
9982     for (int i = 0; i < 4; ++i)
9983       if (RepeatedMask[i] >= 8)
9984         RepeatedMask[i] -= 4;
9985     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9986   }
9987
9988   // If we have a single input shuffle with different shuffle patterns in the
9989   // two 128-bit lanes use the variable mask to VPERMILPS.
9990   if (isSingleInputShuffleMask(Mask)) {
9991     SDValue VPermMask[8];
9992     for (int i = 0; i < 8; ++i)
9993       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9994                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9995     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9996       return DAG.getNode(
9997           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9998           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9999
10000     if (Subtarget->hasAVX2())
10001       return DAG.getNode(
10002           X86ISD::VPERMV, DL, MVT::v8f32,
10003           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10004                                                  MVT::v8i32, VPermMask)),
10005           V1);
10006
10007     // Otherwise, fall back.
10008     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10009                                                    DAG);
10010   }
10011
10012   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10013   // shuffle.
10014   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10015           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10016     return Result;
10017
10018   // If we have AVX2 then we always want to lower with a blend because at v8 we
10019   // can fully permute the elements.
10020   if (Subtarget->hasAVX2())
10021     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10022                                                       Mask, DAG);
10023
10024   // Otherwise fall back on generic lowering.
10025   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10026 }
10027
10028 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10029 ///
10030 /// This routine is only called when we have AVX2 and thus a reasonable
10031 /// instruction set for v8i32 shuffling..
10032 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10033                                        const X86Subtarget *Subtarget,
10034                                        SelectionDAG &DAG) {
10035   SDLoc DL(Op);
10036   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10037   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10038   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10039   ArrayRef<int> Mask = SVOp->getMask();
10040   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10041   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10042
10043   // Whenever we can lower this as a zext, that instruction is strictly faster
10044   // than any alternative. It also allows us to fold memory operands into the
10045   // shuffle in many cases.
10046   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10047                                                          Mask, Subtarget, DAG))
10048     return ZExt;
10049
10050   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10051                                                 Subtarget, DAG))
10052     return Blend;
10053
10054   // Check for being able to broadcast a single element.
10055   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10056                                                         Mask, Subtarget, DAG))
10057     return Broadcast;
10058
10059   // If the shuffle mask is repeated in each 128-bit lane we can use more
10060   // efficient instructions that mirror the shuffles across the two 128-bit
10061   // lanes.
10062   SmallVector<int, 4> RepeatedMask;
10063   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10064     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10065     if (isSingleInputShuffleMask(Mask))
10066       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10067                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10068
10069     // Use dedicated unpack instructions for masks that match their pattern.
10070     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10071       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10072     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10073       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10074     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10075       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10076     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10077       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10078   }
10079
10080   // Try to use shift instructions.
10081   if (SDValue Shift =
10082           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10083     return Shift;
10084
10085   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10086           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10087     return Rotate;
10088
10089   // If the shuffle patterns aren't repeated but it is a single input, directly
10090   // generate a cross-lane VPERMD instruction.
10091   if (isSingleInputShuffleMask(Mask)) {
10092     SDValue VPermMask[8];
10093     for (int i = 0; i < 8; ++i)
10094       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10095                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10096     return DAG.getNode(
10097         X86ISD::VPERMV, DL, MVT::v8i32,
10098         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10099   }
10100
10101   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10102   // shuffle.
10103   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10104           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10105     return Result;
10106
10107   // Otherwise fall back on generic blend lowering.
10108   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10109                                                     Mask, DAG);
10110 }
10111
10112 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10113 ///
10114 /// This routine is only called when we have AVX2 and thus a reasonable
10115 /// instruction set for v16i16 shuffling..
10116 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10117                                         const X86Subtarget *Subtarget,
10118                                         SelectionDAG &DAG) {
10119   SDLoc DL(Op);
10120   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10121   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10122   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10123   ArrayRef<int> Mask = SVOp->getMask();
10124   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10125   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10126
10127   // Whenever we can lower this as a zext, that instruction is strictly faster
10128   // than any alternative. It also allows us to fold memory operands into the
10129   // shuffle in many cases.
10130   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10131                                                          Mask, Subtarget, DAG))
10132     return ZExt;
10133
10134   // Check for being able to broadcast a single element.
10135   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10136                                                         Mask, Subtarget, DAG))
10137     return Broadcast;
10138
10139   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10140                                                 Subtarget, DAG))
10141     return Blend;
10142
10143   // Use dedicated unpack instructions for masks that match their pattern.
10144   if (isShuffleEquivalent(V1, V2, Mask,
10145                           {// First 128-bit lane:
10146                            0, 16, 1, 17, 2, 18, 3, 19,
10147                            // Second 128-bit lane:
10148                            8, 24, 9, 25, 10, 26, 11, 27}))
10149     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10150   if (isShuffleEquivalent(V1, V2, Mask,
10151                           {// First 128-bit lane:
10152                            4, 20, 5, 21, 6, 22, 7, 23,
10153                            // Second 128-bit lane:
10154                            12, 28, 13, 29, 14, 30, 15, 31}))
10155     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10156
10157   // Try to use shift instructions.
10158   if (SDValue Shift =
10159           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10160     return Shift;
10161
10162   // Try to use byte rotation instructions.
10163   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10164           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10165     return Rotate;
10166
10167   if (isSingleInputShuffleMask(Mask)) {
10168     // There are no generalized cross-lane shuffle operations available on i16
10169     // element types.
10170     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10171       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10172                                                      Mask, DAG);
10173
10174     SmallVector<int, 8> RepeatedMask;
10175     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10176       // As this is a single-input shuffle, the repeated mask should be
10177       // a strictly valid v8i16 mask that we can pass through to the v8i16
10178       // lowering to handle even the v16 case.
10179       return lowerV8I16GeneralSingleInputVectorShuffle(
10180           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10181     }
10182
10183     SDValue PSHUFBMask[32];
10184     for (int i = 0; i < 16; ++i) {
10185       if (Mask[i] == -1) {
10186         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10187         continue;
10188       }
10189
10190       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10191       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10192       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10193       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10194     }
10195     return DAG.getBitcast(MVT::v16i16,
10196                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10197                                       DAG.getBitcast(MVT::v32i8, V1),
10198                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10199                                                   MVT::v32i8, PSHUFBMask)));
10200   }
10201
10202   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10203   // shuffle.
10204   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10205           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10206     return Result;
10207
10208   // Otherwise fall back on generic lowering.
10209   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10210 }
10211
10212 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10213 ///
10214 /// This routine is only called when we have AVX2 and thus a reasonable
10215 /// instruction set for v32i8 shuffling..
10216 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10217                                        const X86Subtarget *Subtarget,
10218                                        SelectionDAG &DAG) {
10219   SDLoc DL(Op);
10220   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10221   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10222   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10223   ArrayRef<int> Mask = SVOp->getMask();
10224   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10225   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10226
10227   // Whenever we can lower this as a zext, that instruction is strictly faster
10228   // than any alternative. It also allows us to fold memory operands into the
10229   // shuffle in many cases.
10230   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10231                                                          Mask, Subtarget, DAG))
10232     return ZExt;
10233
10234   // Check for being able to broadcast a single element.
10235   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10236                                                         Mask, Subtarget, DAG))
10237     return Broadcast;
10238
10239   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10240                                                 Subtarget, DAG))
10241     return Blend;
10242
10243   // Use dedicated unpack instructions for masks that match their pattern.
10244   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10245   // 256-bit lanes.
10246   if (isShuffleEquivalent(
10247           V1, V2, Mask,
10248           {// First 128-bit lane:
10249            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10250            // Second 128-bit lane:
10251            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10252     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10253   if (isShuffleEquivalent(
10254           V1, V2, Mask,
10255           {// First 128-bit lane:
10256            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10257            // Second 128-bit lane:
10258            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10259     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10260
10261   // Try to use shift instructions.
10262   if (SDValue Shift =
10263           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10264     return Shift;
10265
10266   // Try to use byte rotation instructions.
10267   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10268           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10269     return Rotate;
10270
10271   if (isSingleInputShuffleMask(Mask)) {
10272     // There are no generalized cross-lane shuffle operations available on i8
10273     // element types.
10274     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10275       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10276                                                      Mask, DAG);
10277
10278     SDValue PSHUFBMask[32];
10279     for (int i = 0; i < 32; ++i)
10280       PSHUFBMask[i] =
10281           Mask[i] < 0
10282               ? DAG.getUNDEF(MVT::i8)
10283               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10284                                 MVT::i8);
10285
10286     return DAG.getNode(
10287         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10288         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10289   }
10290
10291   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10292   // shuffle.
10293   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10294           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10295     return Result;
10296
10297   // Otherwise fall back on generic lowering.
10298   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10299 }
10300
10301 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10302 ///
10303 /// This routine either breaks down the specific type of a 256-bit x86 vector
10304 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10305 /// together based on the available instructions.
10306 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10307                                         MVT VT, const X86Subtarget *Subtarget,
10308                                         SelectionDAG &DAG) {
10309   SDLoc DL(Op);
10310   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10311   ArrayRef<int> Mask = SVOp->getMask();
10312
10313   // If we have a single input to the zero element, insert that into V1 if we
10314   // can do so cheaply.
10315   int NumElts = VT.getVectorNumElements();
10316   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10317     return M >= NumElts;
10318   });
10319
10320   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10321     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10322                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10323       return Insertion;
10324
10325   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10326   // check for those subtargets here and avoid much of the subtarget querying in
10327   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10328   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10329   // floating point types there eventually, just immediately cast everything to
10330   // a float and operate entirely in that domain.
10331   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10332     int ElementBits = VT.getScalarSizeInBits();
10333     if (ElementBits < 32)
10334       // No floating point type available, decompose into 128-bit vectors.
10335       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10336
10337     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10338                                 VT.getVectorNumElements());
10339     V1 = DAG.getBitcast(FpVT, V1);
10340     V2 = DAG.getBitcast(FpVT, V2);
10341     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10342   }
10343
10344   switch (VT.SimpleTy) {
10345   case MVT::v4f64:
10346     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10347   case MVT::v4i64:
10348     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10349   case MVT::v8f32:
10350     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10351   case MVT::v8i32:
10352     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10353   case MVT::v16i16:
10354     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10355   case MVT::v32i8:
10356     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10357
10358   default:
10359     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10360   }
10361 }
10362
10363 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10364 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10365                                        const X86Subtarget *Subtarget,
10366                                        SelectionDAG &DAG) {
10367   SDLoc DL(Op);
10368   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10369   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10370   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10371   ArrayRef<int> Mask = SVOp->getMask();
10372   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10373
10374   // X86 has dedicated unpack instructions that can handle specific blend
10375   // operations: UNPCKH and UNPCKL.
10376   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10377     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10378   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10379     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10380
10381   // FIXME: Implement direct support for this type!
10382   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10383 }
10384
10385 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10386 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10387                                        const X86Subtarget *Subtarget,
10388                                        SelectionDAG &DAG) {
10389   SDLoc DL(Op);
10390   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10391   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10392   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10393   ArrayRef<int> Mask = SVOp->getMask();
10394   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10395
10396   // Use dedicated unpack instructions for masks that match their pattern.
10397   if (isShuffleEquivalent(V1, V2, Mask,
10398                           {// First 128-bit lane.
10399                            0, 16, 1, 17, 4, 20, 5, 21,
10400                            // Second 128-bit lane.
10401                            8, 24, 9, 25, 12, 28, 13, 29}))
10402     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10403   if (isShuffleEquivalent(V1, V2, Mask,
10404                           {// First 128-bit lane.
10405                            2, 18, 3, 19, 6, 22, 7, 23,
10406                            // Second 128-bit lane.
10407                            10, 26, 11, 27, 14, 30, 15, 31}))
10408     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10409
10410   // FIXME: Implement direct support for this type!
10411   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10412 }
10413
10414 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10415 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10416                                        const X86Subtarget *Subtarget,
10417                                        SelectionDAG &DAG) {
10418   SDLoc DL(Op);
10419   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10420   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10421   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10422   ArrayRef<int> Mask = SVOp->getMask();
10423   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10424
10425   // X86 has dedicated unpack instructions that can handle specific blend
10426   // operations: UNPCKH and UNPCKL.
10427   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10428     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10429   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10430     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10431
10432   // FIXME: Implement direct support for this type!
10433   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10434 }
10435
10436 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10437 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10438                                        const X86Subtarget *Subtarget,
10439                                        SelectionDAG &DAG) {
10440   SDLoc DL(Op);
10441   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10442   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10443   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10444   ArrayRef<int> Mask = SVOp->getMask();
10445   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10446
10447   // Use dedicated unpack instructions for masks that match their pattern.
10448   if (isShuffleEquivalent(V1, V2, Mask,
10449                           {// First 128-bit lane.
10450                            0, 16, 1, 17, 4, 20, 5, 21,
10451                            // Second 128-bit lane.
10452                            8, 24, 9, 25, 12, 28, 13, 29}))
10453     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10454   if (isShuffleEquivalent(V1, V2, Mask,
10455                           {// First 128-bit lane.
10456                            2, 18, 3, 19, 6, 22, 7, 23,
10457                            // Second 128-bit lane.
10458                            10, 26, 11, 27, 14, 30, 15, 31}))
10459     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10460
10461   // FIXME: Implement direct support for this type!
10462   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10463 }
10464
10465 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10466 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10467                                         const X86Subtarget *Subtarget,
10468                                         SelectionDAG &DAG) {
10469   SDLoc DL(Op);
10470   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10471   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10472   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10473   ArrayRef<int> Mask = SVOp->getMask();
10474   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10475   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10476
10477   // FIXME: Implement direct support for this type!
10478   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10479 }
10480
10481 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10482 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10483                                        const X86Subtarget *Subtarget,
10484                                        SelectionDAG &DAG) {
10485   SDLoc DL(Op);
10486   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10487   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10488   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10489   ArrayRef<int> Mask = SVOp->getMask();
10490   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10491   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10492
10493   // FIXME: Implement direct support for this type!
10494   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10495 }
10496
10497 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10498 ///
10499 /// This routine either breaks down the specific type of a 512-bit x86 vector
10500 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10501 /// together based on the available instructions.
10502 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10503                                         MVT VT, const X86Subtarget *Subtarget,
10504                                         SelectionDAG &DAG) {
10505   SDLoc DL(Op);
10506   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10507   ArrayRef<int> Mask = SVOp->getMask();
10508   assert(Subtarget->hasAVX512() &&
10509          "Cannot lower 512-bit vectors w/ basic ISA!");
10510
10511   // Check for being able to broadcast a single element.
10512   if (SDValue Broadcast =
10513           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10514     return Broadcast;
10515
10516   // Dispatch to each element type for lowering. If we don't have supprot for
10517   // specific element type shuffles at 512 bits, immediately split them and
10518   // lower them. Each lowering routine of a given type is allowed to assume that
10519   // the requisite ISA extensions for that element type are available.
10520   switch (VT.SimpleTy) {
10521   case MVT::v8f64:
10522     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10523   case MVT::v16f32:
10524     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10525   case MVT::v8i64:
10526     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10527   case MVT::v16i32:
10528     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10529   case MVT::v32i16:
10530     if (Subtarget->hasBWI())
10531       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10532     break;
10533   case MVT::v64i8:
10534     if (Subtarget->hasBWI())
10535       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10536     break;
10537
10538   default:
10539     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10540   }
10541
10542   // Otherwise fall back on splitting.
10543   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10544 }
10545
10546 /// \brief Top-level lowering for x86 vector shuffles.
10547 ///
10548 /// This handles decomposition, canonicalization, and lowering of all x86
10549 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10550 /// above in helper routines. The canonicalization attempts to widen shuffles
10551 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10552 /// s.t. only one of the two inputs needs to be tested, etc.
10553 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10554                                   SelectionDAG &DAG) {
10555   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10556   ArrayRef<int> Mask = SVOp->getMask();
10557   SDValue V1 = Op.getOperand(0);
10558   SDValue V2 = Op.getOperand(1);
10559   MVT VT = Op.getSimpleValueType();
10560   int NumElements = VT.getVectorNumElements();
10561   SDLoc dl(Op);
10562
10563   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10564
10565   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10566   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10567   if (V1IsUndef && V2IsUndef)
10568     return DAG.getUNDEF(VT);
10569
10570   // When we create a shuffle node we put the UNDEF node to second operand,
10571   // but in some cases the first operand may be transformed to UNDEF.
10572   // In this case we should just commute the node.
10573   if (V1IsUndef)
10574     return DAG.getCommutedVectorShuffle(*SVOp);
10575
10576   // Check for non-undef masks pointing at an undef vector and make the masks
10577   // undef as well. This makes it easier to match the shuffle based solely on
10578   // the mask.
10579   if (V2IsUndef)
10580     for (int M : Mask)
10581       if (M >= NumElements) {
10582         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10583         for (int &M : NewMask)
10584           if (M >= NumElements)
10585             M = -1;
10586         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10587       }
10588
10589   // We actually see shuffles that are entirely re-arrangements of a set of
10590   // zero inputs. This mostly happens while decomposing complex shuffles into
10591   // simple ones. Directly lower these as a buildvector of zeros.
10592   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10593   if (Zeroable.all())
10594     return getZeroVector(VT, Subtarget, DAG, dl);
10595
10596   // Try to collapse shuffles into using a vector type with fewer elements but
10597   // wider element types. We cap this to not form integers or floating point
10598   // elements wider than 64 bits, but it might be interesting to form i128
10599   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10600   SmallVector<int, 16> WidenedMask;
10601   if (VT.getScalarSizeInBits() < 64 &&
10602       canWidenShuffleElements(Mask, WidenedMask)) {
10603     MVT NewEltVT = VT.isFloatingPoint()
10604                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10605                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10606     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10607     // Make sure that the new vector type is legal. For example, v2f64 isn't
10608     // legal on SSE1.
10609     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10610       V1 = DAG.getBitcast(NewVT, V1);
10611       V2 = DAG.getBitcast(NewVT, V2);
10612       return DAG.getBitcast(
10613           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10614     }
10615   }
10616
10617   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10618   for (int M : SVOp->getMask())
10619     if (M < 0)
10620       ++NumUndefElements;
10621     else if (M < NumElements)
10622       ++NumV1Elements;
10623     else
10624       ++NumV2Elements;
10625
10626   // Commute the shuffle as needed such that more elements come from V1 than
10627   // V2. This allows us to match the shuffle pattern strictly on how many
10628   // elements come from V1 without handling the symmetric cases.
10629   if (NumV2Elements > NumV1Elements)
10630     return DAG.getCommutedVectorShuffle(*SVOp);
10631
10632   // When the number of V1 and V2 elements are the same, try to minimize the
10633   // number of uses of V2 in the low half of the vector. When that is tied,
10634   // ensure that the sum of indices for V1 is equal to or lower than the sum
10635   // indices for V2. When those are equal, try to ensure that the number of odd
10636   // indices for V1 is lower than the number of odd indices for V2.
10637   if (NumV1Elements == NumV2Elements) {
10638     int LowV1Elements = 0, LowV2Elements = 0;
10639     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10640       if (M >= NumElements)
10641         ++LowV2Elements;
10642       else if (M >= 0)
10643         ++LowV1Elements;
10644     if (LowV2Elements > LowV1Elements) {
10645       return DAG.getCommutedVectorShuffle(*SVOp);
10646     } else if (LowV2Elements == LowV1Elements) {
10647       int SumV1Indices = 0, SumV2Indices = 0;
10648       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10649         if (SVOp->getMask()[i] >= NumElements)
10650           SumV2Indices += i;
10651         else if (SVOp->getMask()[i] >= 0)
10652           SumV1Indices += i;
10653       if (SumV2Indices < SumV1Indices) {
10654         return DAG.getCommutedVectorShuffle(*SVOp);
10655       } else if (SumV2Indices == SumV1Indices) {
10656         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10657         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10658           if (SVOp->getMask()[i] >= NumElements)
10659             NumV2OddIndices += i % 2;
10660           else if (SVOp->getMask()[i] >= 0)
10661             NumV1OddIndices += i % 2;
10662         if (NumV2OddIndices < NumV1OddIndices)
10663           return DAG.getCommutedVectorShuffle(*SVOp);
10664       }
10665     }
10666   }
10667
10668   // For each vector width, delegate to a specialized lowering routine.
10669   if (VT.getSizeInBits() == 128)
10670     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10671
10672   if (VT.getSizeInBits() == 256)
10673     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10674
10675   // Force AVX-512 vectors to be scalarized for now.
10676   // FIXME: Implement AVX-512 support!
10677   if (VT.getSizeInBits() == 512)
10678     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10679
10680   llvm_unreachable("Unimplemented!");
10681 }
10682
10683 // This function assumes its argument is a BUILD_VECTOR of constants or
10684 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10685 // true.
10686 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10687                                     unsigned &MaskValue) {
10688   MaskValue = 0;
10689   unsigned NumElems = BuildVector->getNumOperands();
10690   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10691   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10692   unsigned NumElemsInLane = NumElems / NumLanes;
10693
10694   // Blend for v16i16 should be symetric for the both lanes.
10695   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10696     SDValue EltCond = BuildVector->getOperand(i);
10697     SDValue SndLaneEltCond =
10698         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10699
10700     int Lane1Cond = -1, Lane2Cond = -1;
10701     if (isa<ConstantSDNode>(EltCond))
10702       Lane1Cond = !isZero(EltCond);
10703     if (isa<ConstantSDNode>(SndLaneEltCond))
10704       Lane2Cond = !isZero(SndLaneEltCond);
10705
10706     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10707       // Lane1Cond != 0, means we want the first argument.
10708       // Lane1Cond == 0, means we want the second argument.
10709       // The encoding of this argument is 0 for the first argument, 1
10710       // for the second. Therefore, invert the condition.
10711       MaskValue |= !Lane1Cond << i;
10712     else if (Lane1Cond < 0)
10713       MaskValue |= !Lane2Cond << i;
10714     else
10715       return false;
10716   }
10717   return true;
10718 }
10719
10720 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10721 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10722                                            const X86Subtarget *Subtarget,
10723                                            SelectionDAG &DAG) {
10724   SDValue Cond = Op.getOperand(0);
10725   SDValue LHS = Op.getOperand(1);
10726   SDValue RHS = Op.getOperand(2);
10727   SDLoc dl(Op);
10728   MVT VT = Op.getSimpleValueType();
10729
10730   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10731     return SDValue();
10732   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10733
10734   // Only non-legal VSELECTs reach this lowering, convert those into generic
10735   // shuffles and re-use the shuffle lowering path for blends.
10736   SmallVector<int, 32> Mask;
10737   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10738     SDValue CondElt = CondBV->getOperand(i);
10739     Mask.push_back(
10740         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10741   }
10742   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10743 }
10744
10745 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10746   // A vselect where all conditions and data are constants can be optimized into
10747   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10748   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10749       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10750       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10751     return SDValue();
10752
10753   // Try to lower this to a blend-style vector shuffle. This can handle all
10754   // constant condition cases.
10755   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10756     return BlendOp;
10757
10758   // Variable blends are only legal from SSE4.1 onward.
10759   if (!Subtarget->hasSSE41())
10760     return SDValue();
10761
10762   // Only some types will be legal on some subtargets. If we can emit a legal
10763   // VSELECT-matching blend, return Op, and but if we need to expand, return
10764   // a null value.
10765   switch (Op.getSimpleValueType().SimpleTy) {
10766   default:
10767     // Most of the vector types have blends past SSE4.1.
10768     return Op;
10769
10770   case MVT::v32i8:
10771     // The byte blends for AVX vectors were introduced only in AVX2.
10772     if (Subtarget->hasAVX2())
10773       return Op;
10774
10775     return SDValue();
10776
10777   case MVT::v8i16:
10778   case MVT::v16i16:
10779     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10780     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10781       return Op;
10782
10783     // FIXME: We should custom lower this by fixing the condition and using i8
10784     // blends.
10785     return SDValue();
10786   }
10787 }
10788
10789 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10790   MVT VT = Op.getSimpleValueType();
10791   SDLoc dl(Op);
10792
10793   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10794     return SDValue();
10795
10796   if (VT.getSizeInBits() == 8) {
10797     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10798                                   Op.getOperand(0), Op.getOperand(1));
10799     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10800                                   DAG.getValueType(VT));
10801     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10802   }
10803
10804   if (VT.getSizeInBits() == 16) {
10805     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10806     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10807     if (Idx == 0)
10808       return DAG.getNode(
10809           ISD::TRUNCATE, dl, MVT::i16,
10810           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10811                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10812                       Op.getOperand(1)));
10813     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10814                                   Op.getOperand(0), Op.getOperand(1));
10815     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10816                                   DAG.getValueType(VT));
10817     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10818   }
10819
10820   if (VT == MVT::f32) {
10821     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10822     // the result back to FR32 register. It's only worth matching if the
10823     // result has a single use which is a store or a bitcast to i32.  And in
10824     // the case of a store, it's not worth it if the index is a constant 0,
10825     // because a MOVSSmr can be used instead, which is smaller and faster.
10826     if (!Op.hasOneUse())
10827       return SDValue();
10828     SDNode *User = *Op.getNode()->use_begin();
10829     if ((User->getOpcode() != ISD::STORE ||
10830          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10831           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10832         (User->getOpcode() != ISD::BITCAST ||
10833          User->getValueType(0) != MVT::i32))
10834       return SDValue();
10835     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10836                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10837                                   Op.getOperand(1));
10838     return DAG.getBitcast(MVT::f32, Extract);
10839   }
10840
10841   if (VT == MVT::i32 || VT == MVT::i64) {
10842     // ExtractPS/pextrq works with constant index.
10843     if (isa<ConstantSDNode>(Op.getOperand(1)))
10844       return Op;
10845   }
10846   return SDValue();
10847 }
10848
10849 /// Extract one bit from mask vector, like v16i1 or v8i1.
10850 /// AVX-512 feature.
10851 SDValue
10852 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10853   SDValue Vec = Op.getOperand(0);
10854   SDLoc dl(Vec);
10855   MVT VecVT = Vec.getSimpleValueType();
10856   SDValue Idx = Op.getOperand(1);
10857   MVT EltVT = Op.getSimpleValueType();
10858
10859   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10860   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10861          "Unexpected vector type in ExtractBitFromMaskVector");
10862
10863   // variable index can't be handled in mask registers,
10864   // extend vector to VR512
10865   if (!isa<ConstantSDNode>(Idx)) {
10866     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10867     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10868     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10869                               ExtVT.getVectorElementType(), Ext, Idx);
10870     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10871   }
10872
10873   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10874   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10875   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10876     rc = getRegClassFor(MVT::v16i1);
10877   unsigned MaxSift = rc->getSize()*8 - 1;
10878   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10879                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10880   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10881                     DAG.getConstant(MaxSift, dl, MVT::i8));
10882   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10883                        DAG.getIntPtrConstant(0, dl));
10884 }
10885
10886 SDValue
10887 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10888                                            SelectionDAG &DAG) const {
10889   SDLoc dl(Op);
10890   SDValue Vec = Op.getOperand(0);
10891   MVT VecVT = Vec.getSimpleValueType();
10892   SDValue Idx = Op.getOperand(1);
10893
10894   if (Op.getSimpleValueType() == MVT::i1)
10895     return ExtractBitFromMaskVector(Op, DAG);
10896
10897   if (!isa<ConstantSDNode>(Idx)) {
10898     if (VecVT.is512BitVector() ||
10899         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10900          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10901
10902       MVT MaskEltVT =
10903         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10904       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10905                                     MaskEltVT.getSizeInBits());
10906
10907       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10908       auto PtrVT = getPointerTy(DAG.getDataLayout());
10909       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10910                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10911                                  DAG.getConstant(0, dl, PtrVT));
10912       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10913       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10914                          DAG.getConstant(0, dl, PtrVT));
10915     }
10916     return SDValue();
10917   }
10918
10919   // If this is a 256-bit vector result, first extract the 128-bit vector and
10920   // then extract the element from the 128-bit vector.
10921   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10922
10923     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10924     // Get the 128-bit vector.
10925     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10926     MVT EltVT = VecVT.getVectorElementType();
10927
10928     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10929
10930     //if (IdxVal >= NumElems/2)
10931     //  IdxVal -= NumElems/2;
10932     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10933     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10934                        DAG.getConstant(IdxVal, dl, MVT::i32));
10935   }
10936
10937   assert(VecVT.is128BitVector() && "Unexpected vector length");
10938
10939   if (Subtarget->hasSSE41())
10940     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10941       return Res;
10942
10943   MVT VT = Op.getSimpleValueType();
10944   // TODO: handle v16i8.
10945   if (VT.getSizeInBits() == 16) {
10946     SDValue Vec = Op.getOperand(0);
10947     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10948     if (Idx == 0)
10949       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10950                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10951                                      DAG.getBitcast(MVT::v4i32, Vec),
10952                                      Op.getOperand(1)));
10953     // Transform it so it match pextrw which produces a 32-bit result.
10954     MVT EltVT = MVT::i32;
10955     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10956                                   Op.getOperand(0), Op.getOperand(1));
10957     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10958                                   DAG.getValueType(VT));
10959     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10960   }
10961
10962   if (VT.getSizeInBits() == 32) {
10963     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10964     if (Idx == 0)
10965       return Op;
10966
10967     // SHUFPS the element to the lowest double word, then movss.
10968     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10969     MVT VVT = Op.getOperand(0).getSimpleValueType();
10970     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10971                                        DAG.getUNDEF(VVT), Mask);
10972     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10973                        DAG.getIntPtrConstant(0, dl));
10974   }
10975
10976   if (VT.getSizeInBits() == 64) {
10977     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10978     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10979     //        to match extract_elt for f64.
10980     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10981     if (Idx == 0)
10982       return Op;
10983
10984     // UNPCKHPD the element to the lowest double word, then movsd.
10985     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10986     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10987     int Mask[2] = { 1, -1 };
10988     MVT VVT = Op.getOperand(0).getSimpleValueType();
10989     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10990                                        DAG.getUNDEF(VVT), Mask);
10991     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10992                        DAG.getIntPtrConstant(0, dl));
10993   }
10994
10995   return SDValue();
10996 }
10997
10998 /// Insert one bit to mask vector, like v16i1 or v8i1.
10999 /// AVX-512 feature.
11000 SDValue
11001 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11002   SDLoc dl(Op);
11003   SDValue Vec = Op.getOperand(0);
11004   SDValue Elt = Op.getOperand(1);
11005   SDValue Idx = Op.getOperand(2);
11006   MVT VecVT = Vec.getSimpleValueType();
11007
11008   if (!isa<ConstantSDNode>(Idx)) {
11009     // Non constant index. Extend source and destination,
11010     // insert element and then truncate the result.
11011     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11012     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11013     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11014       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11015       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11016     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11017   }
11018
11019   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11020   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11021   if (IdxVal)
11022     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11023                            DAG.getConstant(IdxVal, dl, MVT::i8));
11024   if (Vec.getOpcode() == ISD::UNDEF)
11025     return EltInVec;
11026   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11027 }
11028
11029 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11030                                                   SelectionDAG &DAG) const {
11031   MVT VT = Op.getSimpleValueType();
11032   MVT EltVT = VT.getVectorElementType();
11033
11034   if (EltVT == MVT::i1)
11035     return InsertBitToMaskVector(Op, DAG);
11036
11037   SDLoc dl(Op);
11038   SDValue N0 = Op.getOperand(0);
11039   SDValue N1 = Op.getOperand(1);
11040   SDValue N2 = Op.getOperand(2);
11041   if (!isa<ConstantSDNode>(N2))
11042     return SDValue();
11043   auto *N2C = cast<ConstantSDNode>(N2);
11044   unsigned IdxVal = N2C->getZExtValue();
11045
11046   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11047   // into that, and then insert the subvector back into the result.
11048   if (VT.is256BitVector() || VT.is512BitVector()) {
11049     // With a 256-bit vector, we can insert into the zero element efficiently
11050     // using a blend if we have AVX or AVX2 and the right data type.
11051     if (VT.is256BitVector() && IdxVal == 0) {
11052       // TODO: It is worthwhile to cast integer to floating point and back
11053       // and incur a domain crossing penalty if that's what we'll end up
11054       // doing anyway after extracting to a 128-bit vector.
11055       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11056           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11057         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11058         N2 = DAG.getIntPtrConstant(1, dl);
11059         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11060       }
11061     }
11062
11063     // Get the desired 128-bit vector chunk.
11064     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11065
11066     // Insert the element into the desired chunk.
11067     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11068     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11069
11070     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11071                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11072
11073     // Insert the changed part back into the bigger vector
11074     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11075   }
11076   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11077
11078   if (Subtarget->hasSSE41()) {
11079     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11080       unsigned Opc;
11081       if (VT == MVT::v8i16) {
11082         Opc = X86ISD::PINSRW;
11083       } else {
11084         assert(VT == MVT::v16i8);
11085         Opc = X86ISD::PINSRB;
11086       }
11087
11088       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11089       // argument.
11090       if (N1.getValueType() != MVT::i32)
11091         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11092       if (N2.getValueType() != MVT::i32)
11093         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11094       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11095     }
11096
11097     if (EltVT == MVT::f32) {
11098       // Bits [7:6] of the constant are the source select. This will always be
11099       //   zero here. The DAG Combiner may combine an extract_elt index into
11100       //   these bits. For example (insert (extract, 3), 2) could be matched by
11101       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11102       // Bits [5:4] of the constant are the destination select. This is the
11103       //   value of the incoming immediate.
11104       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11105       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11106
11107       const Function *F = DAG.getMachineFunction().getFunction();
11108       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11109       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11110         // If this is an insertion of 32-bits into the low 32-bits of
11111         // a vector, we prefer to generate a blend with immediate rather
11112         // than an insertps. Blends are simpler operations in hardware and so
11113         // will always have equal or better performance than insertps.
11114         // But if optimizing for size and there's a load folding opportunity,
11115         // generate insertps because blendps does not have a 32-bit memory
11116         // operand form.
11117         N2 = DAG.getIntPtrConstant(1, dl);
11118         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11119         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11120       }
11121       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11122       // Create this as a scalar to vector..
11123       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11124       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11125     }
11126
11127     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11128       // PINSR* works with constant index.
11129       return Op;
11130     }
11131   }
11132
11133   if (EltVT == MVT::i8)
11134     return SDValue();
11135
11136   if (EltVT.getSizeInBits() == 16) {
11137     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11138     // as its second argument.
11139     if (N1.getValueType() != MVT::i32)
11140       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11141     if (N2.getValueType() != MVT::i32)
11142       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11143     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11144   }
11145   return SDValue();
11146 }
11147
11148 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11149   SDLoc dl(Op);
11150   MVT OpVT = Op.getSimpleValueType();
11151
11152   // If this is a 256-bit vector result, first insert into a 128-bit
11153   // vector and then insert into the 256-bit vector.
11154   if (!OpVT.is128BitVector()) {
11155     // Insert into a 128-bit vector.
11156     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11157     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11158                                  OpVT.getVectorNumElements() / SizeFactor);
11159
11160     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11161
11162     // Insert the 128-bit vector.
11163     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11164   }
11165
11166   if (OpVT == MVT::v1i64 &&
11167       Op.getOperand(0).getValueType() == MVT::i64)
11168     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11169
11170   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11171   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11172   return DAG.getBitcast(
11173       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11174 }
11175
11176 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11177 // a simple subregister reference or explicit instructions to grab
11178 // upper bits of a vector.
11179 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11180                                       SelectionDAG &DAG) {
11181   SDLoc dl(Op);
11182   SDValue In =  Op.getOperand(0);
11183   SDValue Idx = Op.getOperand(1);
11184   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11185   MVT ResVT   = Op.getSimpleValueType();
11186   MVT InVT    = In.getSimpleValueType();
11187
11188   if (Subtarget->hasFp256()) {
11189     if (ResVT.is128BitVector() &&
11190         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11191         isa<ConstantSDNode>(Idx)) {
11192       return Extract128BitVector(In, IdxVal, DAG, dl);
11193     }
11194     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11195         isa<ConstantSDNode>(Idx)) {
11196       return Extract256BitVector(In, IdxVal, DAG, dl);
11197     }
11198   }
11199   return SDValue();
11200 }
11201
11202 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11203 // simple superregister reference or explicit instructions to insert
11204 // the upper bits of a vector.
11205 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11206                                      SelectionDAG &DAG) {
11207   if (!Subtarget->hasAVX())
11208     return SDValue();
11209
11210   SDLoc dl(Op);
11211   SDValue Vec = Op.getOperand(0);
11212   SDValue SubVec = Op.getOperand(1);
11213   SDValue Idx = Op.getOperand(2);
11214
11215   if (!isa<ConstantSDNode>(Idx))
11216     return SDValue();
11217
11218   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11219   MVT OpVT = Op.getSimpleValueType();
11220   MVT SubVecVT = SubVec.getSimpleValueType();
11221
11222   // Fold two 16-byte subvector loads into one 32-byte load:
11223   // (insert_subvector (insert_subvector undef, (load addr), 0),
11224   //                   (load addr + 16), Elts/2)
11225   // --> load32 addr
11226   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11227       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11228       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11229       !Subtarget->isUnalignedMem32Slow()) {
11230     SDValue SubVec2 = Vec.getOperand(1);
11231     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11232       if (Idx2->getZExtValue() == 0) {
11233         SDValue Ops[] = { SubVec2, SubVec };
11234         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11235           return Ld;
11236       }
11237     }
11238   }
11239
11240   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11241       SubVecVT.is128BitVector())
11242     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11243
11244   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11245     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11246
11247   if (OpVT.getVectorElementType() == MVT::i1) {
11248     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11249       return Op;
11250     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11251     SDValue Undef = DAG.getUNDEF(OpVT);
11252     unsigned NumElems = OpVT.getVectorNumElements();
11253     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11254
11255     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11256       // Zero upper bits of the Vec
11257       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11258       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11259
11260       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11261                                  SubVec, ZeroIdx);
11262       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11263       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11264     }
11265     if (IdxVal == 0) {
11266       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11267                                  SubVec, ZeroIdx);
11268       // Zero upper bits of the Vec2
11269       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11270       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11271       // Zero lower bits of the Vec
11272       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11273       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11274       // Merge them together
11275       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11276     }
11277   }
11278   return SDValue();
11279 }
11280
11281 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11282 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11283 // one of the above mentioned nodes. It has to be wrapped because otherwise
11284 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11285 // be used to form addressing mode. These wrapped nodes will be selected
11286 // into MOV32ri.
11287 SDValue
11288 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11289   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11290
11291   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11292   // global base reg.
11293   unsigned char OpFlag = 0;
11294   unsigned WrapperKind = X86ISD::Wrapper;
11295   CodeModel::Model M = DAG.getTarget().getCodeModel();
11296
11297   if (Subtarget->isPICStyleRIPRel() &&
11298       (M == CodeModel::Small || M == CodeModel::Kernel))
11299     WrapperKind = X86ISD::WrapperRIP;
11300   else if (Subtarget->isPICStyleGOT())
11301     OpFlag = X86II::MO_GOTOFF;
11302   else if (Subtarget->isPICStyleStubPIC())
11303     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11304
11305   auto PtrVT = getPointerTy(DAG.getDataLayout());
11306   SDValue Result = DAG.getTargetConstantPool(
11307       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11308   SDLoc DL(CP);
11309   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11310   // With PIC, the address is actually $g + Offset.
11311   if (OpFlag) {
11312     Result =
11313         DAG.getNode(ISD::ADD, DL, PtrVT,
11314                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11315   }
11316
11317   return Result;
11318 }
11319
11320 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11321   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11322
11323   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11324   // global base reg.
11325   unsigned char OpFlag = 0;
11326   unsigned WrapperKind = X86ISD::Wrapper;
11327   CodeModel::Model M = DAG.getTarget().getCodeModel();
11328
11329   if (Subtarget->isPICStyleRIPRel() &&
11330       (M == CodeModel::Small || M == CodeModel::Kernel))
11331     WrapperKind = X86ISD::WrapperRIP;
11332   else if (Subtarget->isPICStyleGOT())
11333     OpFlag = X86II::MO_GOTOFF;
11334   else if (Subtarget->isPICStyleStubPIC())
11335     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11336
11337   auto PtrVT = getPointerTy(DAG.getDataLayout());
11338   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11339   SDLoc DL(JT);
11340   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11341
11342   // With PIC, the address is actually $g + Offset.
11343   if (OpFlag)
11344     Result =
11345         DAG.getNode(ISD::ADD, DL, PtrVT,
11346                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11347
11348   return Result;
11349 }
11350
11351 SDValue
11352 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11353   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11354
11355   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11356   // global base reg.
11357   unsigned char OpFlag = 0;
11358   unsigned WrapperKind = X86ISD::Wrapper;
11359   CodeModel::Model M = DAG.getTarget().getCodeModel();
11360
11361   if (Subtarget->isPICStyleRIPRel() &&
11362       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11363     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11364       OpFlag = X86II::MO_GOTPCREL;
11365     WrapperKind = X86ISD::WrapperRIP;
11366   } else if (Subtarget->isPICStyleGOT()) {
11367     OpFlag = X86II::MO_GOT;
11368   } else if (Subtarget->isPICStyleStubPIC()) {
11369     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11370   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11371     OpFlag = X86II::MO_DARWIN_NONLAZY;
11372   }
11373
11374   auto PtrVT = getPointerTy(DAG.getDataLayout());
11375   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11376
11377   SDLoc DL(Op);
11378   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11379
11380   // With PIC, the address is actually $g + Offset.
11381   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11382       !Subtarget->is64Bit()) {
11383     Result =
11384         DAG.getNode(ISD::ADD, DL, PtrVT,
11385                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11386   }
11387
11388   // For symbols that require a load from a stub to get the address, emit the
11389   // load.
11390   if (isGlobalStubReference(OpFlag))
11391     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11392                          MachinePointerInfo::getGOT(), false, false, false, 0);
11393
11394   return Result;
11395 }
11396
11397 SDValue
11398 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11399   // Create the TargetBlockAddressAddress node.
11400   unsigned char OpFlags =
11401     Subtarget->ClassifyBlockAddressReference();
11402   CodeModel::Model M = DAG.getTarget().getCodeModel();
11403   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11404   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11405   SDLoc dl(Op);
11406   auto PtrVT = getPointerTy(DAG.getDataLayout());
11407   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11408
11409   if (Subtarget->isPICStyleRIPRel() &&
11410       (M == CodeModel::Small || M == CodeModel::Kernel))
11411     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11412   else
11413     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11414
11415   // With PIC, the address is actually $g + Offset.
11416   if (isGlobalRelativeToPICBase(OpFlags)) {
11417     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11418                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11419   }
11420
11421   return Result;
11422 }
11423
11424 SDValue
11425 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11426                                       int64_t Offset, SelectionDAG &DAG) const {
11427   // Create the TargetGlobalAddress node, folding in the constant
11428   // offset if it is legal.
11429   unsigned char OpFlags =
11430       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11431   CodeModel::Model M = DAG.getTarget().getCodeModel();
11432   auto PtrVT = getPointerTy(DAG.getDataLayout());
11433   SDValue Result;
11434   if (OpFlags == X86II::MO_NO_FLAG &&
11435       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11436     // A direct static reference to a global.
11437     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11438     Offset = 0;
11439   } else {
11440     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11441   }
11442
11443   if (Subtarget->isPICStyleRIPRel() &&
11444       (M == CodeModel::Small || M == CodeModel::Kernel))
11445     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11446   else
11447     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11448
11449   // With PIC, the address is actually $g + Offset.
11450   if (isGlobalRelativeToPICBase(OpFlags)) {
11451     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11452                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11453   }
11454
11455   // For globals that require a load from a stub to get the address, emit the
11456   // load.
11457   if (isGlobalStubReference(OpFlags))
11458     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11459                          MachinePointerInfo::getGOT(), false, false, false, 0);
11460
11461   // If there was a non-zero offset that we didn't fold, create an explicit
11462   // addition for it.
11463   if (Offset != 0)
11464     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11465                          DAG.getConstant(Offset, dl, PtrVT));
11466
11467   return Result;
11468 }
11469
11470 SDValue
11471 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11472   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11473   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11474   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11475 }
11476
11477 static SDValue
11478 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11479            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11480            unsigned char OperandFlags, bool LocalDynamic = false) {
11481   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11482   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11483   SDLoc dl(GA);
11484   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11485                                            GA->getValueType(0),
11486                                            GA->getOffset(),
11487                                            OperandFlags);
11488
11489   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11490                                            : X86ISD::TLSADDR;
11491
11492   if (InFlag) {
11493     SDValue Ops[] = { Chain,  TGA, *InFlag };
11494     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11495   } else {
11496     SDValue Ops[]  = { Chain, TGA };
11497     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11498   }
11499
11500   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11501   MFI->setAdjustsStack(true);
11502   MFI->setHasCalls(true);
11503
11504   SDValue Flag = Chain.getValue(1);
11505   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11506 }
11507
11508 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11509 static SDValue
11510 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11511                                 const EVT PtrVT) {
11512   SDValue InFlag;
11513   SDLoc dl(GA);  // ? function entry point might be better
11514   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11515                                    DAG.getNode(X86ISD::GlobalBaseReg,
11516                                                SDLoc(), PtrVT), InFlag);
11517   InFlag = Chain.getValue(1);
11518
11519   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11520 }
11521
11522 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11523 static SDValue
11524 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11525                                 const EVT PtrVT) {
11526   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11527                     X86::RAX, X86II::MO_TLSGD);
11528 }
11529
11530 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11531                                            SelectionDAG &DAG,
11532                                            const EVT PtrVT,
11533                                            bool is64Bit) {
11534   SDLoc dl(GA);
11535
11536   // Get the start address of the TLS block for this module.
11537   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11538       .getInfo<X86MachineFunctionInfo>();
11539   MFI->incNumLocalDynamicTLSAccesses();
11540
11541   SDValue Base;
11542   if (is64Bit) {
11543     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11544                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11545   } else {
11546     SDValue InFlag;
11547     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11548         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11549     InFlag = Chain.getValue(1);
11550     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11551                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11552   }
11553
11554   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11555   // of Base.
11556
11557   // Build x@dtpoff.
11558   unsigned char OperandFlags = X86II::MO_DTPOFF;
11559   unsigned WrapperKind = X86ISD::Wrapper;
11560   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11561                                            GA->getValueType(0),
11562                                            GA->getOffset(), OperandFlags);
11563   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11564
11565   // Add x@dtpoff with the base.
11566   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11567 }
11568
11569 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11570 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11571                                    const EVT PtrVT, TLSModel::Model model,
11572                                    bool is64Bit, bool isPIC) {
11573   SDLoc dl(GA);
11574
11575   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11576   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11577                                                          is64Bit ? 257 : 256));
11578
11579   SDValue ThreadPointer =
11580       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11581                   MachinePointerInfo(Ptr), false, false, false, 0);
11582
11583   unsigned char OperandFlags = 0;
11584   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11585   // initialexec.
11586   unsigned WrapperKind = X86ISD::Wrapper;
11587   if (model == TLSModel::LocalExec) {
11588     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11589   } else if (model == TLSModel::InitialExec) {
11590     if (is64Bit) {
11591       OperandFlags = X86II::MO_GOTTPOFF;
11592       WrapperKind = X86ISD::WrapperRIP;
11593     } else {
11594       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11595     }
11596   } else {
11597     llvm_unreachable("Unexpected model");
11598   }
11599
11600   // emit "addl x@ntpoff,%eax" (local exec)
11601   // or "addl x@indntpoff,%eax" (initial exec)
11602   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11603   SDValue TGA =
11604       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11605                                  GA->getOffset(), OperandFlags);
11606   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11607
11608   if (model == TLSModel::InitialExec) {
11609     if (isPIC && !is64Bit) {
11610       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11611                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11612                            Offset);
11613     }
11614
11615     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11616                          MachinePointerInfo::getGOT(), false, false, false, 0);
11617   }
11618
11619   // The address of the thread local variable is the add of the thread
11620   // pointer with the offset of the variable.
11621   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11622 }
11623
11624 SDValue
11625 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11626
11627   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11628   const GlobalValue *GV = GA->getGlobal();
11629   auto PtrVT = getPointerTy(DAG.getDataLayout());
11630
11631   if (Subtarget->isTargetELF()) {
11632     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11633     switch (model) {
11634       case TLSModel::GeneralDynamic:
11635         if (Subtarget->is64Bit())
11636           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11637         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11638       case TLSModel::LocalDynamic:
11639         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11640                                            Subtarget->is64Bit());
11641       case TLSModel::InitialExec:
11642       case TLSModel::LocalExec:
11643         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11644                                    DAG.getTarget().getRelocationModel() ==
11645                                        Reloc::PIC_);
11646     }
11647     llvm_unreachable("Unknown TLS model.");
11648   }
11649
11650   if (Subtarget->isTargetDarwin()) {
11651     // Darwin only has one model of TLS.  Lower to that.
11652     unsigned char OpFlag = 0;
11653     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11654                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11655
11656     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11657     // global base reg.
11658     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11659                  !Subtarget->is64Bit();
11660     if (PIC32)
11661       OpFlag = X86II::MO_TLVP_PIC_BASE;
11662     else
11663       OpFlag = X86II::MO_TLVP;
11664     SDLoc DL(Op);
11665     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11666                                                 GA->getValueType(0),
11667                                                 GA->getOffset(), OpFlag);
11668     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11669
11670     // With PIC32, the address is actually $g + Offset.
11671     if (PIC32)
11672       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11673                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11674                            Offset);
11675
11676     // Lowering the machine isd will make sure everything is in the right
11677     // location.
11678     SDValue Chain = DAG.getEntryNode();
11679     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11680     SDValue Args[] = { Chain, Offset };
11681     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11682
11683     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11684     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11685     MFI->setAdjustsStack(true);
11686
11687     // And our return value (tls address) is in the standard call return value
11688     // location.
11689     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11690     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11691   }
11692
11693   if (Subtarget->isTargetKnownWindowsMSVC() ||
11694       Subtarget->isTargetWindowsGNU()) {
11695     // Just use the implicit TLS architecture
11696     // Need to generate someting similar to:
11697     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11698     //                                  ; from TEB
11699     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11700     //   mov     rcx, qword [rdx+rcx*8]
11701     //   mov     eax, .tls$:tlsvar
11702     //   [rax+rcx] contains the address
11703     // Windows 64bit: gs:0x58
11704     // Windows 32bit: fs:__tls_array
11705
11706     SDLoc dl(GA);
11707     SDValue Chain = DAG.getEntryNode();
11708
11709     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11710     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11711     // use its literal value of 0x2C.
11712     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11713                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11714                                                              256)
11715                                         : Type::getInt32PtrTy(*DAG.getContext(),
11716                                                               257));
11717
11718     SDValue TlsArray = Subtarget->is64Bit()
11719                            ? DAG.getIntPtrConstant(0x58, dl)
11720                            : (Subtarget->isTargetWindowsGNU()
11721                                   ? DAG.getIntPtrConstant(0x2C, dl)
11722                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11723
11724     SDValue ThreadPointer =
11725         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11726                     false, false, 0);
11727
11728     SDValue res;
11729     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11730       res = ThreadPointer;
11731     } else {
11732       // Load the _tls_index variable
11733       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11734       if (Subtarget->is64Bit())
11735         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11736                              MachinePointerInfo(), MVT::i32, false, false,
11737                              false, 0);
11738       else
11739         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11740                           false, false, 0);
11741
11742       auto &DL = DAG.getDataLayout();
11743       SDValue Scale =
11744           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11745       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11746
11747       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11748     }
11749
11750     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11751                       false, 0);
11752
11753     // Get the offset of start of .tls section
11754     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11755                                              GA->getValueType(0),
11756                                              GA->getOffset(), X86II::MO_SECREL);
11757     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11758
11759     // The address of the thread local variable is the add of the thread
11760     // pointer with the offset of the variable.
11761     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11762   }
11763
11764   llvm_unreachable("TLS not implemented for this target.");
11765 }
11766
11767 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11768 /// and take a 2 x i32 value to shift plus a shift amount.
11769 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11770   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11771   MVT VT = Op.getSimpleValueType();
11772   unsigned VTBits = VT.getSizeInBits();
11773   SDLoc dl(Op);
11774   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11775   SDValue ShOpLo = Op.getOperand(0);
11776   SDValue ShOpHi = Op.getOperand(1);
11777   SDValue ShAmt  = Op.getOperand(2);
11778   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11779   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11780   // during isel.
11781   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11782                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11783   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11784                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11785                        : DAG.getConstant(0, dl, VT);
11786
11787   SDValue Tmp2, Tmp3;
11788   if (Op.getOpcode() == ISD::SHL_PARTS) {
11789     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11790     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11791   } else {
11792     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11793     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11794   }
11795
11796   // If the shift amount is larger or equal than the width of a part we can't
11797   // rely on the results of shld/shrd. Insert a test and select the appropriate
11798   // values for large shift amounts.
11799   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11800                                 DAG.getConstant(VTBits, dl, MVT::i8));
11801   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11802                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11803
11804   SDValue Hi, Lo;
11805   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11806   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11807   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11808
11809   if (Op.getOpcode() == ISD::SHL_PARTS) {
11810     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11811     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11812   } else {
11813     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11814     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11815   }
11816
11817   SDValue Ops[2] = { Lo, Hi };
11818   return DAG.getMergeValues(Ops, dl);
11819 }
11820
11821 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11822                                            SelectionDAG &DAG) const {
11823   SDValue Src = Op.getOperand(0);
11824   MVT SrcVT = Src.getSimpleValueType();
11825   MVT VT = Op.getSimpleValueType();
11826   SDLoc dl(Op);
11827
11828   if (SrcVT.isVector()) {
11829     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11830       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11831                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11832                          DAG.getUNDEF(SrcVT)));
11833     }
11834     if (SrcVT.getVectorElementType() == MVT::i1) {
11835       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11836       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11837                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11838     }
11839     return SDValue();
11840   }
11841
11842   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11843          "Unknown SINT_TO_FP to lower!");
11844
11845   // These are really Legal; return the operand so the caller accepts it as
11846   // Legal.
11847   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11848     return Op;
11849   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11850       Subtarget->is64Bit()) {
11851     return Op;
11852   }
11853
11854   unsigned Size = SrcVT.getSizeInBits()/8;
11855   MachineFunction &MF = DAG.getMachineFunction();
11856   auto PtrVT = getPointerTy(MF.getDataLayout());
11857   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11858   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11859   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11860                                StackSlot,
11861                                MachinePointerInfo::getFixedStack(SSFI),
11862                                false, false, 0);
11863   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11864 }
11865
11866 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11867                                      SDValue StackSlot,
11868                                      SelectionDAG &DAG) const {
11869   // Build the FILD
11870   SDLoc DL(Op);
11871   SDVTList Tys;
11872   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11873   if (useSSE)
11874     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11875   else
11876     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11877
11878   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11879
11880   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11881   MachineMemOperand *MMO;
11882   if (FI) {
11883     int SSFI = FI->getIndex();
11884     MMO =
11885       DAG.getMachineFunction()
11886       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11887                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11888   } else {
11889     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11890     StackSlot = StackSlot.getOperand(1);
11891   }
11892   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11893   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11894                                            X86ISD::FILD, DL,
11895                                            Tys, Ops, SrcVT, MMO);
11896
11897   if (useSSE) {
11898     Chain = Result.getValue(1);
11899     SDValue InFlag = Result.getValue(2);
11900
11901     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11902     // shouldn't be necessary except that RFP cannot be live across
11903     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11904     MachineFunction &MF = DAG.getMachineFunction();
11905     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11906     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11907     auto PtrVT = getPointerTy(MF.getDataLayout());
11908     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11909     Tys = DAG.getVTList(MVT::Other);
11910     SDValue Ops[] = {
11911       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11912     };
11913     MachineMemOperand *MMO =
11914       DAG.getMachineFunction()
11915       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11916                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11917
11918     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11919                                     Ops, Op.getValueType(), MMO);
11920     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11921                          MachinePointerInfo::getFixedStack(SSFI),
11922                          false, false, false, 0);
11923   }
11924
11925   return Result;
11926 }
11927
11928 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11929 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11930                                                SelectionDAG &DAG) const {
11931   // This algorithm is not obvious. Here it is what we're trying to output:
11932   /*
11933      movq       %rax,  %xmm0
11934      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11935      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11936      #ifdef __SSE3__
11937        haddpd   %xmm0, %xmm0
11938      #else
11939        pshufd   $0x4e, %xmm0, %xmm1
11940        addpd    %xmm1, %xmm0
11941      #endif
11942   */
11943
11944   SDLoc dl(Op);
11945   LLVMContext *Context = DAG.getContext();
11946
11947   // Build some magic constants.
11948   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11949   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11950   auto PtrVT = getPointerTy(DAG.getDataLayout());
11951   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11952
11953   SmallVector<Constant*,2> CV1;
11954   CV1.push_back(
11955     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11956                                       APInt(64, 0x4330000000000000ULL))));
11957   CV1.push_back(
11958     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11959                                       APInt(64, 0x4530000000000000ULL))));
11960   Constant *C1 = ConstantVector::get(CV1);
11961   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11962
11963   // Load the 64-bit value into an XMM register.
11964   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11965                             Op.getOperand(0));
11966   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11967                               MachinePointerInfo::getConstantPool(),
11968                               false, false, false, 16);
11969   SDValue Unpck1 =
11970       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11971
11972   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11973                               MachinePointerInfo::getConstantPool(),
11974                               false, false, false, 16);
11975   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11976   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11977   SDValue Result;
11978
11979   if (Subtarget->hasSSE3()) {
11980     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11981     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11982   } else {
11983     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11984     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11985                                            S2F, 0x4E, DAG);
11986     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11987                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
11988   }
11989
11990   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11991                      DAG.getIntPtrConstant(0, dl));
11992 }
11993
11994 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11995 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11996                                                SelectionDAG &DAG) const {
11997   SDLoc dl(Op);
11998   // FP constant to bias correct the final result.
11999   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12000                                    MVT::f64);
12001
12002   // Load the 32-bit value into an XMM register.
12003   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12004                              Op.getOperand(0));
12005
12006   // Zero out the upper parts of the register.
12007   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12008
12009   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12010                      DAG.getBitcast(MVT::v2f64, Load),
12011                      DAG.getIntPtrConstant(0, dl));
12012
12013   // Or the load with the bias.
12014   SDValue Or = DAG.getNode(
12015       ISD::OR, dl, MVT::v2i64,
12016       DAG.getBitcast(MVT::v2i64,
12017                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12018       DAG.getBitcast(MVT::v2i64,
12019                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12020   Or =
12021       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12022                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12023
12024   // Subtract the bias.
12025   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12026
12027   // Handle final rounding.
12028   EVT DestVT = Op.getValueType();
12029
12030   if (DestVT.bitsLT(MVT::f64))
12031     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12032                        DAG.getIntPtrConstant(0, dl));
12033   if (DestVT.bitsGT(MVT::f64))
12034     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12035
12036   // Handle final rounding.
12037   return Sub;
12038 }
12039
12040 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12041                                      const X86Subtarget &Subtarget) {
12042   // The algorithm is the following:
12043   // #ifdef __SSE4_1__
12044   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12045   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12046   //                                 (uint4) 0x53000000, 0xaa);
12047   // #else
12048   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12049   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12050   // #endif
12051   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12052   //     return (float4) lo + fhi;
12053
12054   SDLoc DL(Op);
12055   SDValue V = Op->getOperand(0);
12056   EVT VecIntVT = V.getValueType();
12057   bool Is128 = VecIntVT == MVT::v4i32;
12058   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12059   // If we convert to something else than the supported type, e.g., to v4f64,
12060   // abort early.
12061   if (VecFloatVT != Op->getValueType(0))
12062     return SDValue();
12063
12064   unsigned NumElts = VecIntVT.getVectorNumElements();
12065   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12066          "Unsupported custom type");
12067   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12068
12069   // In the #idef/#else code, we have in common:
12070   // - The vector of constants:
12071   // -- 0x4b000000
12072   // -- 0x53000000
12073   // - A shift:
12074   // -- v >> 16
12075
12076   // Create the splat vector for 0x4b000000.
12077   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12078   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12079                            CstLow, CstLow, CstLow, CstLow};
12080   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12081                                   makeArrayRef(&CstLowArray[0], NumElts));
12082   // Create the splat vector for 0x53000000.
12083   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12084   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12085                             CstHigh, CstHigh, CstHigh, CstHigh};
12086   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12087                                    makeArrayRef(&CstHighArray[0], NumElts));
12088
12089   // Create the right shift.
12090   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12091   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12092                              CstShift, CstShift, CstShift, CstShift};
12093   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12094                                     makeArrayRef(&CstShiftArray[0], NumElts));
12095   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12096
12097   SDValue Low, High;
12098   if (Subtarget.hasSSE41()) {
12099     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12100     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12101     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12102     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12103     // Low will be bitcasted right away, so do not bother bitcasting back to its
12104     // original type.
12105     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12106                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12107     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12108     //                                 (uint4) 0x53000000, 0xaa);
12109     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12110     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12111     // High will be bitcasted right away, so do not bother bitcasting back to
12112     // its original type.
12113     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12114                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12115   } else {
12116     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12117     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12118                                      CstMask, CstMask, CstMask);
12119     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12120     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12121     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12122
12123     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12124     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12125   }
12126
12127   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12128   SDValue CstFAdd = DAG.getConstantFP(
12129       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12130   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12131                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12132   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12133                                    makeArrayRef(&CstFAddArray[0], NumElts));
12134
12135   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12136   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12137   SDValue FHigh =
12138       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12139   //     return (float4) lo + fhi;
12140   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12141   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12142 }
12143
12144 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12145                                                SelectionDAG &DAG) const {
12146   SDValue N0 = Op.getOperand(0);
12147   MVT SVT = N0.getSimpleValueType();
12148   SDLoc dl(Op);
12149
12150   switch (SVT.SimpleTy) {
12151   default:
12152     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12153   case MVT::v4i8:
12154   case MVT::v4i16:
12155   case MVT::v8i8:
12156   case MVT::v8i16: {
12157     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12158     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12159                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12160   }
12161   case MVT::v4i32:
12162   case MVT::v8i32:
12163     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12164   case MVT::v16i8:
12165   case MVT::v16i16:
12166     if (Subtarget->hasAVX512())
12167       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12168                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12169   }
12170   llvm_unreachable(nullptr);
12171 }
12172
12173 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12174                                            SelectionDAG &DAG) const {
12175   SDValue N0 = Op.getOperand(0);
12176   SDLoc dl(Op);
12177   auto PtrVT = getPointerTy(DAG.getDataLayout());
12178
12179   if (Op.getValueType().isVector())
12180     return lowerUINT_TO_FP_vec(Op, DAG);
12181
12182   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12183   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12184   // the optimization here.
12185   if (DAG.SignBitIsZero(N0))
12186     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12187
12188   MVT SrcVT = N0.getSimpleValueType();
12189   MVT DstVT = Op.getSimpleValueType();
12190   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12191     return LowerUINT_TO_FP_i64(Op, DAG);
12192   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12193     return LowerUINT_TO_FP_i32(Op, DAG);
12194   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12195     return SDValue();
12196
12197   // Make a 64-bit buffer, and use it to build an FILD.
12198   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12199   if (SrcVT == MVT::i32) {
12200     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12201     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12202     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12203                                   StackSlot, MachinePointerInfo(),
12204                                   false, false, 0);
12205     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12206                                   OffsetSlot, MachinePointerInfo(),
12207                                   false, false, 0);
12208     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12209     return Fild;
12210   }
12211
12212   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12213   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12214                                StackSlot, MachinePointerInfo(),
12215                                false, false, 0);
12216   // For i64 source, we need to add the appropriate power of 2 if the input
12217   // was negative.  This is the same as the optimization in
12218   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12219   // we must be careful to do the computation in x87 extended precision, not
12220   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12221   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12222   MachineMemOperand *MMO =
12223     DAG.getMachineFunction()
12224     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12225                           MachineMemOperand::MOLoad, 8, 8);
12226
12227   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12228   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12229   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12230                                          MVT::i64, MMO);
12231
12232   APInt FF(32, 0x5F800000ULL);
12233
12234   // Check whether the sign bit is set.
12235   SDValue SignSet = DAG.getSetCC(
12236       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12237       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12238
12239   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12240   SDValue FudgePtr = DAG.getConstantPool(
12241       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12242
12243   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12244   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12245   SDValue Four = DAG.getIntPtrConstant(4, dl);
12246   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12247                                Zero, Four);
12248   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12249
12250   // Load the value out, extending it from f32 to f80.
12251   // FIXME: Avoid the extend by constructing the right constant pool?
12252   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12253                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12254                                  MVT::f32, false, false, false, 4);
12255   // Extend everything to 80 bits to force it to be done on x87.
12256   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12257   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12258                      DAG.getIntPtrConstant(0, dl));
12259 }
12260
12261 std::pair<SDValue,SDValue>
12262 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12263                                     bool IsSigned, bool IsReplace) const {
12264   SDLoc DL(Op);
12265
12266   EVT DstTy = Op.getValueType();
12267   auto PtrVT = getPointerTy(DAG.getDataLayout());
12268
12269   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12270     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12271     DstTy = MVT::i64;
12272   }
12273
12274   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12275          DstTy.getSimpleVT() >= MVT::i16 &&
12276          "Unknown FP_TO_INT to lower!");
12277
12278   // These are really Legal.
12279   if (DstTy == MVT::i32 &&
12280       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12281     return std::make_pair(SDValue(), SDValue());
12282   if (Subtarget->is64Bit() &&
12283       DstTy == MVT::i64 &&
12284       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12285     return std::make_pair(SDValue(), SDValue());
12286
12287   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12288   // stack slot, or into the FTOL runtime function.
12289   MachineFunction &MF = DAG.getMachineFunction();
12290   unsigned MemSize = DstTy.getSizeInBits()/8;
12291   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12292   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12293
12294   unsigned Opc;
12295   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12296     Opc = X86ISD::WIN_FTOL;
12297   else
12298     switch (DstTy.getSimpleVT().SimpleTy) {
12299     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12300     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12301     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12302     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12303     }
12304
12305   SDValue Chain = DAG.getEntryNode();
12306   SDValue Value = Op.getOperand(0);
12307   EVT TheVT = Op.getOperand(0).getValueType();
12308   // FIXME This causes a redundant load/store if the SSE-class value is already
12309   // in memory, such as if it is on the callstack.
12310   if (isScalarFPTypeInSSEReg(TheVT)) {
12311     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12312     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12313                          MachinePointerInfo::getFixedStack(SSFI),
12314                          false, false, 0);
12315     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12316     SDValue Ops[] = {
12317       Chain, StackSlot, DAG.getValueType(TheVT)
12318     };
12319
12320     MachineMemOperand *MMO =
12321       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12322                               MachineMemOperand::MOLoad, MemSize, MemSize);
12323     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12324     Chain = Value.getValue(1);
12325     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12326     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12327   }
12328
12329   MachineMemOperand *MMO =
12330     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12331                             MachineMemOperand::MOStore, MemSize, MemSize);
12332
12333   if (Opc != X86ISD::WIN_FTOL) {
12334     // Build the FP_TO_INT*_IN_MEM
12335     SDValue Ops[] = { Chain, Value, StackSlot };
12336     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12337                                            Ops, DstTy, MMO);
12338     return std::make_pair(FIST, StackSlot);
12339   } else {
12340     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12341       DAG.getVTList(MVT::Other, MVT::Glue),
12342       Chain, Value);
12343     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12344       MVT::i32, ftol.getValue(1));
12345     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12346       MVT::i32, eax.getValue(2));
12347     SDValue Ops[] = { eax, edx };
12348     SDValue pair = IsReplace
12349       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12350       : DAG.getMergeValues(Ops, DL);
12351     return std::make_pair(pair, SDValue());
12352   }
12353 }
12354
12355 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12356                               const X86Subtarget *Subtarget) {
12357   MVT VT = Op->getSimpleValueType(0);
12358   SDValue In = Op->getOperand(0);
12359   MVT InVT = In.getSimpleValueType();
12360   SDLoc dl(Op);
12361
12362   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12363     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12364
12365   // Optimize vectors in AVX mode:
12366   //
12367   //   v8i16 -> v8i32
12368   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12369   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12370   //   Concat upper and lower parts.
12371   //
12372   //   v4i32 -> v4i64
12373   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12374   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12375   //   Concat upper and lower parts.
12376   //
12377
12378   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12379       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12380       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12381     return SDValue();
12382
12383   if (Subtarget->hasInt256())
12384     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12385
12386   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12387   SDValue Undef = DAG.getUNDEF(InVT);
12388   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12389   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12390   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12391
12392   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12393                              VT.getVectorNumElements()/2);
12394
12395   OpLo = DAG.getBitcast(HVT, OpLo);
12396   OpHi = DAG.getBitcast(HVT, OpHi);
12397
12398   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12399 }
12400
12401 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12402                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12403   MVT VT = Op->getSimpleValueType(0);
12404   SDValue In = Op->getOperand(0);
12405   MVT InVT = In.getSimpleValueType();
12406   SDLoc DL(Op);
12407   unsigned int NumElts = VT.getVectorNumElements();
12408   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12409     return SDValue();
12410
12411   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12412     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12413
12414   assert(InVT.getVectorElementType() == MVT::i1);
12415   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12416   SDValue One =
12417    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12418   SDValue Zero =
12419    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12420
12421   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12422   if (VT.is512BitVector())
12423     return V;
12424   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12425 }
12426
12427 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12428                                SelectionDAG &DAG) {
12429   if (Subtarget->hasFp256())
12430     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12431       return Res;
12432
12433   return SDValue();
12434 }
12435
12436 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12437                                 SelectionDAG &DAG) {
12438   SDLoc DL(Op);
12439   MVT VT = Op.getSimpleValueType();
12440   SDValue In = Op.getOperand(0);
12441   MVT SVT = In.getSimpleValueType();
12442
12443   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12444     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12445
12446   if (Subtarget->hasFp256())
12447     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12448       return Res;
12449
12450   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12451          VT.getVectorNumElements() != SVT.getVectorNumElements());
12452   return SDValue();
12453 }
12454
12455 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12456   SDLoc DL(Op);
12457   MVT VT = Op.getSimpleValueType();
12458   SDValue In = Op.getOperand(0);
12459   MVT InVT = In.getSimpleValueType();
12460
12461   if (VT == MVT::i1) {
12462     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12463            "Invalid scalar TRUNCATE operation");
12464     if (InVT.getSizeInBits() >= 32)
12465       return SDValue();
12466     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12467     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12468   }
12469   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12470          "Invalid TRUNCATE operation");
12471
12472   // move vector to mask - truncate solution for SKX
12473   if (VT.getVectorElementType() == MVT::i1) {
12474     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12475         Subtarget->hasBWI())
12476       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12477     if ((InVT.is256BitVector() || InVT.is128BitVector())
12478         && InVT.getScalarSizeInBits() <= 16 &&
12479         Subtarget->hasBWI() && Subtarget->hasVLX())
12480       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12481     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12482         Subtarget->hasDQI())
12483       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12484     if ((InVT.is256BitVector() || InVT.is128BitVector())
12485         && InVT.getScalarSizeInBits() >= 32 &&
12486         Subtarget->hasDQI() && Subtarget->hasVLX())
12487       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12488   }
12489   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12490     if (VT.getVectorElementType().getSizeInBits() >=8)
12491       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12492
12493     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12494     unsigned NumElts = InVT.getVectorNumElements();
12495     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12496     if (InVT.getSizeInBits() < 512) {
12497       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12498       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12499       InVT = ExtVT;
12500     }
12501
12502     SDValue OneV =
12503      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12504     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12505     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12506   }
12507
12508   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12509     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12510     if (Subtarget->hasInt256()) {
12511       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12512       In = DAG.getBitcast(MVT::v8i32, In);
12513       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12514                                 ShufMask);
12515       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12516                          DAG.getIntPtrConstant(0, DL));
12517     }
12518
12519     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12520                                DAG.getIntPtrConstant(0, DL));
12521     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12522                                DAG.getIntPtrConstant(2, DL));
12523     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12524     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12525     static const int ShufMask[] = {0, 2, 4, 6};
12526     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12527   }
12528
12529   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12530     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12531     if (Subtarget->hasInt256()) {
12532       In = DAG.getBitcast(MVT::v32i8, In);
12533
12534       SmallVector<SDValue,32> pshufbMask;
12535       for (unsigned i = 0; i < 2; ++i) {
12536         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12537         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12538         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12539         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12540         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12541         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12542         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12543         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12544         for (unsigned j = 0; j < 8; ++j)
12545           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12546       }
12547       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12548       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12549       In = DAG.getBitcast(MVT::v4i64, In);
12550
12551       static const int ShufMask[] = {0,  2,  -1,  -1};
12552       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12553                                 &ShufMask[0]);
12554       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12555                        DAG.getIntPtrConstant(0, DL));
12556       return DAG.getBitcast(VT, In);
12557     }
12558
12559     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12560                                DAG.getIntPtrConstant(0, DL));
12561
12562     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12563                                DAG.getIntPtrConstant(4, DL));
12564
12565     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12566     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12567
12568     // The PSHUFB mask:
12569     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12570                                    -1, -1, -1, -1, -1, -1, -1, -1};
12571
12572     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12573     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12574     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12575
12576     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12577     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12578
12579     // The MOVLHPS Mask:
12580     static const int ShufMask2[] = {0, 1, 4, 5};
12581     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12582     return DAG.getBitcast(MVT::v8i16, res);
12583   }
12584
12585   // Handle truncation of V256 to V128 using shuffles.
12586   if (!VT.is128BitVector() || !InVT.is256BitVector())
12587     return SDValue();
12588
12589   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12590
12591   unsigned NumElems = VT.getVectorNumElements();
12592   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12593
12594   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12595   // Prepare truncation shuffle mask
12596   for (unsigned i = 0; i != NumElems; ++i)
12597     MaskVec[i] = i * 2;
12598   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12599                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12600   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12601                      DAG.getIntPtrConstant(0, DL));
12602 }
12603
12604 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12605                                            SelectionDAG &DAG) const {
12606   assert(!Op.getSimpleValueType().isVector());
12607
12608   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12609     /*IsSigned=*/ true, /*IsReplace=*/ false);
12610   SDValue FIST = Vals.first, StackSlot = Vals.second;
12611   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12612   if (!FIST.getNode()) return Op;
12613
12614   if (StackSlot.getNode())
12615     // Load the result.
12616     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12617                        FIST, StackSlot, MachinePointerInfo(),
12618                        false, false, false, 0);
12619
12620   // The node is the result.
12621   return FIST;
12622 }
12623
12624 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12625                                            SelectionDAG &DAG) const {
12626   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12627     /*IsSigned=*/ false, /*IsReplace=*/ false);
12628   SDValue FIST = Vals.first, StackSlot = Vals.second;
12629   assert(FIST.getNode() && "Unexpected failure");
12630
12631   if (StackSlot.getNode())
12632     // Load the result.
12633     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12634                        FIST, StackSlot, MachinePointerInfo(),
12635                        false, false, false, 0);
12636
12637   // The node is the result.
12638   return FIST;
12639 }
12640
12641 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12642   SDLoc DL(Op);
12643   MVT VT = Op.getSimpleValueType();
12644   SDValue In = Op.getOperand(0);
12645   MVT SVT = In.getSimpleValueType();
12646
12647   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12648
12649   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12650                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12651                                  In, DAG.getUNDEF(SVT)));
12652 }
12653
12654 /// The only differences between FABS and FNEG are the mask and the logic op.
12655 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12656 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12657   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12658          "Wrong opcode for lowering FABS or FNEG.");
12659
12660   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12661
12662   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12663   // into an FNABS. We'll lower the FABS after that if it is still in use.
12664   if (IsFABS)
12665     for (SDNode *User : Op->uses())
12666       if (User->getOpcode() == ISD::FNEG)
12667         return Op;
12668
12669   SDValue Op0 = Op.getOperand(0);
12670   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12671
12672   SDLoc dl(Op);
12673   MVT VT = Op.getSimpleValueType();
12674   // Assume scalar op for initialization; update for vector if needed.
12675   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12676   // generate a 16-byte vector constant and logic op even for the scalar case.
12677   // Using a 16-byte mask allows folding the load of the mask with
12678   // the logic op, so it can save (~4 bytes) on code size.
12679   MVT EltVT = VT;
12680   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12681   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12682   // decide if we should generate a 16-byte constant mask when we only need 4 or
12683   // 8 bytes for the scalar case.
12684   if (VT.isVector()) {
12685     EltVT = VT.getVectorElementType();
12686     NumElts = VT.getVectorNumElements();
12687   }
12688
12689   unsigned EltBits = EltVT.getSizeInBits();
12690   LLVMContext *Context = DAG.getContext();
12691   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12692   APInt MaskElt =
12693     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12694   Constant *C = ConstantInt::get(*Context, MaskElt);
12695   C = ConstantVector::getSplat(NumElts, C);
12696   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12697   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12698   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12699   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12700                              MachinePointerInfo::getConstantPool(),
12701                              false, false, false, Alignment);
12702
12703   if (VT.isVector()) {
12704     // For a vector, cast operands to a vector type, perform the logic op,
12705     // and cast the result back to the original value type.
12706     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12707     SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12708     SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12709                               : DAG.getBitcast(VecVT, Op0);
12710     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12711     return DAG.getBitcast(VT,
12712                           DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12713   }
12714
12715   // If not vector, then scalar.
12716   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12717   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12718   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12719 }
12720
12721 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12722   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12723   LLVMContext *Context = DAG.getContext();
12724   SDValue Op0 = Op.getOperand(0);
12725   SDValue Op1 = Op.getOperand(1);
12726   SDLoc dl(Op);
12727   MVT VT = Op.getSimpleValueType();
12728   MVT SrcVT = Op1.getSimpleValueType();
12729
12730   // If second operand is smaller, extend it first.
12731   if (SrcVT.bitsLT(VT)) {
12732     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12733     SrcVT = VT;
12734   }
12735   // And if it is bigger, shrink it first.
12736   if (SrcVT.bitsGT(VT)) {
12737     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12738     SrcVT = VT;
12739   }
12740
12741   // At this point the operands and the result should have the same
12742   // type, and that won't be f80 since that is not custom lowered.
12743
12744   const fltSemantics &Sem =
12745       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12746   const unsigned SizeInBits = VT.getSizeInBits();
12747
12748   SmallVector<Constant *, 4> CV(
12749       VT == MVT::f64 ? 2 : 4,
12750       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12751
12752   // First, clear all bits but the sign bit from the second operand (sign).
12753   CV[0] = ConstantFP::get(*Context,
12754                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12755   Constant *C = ConstantVector::get(CV);
12756   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12757   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12758   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12759                               MachinePointerInfo::getConstantPool(),
12760                               false, false, false, 16);
12761   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12762
12763   // Next, clear the sign bit from the first operand (magnitude).
12764   // If it's a constant, we can clear it here.
12765   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12766     APFloat APF = Op0CN->getValueAPF();
12767     // If the magnitude is a positive zero, the sign bit alone is enough.
12768     if (APF.isPosZero())
12769       return SignBit;
12770     APF.clearSign();
12771     CV[0] = ConstantFP::get(*Context, APF);
12772   } else {
12773     CV[0] = ConstantFP::get(
12774         *Context,
12775         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12776   }
12777   C = ConstantVector::get(CV);
12778   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12779   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12780                             MachinePointerInfo::getConstantPool(),
12781                             false, false, false, 16);
12782   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12783   if (!isa<ConstantFPSDNode>(Op0))
12784     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12785
12786   // OR the magnitude value with the sign bit.
12787   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12788 }
12789
12790 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12791   SDValue N0 = Op.getOperand(0);
12792   SDLoc dl(Op);
12793   MVT VT = Op.getSimpleValueType();
12794
12795   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12796   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12797                                   DAG.getConstant(1, dl, VT));
12798   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12799 }
12800
12801 // Check whether an OR'd tree is PTEST-able.
12802 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12803                                       SelectionDAG &DAG) {
12804   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12805
12806   if (!Subtarget->hasSSE41())
12807     return SDValue();
12808
12809   if (!Op->hasOneUse())
12810     return SDValue();
12811
12812   SDNode *N = Op.getNode();
12813   SDLoc DL(N);
12814
12815   SmallVector<SDValue, 8> Opnds;
12816   DenseMap<SDValue, unsigned> VecInMap;
12817   SmallVector<SDValue, 8> VecIns;
12818   EVT VT = MVT::Other;
12819
12820   // Recognize a special case where a vector is casted into wide integer to
12821   // test all 0s.
12822   Opnds.push_back(N->getOperand(0));
12823   Opnds.push_back(N->getOperand(1));
12824
12825   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12826     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12827     // BFS traverse all OR'd operands.
12828     if (I->getOpcode() == ISD::OR) {
12829       Opnds.push_back(I->getOperand(0));
12830       Opnds.push_back(I->getOperand(1));
12831       // Re-evaluate the number of nodes to be traversed.
12832       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12833       continue;
12834     }
12835
12836     // Quit if a non-EXTRACT_VECTOR_ELT
12837     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12838       return SDValue();
12839
12840     // Quit if without a constant index.
12841     SDValue Idx = I->getOperand(1);
12842     if (!isa<ConstantSDNode>(Idx))
12843       return SDValue();
12844
12845     SDValue ExtractedFromVec = I->getOperand(0);
12846     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12847     if (M == VecInMap.end()) {
12848       VT = ExtractedFromVec.getValueType();
12849       // Quit if not 128/256-bit vector.
12850       if (!VT.is128BitVector() && !VT.is256BitVector())
12851         return SDValue();
12852       // Quit if not the same type.
12853       if (VecInMap.begin() != VecInMap.end() &&
12854           VT != VecInMap.begin()->first.getValueType())
12855         return SDValue();
12856       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12857       VecIns.push_back(ExtractedFromVec);
12858     }
12859     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12860   }
12861
12862   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12863          "Not extracted from 128-/256-bit vector.");
12864
12865   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12866
12867   for (DenseMap<SDValue, unsigned>::const_iterator
12868         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12869     // Quit if not all elements are used.
12870     if (I->second != FullMask)
12871       return SDValue();
12872   }
12873
12874   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12875
12876   // Cast all vectors into TestVT for PTEST.
12877   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12878     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12879
12880   // If more than one full vectors are evaluated, OR them first before PTEST.
12881   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12882     // Each iteration will OR 2 nodes and append the result until there is only
12883     // 1 node left, i.e. the final OR'd value of all vectors.
12884     SDValue LHS = VecIns[Slot];
12885     SDValue RHS = VecIns[Slot + 1];
12886     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12887   }
12888
12889   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12890                      VecIns.back(), VecIns.back());
12891 }
12892
12893 /// \brief return true if \c Op has a use that doesn't just read flags.
12894 static bool hasNonFlagsUse(SDValue Op) {
12895   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12896        ++UI) {
12897     SDNode *User = *UI;
12898     unsigned UOpNo = UI.getOperandNo();
12899     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12900       // Look pass truncate.
12901       UOpNo = User->use_begin().getOperandNo();
12902       User = *User->use_begin();
12903     }
12904
12905     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12906         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12907       return true;
12908   }
12909   return false;
12910 }
12911
12912 /// Emit nodes that will be selected as "test Op0,Op0", or something
12913 /// equivalent.
12914 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12915                                     SelectionDAG &DAG) const {
12916   if (Op.getValueType() == MVT::i1) {
12917     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12918     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12919                        DAG.getConstant(0, dl, MVT::i8));
12920   }
12921   // CF and OF aren't always set the way we want. Determine which
12922   // of these we need.
12923   bool NeedCF = false;
12924   bool NeedOF = false;
12925   switch (X86CC) {
12926   default: break;
12927   case X86::COND_A: case X86::COND_AE:
12928   case X86::COND_B: case X86::COND_BE:
12929     NeedCF = true;
12930     break;
12931   case X86::COND_G: case X86::COND_GE:
12932   case X86::COND_L: case X86::COND_LE:
12933   case X86::COND_O: case X86::COND_NO: {
12934     // Check if we really need to set the
12935     // Overflow flag. If NoSignedWrap is present
12936     // that is not actually needed.
12937     switch (Op->getOpcode()) {
12938     case ISD::ADD:
12939     case ISD::SUB:
12940     case ISD::MUL:
12941     case ISD::SHL: {
12942       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12943       if (BinNode->Flags.hasNoSignedWrap())
12944         break;
12945     }
12946     default:
12947       NeedOF = true;
12948       break;
12949     }
12950     break;
12951   }
12952   }
12953   // See if we can use the EFLAGS value from the operand instead of
12954   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12955   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12956   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12957     // Emit a CMP with 0, which is the TEST pattern.
12958     //if (Op.getValueType() == MVT::i1)
12959     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12960     //                     DAG.getConstant(0, MVT::i1));
12961     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12962                        DAG.getConstant(0, dl, Op.getValueType()));
12963   }
12964   unsigned Opcode = 0;
12965   unsigned NumOperands = 0;
12966
12967   // Truncate operations may prevent the merge of the SETCC instruction
12968   // and the arithmetic instruction before it. Attempt to truncate the operands
12969   // of the arithmetic instruction and use a reduced bit-width instruction.
12970   bool NeedTruncation = false;
12971   SDValue ArithOp = Op;
12972   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12973     SDValue Arith = Op->getOperand(0);
12974     // Both the trunc and the arithmetic op need to have one user each.
12975     if (Arith->hasOneUse())
12976       switch (Arith.getOpcode()) {
12977         default: break;
12978         case ISD::ADD:
12979         case ISD::SUB:
12980         case ISD::AND:
12981         case ISD::OR:
12982         case ISD::XOR: {
12983           NeedTruncation = true;
12984           ArithOp = Arith;
12985         }
12986       }
12987   }
12988
12989   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12990   // which may be the result of a CAST.  We use the variable 'Op', which is the
12991   // non-casted variable when we check for possible users.
12992   switch (ArithOp.getOpcode()) {
12993   case ISD::ADD:
12994     // Due to an isel shortcoming, be conservative if this add is likely to be
12995     // selected as part of a load-modify-store instruction. When the root node
12996     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12997     // uses of other nodes in the match, such as the ADD in this case. This
12998     // leads to the ADD being left around and reselected, with the result being
12999     // two adds in the output.  Alas, even if none our users are stores, that
13000     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13001     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13002     // climbing the DAG back to the root, and it doesn't seem to be worth the
13003     // effort.
13004     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13005          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13006       if (UI->getOpcode() != ISD::CopyToReg &&
13007           UI->getOpcode() != ISD::SETCC &&
13008           UI->getOpcode() != ISD::STORE)
13009         goto default_case;
13010
13011     if (ConstantSDNode *C =
13012         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13013       // An add of one will be selected as an INC.
13014       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13015         Opcode = X86ISD::INC;
13016         NumOperands = 1;
13017         break;
13018       }
13019
13020       // An add of negative one (subtract of one) will be selected as a DEC.
13021       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13022         Opcode = X86ISD::DEC;
13023         NumOperands = 1;
13024         break;
13025       }
13026     }
13027
13028     // Otherwise use a regular EFLAGS-setting add.
13029     Opcode = X86ISD::ADD;
13030     NumOperands = 2;
13031     break;
13032   case ISD::SHL:
13033   case ISD::SRL:
13034     // If we have a constant logical shift that's only used in a comparison
13035     // against zero turn it into an equivalent AND. This allows turning it into
13036     // a TEST instruction later.
13037     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13038         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13039       EVT VT = Op.getValueType();
13040       unsigned BitWidth = VT.getSizeInBits();
13041       unsigned ShAmt = Op->getConstantOperandVal(1);
13042       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13043         break;
13044       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13045                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13046                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13047       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13048         break;
13049       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13050                                 DAG.getConstant(Mask, dl, VT));
13051       DAG.ReplaceAllUsesWith(Op, New);
13052       Op = New;
13053     }
13054     break;
13055
13056   case ISD::AND:
13057     // If the primary and result isn't used, don't bother using X86ISD::AND,
13058     // because a TEST instruction will be better.
13059     if (!hasNonFlagsUse(Op))
13060       break;
13061     // FALL THROUGH
13062   case ISD::SUB:
13063   case ISD::OR:
13064   case ISD::XOR:
13065     // Due to the ISEL shortcoming noted above, be conservative if this op is
13066     // likely to be selected as part of a load-modify-store instruction.
13067     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13068            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13069       if (UI->getOpcode() == ISD::STORE)
13070         goto default_case;
13071
13072     // Otherwise use a regular EFLAGS-setting instruction.
13073     switch (ArithOp.getOpcode()) {
13074     default: llvm_unreachable("unexpected operator!");
13075     case ISD::SUB: Opcode = X86ISD::SUB; break;
13076     case ISD::XOR: Opcode = X86ISD::XOR; break;
13077     case ISD::AND: Opcode = X86ISD::AND; break;
13078     case ISD::OR: {
13079       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13080         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13081         if (EFLAGS.getNode())
13082           return EFLAGS;
13083       }
13084       Opcode = X86ISD::OR;
13085       break;
13086     }
13087     }
13088
13089     NumOperands = 2;
13090     break;
13091   case X86ISD::ADD:
13092   case X86ISD::SUB:
13093   case X86ISD::INC:
13094   case X86ISD::DEC:
13095   case X86ISD::OR:
13096   case X86ISD::XOR:
13097   case X86ISD::AND:
13098     return SDValue(Op.getNode(), 1);
13099   default:
13100   default_case:
13101     break;
13102   }
13103
13104   // If we found that truncation is beneficial, perform the truncation and
13105   // update 'Op'.
13106   if (NeedTruncation) {
13107     EVT VT = Op.getValueType();
13108     SDValue WideVal = Op->getOperand(0);
13109     EVT WideVT = WideVal.getValueType();
13110     unsigned ConvertedOp = 0;
13111     // Use a target machine opcode to prevent further DAGCombine
13112     // optimizations that may separate the arithmetic operations
13113     // from the setcc node.
13114     switch (WideVal.getOpcode()) {
13115       default: break;
13116       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13117       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13118       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13119       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13120       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13121     }
13122
13123     if (ConvertedOp) {
13124       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13125       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13126         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13127         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13128         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13129       }
13130     }
13131   }
13132
13133   if (Opcode == 0)
13134     // Emit a CMP with 0, which is the TEST pattern.
13135     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13136                        DAG.getConstant(0, dl, Op.getValueType()));
13137
13138   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13139   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13140
13141   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13142   DAG.ReplaceAllUsesWith(Op, New);
13143   return SDValue(New.getNode(), 1);
13144 }
13145
13146 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13147 /// equivalent.
13148 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13149                                    SDLoc dl, SelectionDAG &DAG) const {
13150   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13151     if (C->getAPIntValue() == 0)
13152       return EmitTest(Op0, X86CC, dl, DAG);
13153
13154      if (Op0.getValueType() == MVT::i1)
13155        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13156   }
13157
13158   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13159        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13160     // Do the comparison at i32 if it's smaller, besides the Atom case.
13161     // This avoids subregister aliasing issues. Keep the smaller reference
13162     // if we're optimizing for size, however, as that'll allow better folding
13163     // of memory operations.
13164     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13165         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13166             Attribute::MinSize) &&
13167         !Subtarget->isAtom()) {
13168       unsigned ExtendOp =
13169           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13170       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13171       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13172     }
13173     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13174     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13175     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13176                               Op0, Op1);
13177     return SDValue(Sub.getNode(), 1);
13178   }
13179   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13180 }
13181
13182 /// Convert a comparison if required by the subtarget.
13183 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13184                                                  SelectionDAG &DAG) const {
13185   // If the subtarget does not support the FUCOMI instruction, floating-point
13186   // comparisons have to be converted.
13187   if (Subtarget->hasCMov() ||
13188       Cmp.getOpcode() != X86ISD::CMP ||
13189       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13190       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13191     return Cmp;
13192
13193   // The instruction selector will select an FUCOM instruction instead of
13194   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13195   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13196   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13197   SDLoc dl(Cmp);
13198   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13199   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13200   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13201                             DAG.getConstant(8, dl, MVT::i8));
13202   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13203   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13204 }
13205
13206 /// The minimum architected relative accuracy is 2^-12. We need one
13207 /// Newton-Raphson step to have a good float result (24 bits of precision).
13208 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13209                                             DAGCombinerInfo &DCI,
13210                                             unsigned &RefinementSteps,
13211                                             bool &UseOneConstNR) const {
13212   EVT VT = Op.getValueType();
13213   const char *RecipOp;
13214
13215   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13216   // TODO: Add support for AVX512 (v16f32).
13217   // It is likely not profitable to do this for f64 because a double-precision
13218   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13219   // instructions: convert to single, rsqrtss, convert back to double, refine
13220   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13221   // along with FMA, this could be a throughput win.
13222   if (VT == MVT::f32 && Subtarget->hasSSE1())
13223     RecipOp = "sqrtf";
13224   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13225            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13226     RecipOp = "vec-sqrtf";
13227   else
13228     return SDValue();
13229
13230   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13231   if (!Recips.isEnabled(RecipOp))
13232     return SDValue();
13233
13234   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13235   UseOneConstNR = false;
13236   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13237 }
13238
13239 /// The minimum architected relative accuracy is 2^-12. We need one
13240 /// Newton-Raphson step to have a good float result (24 bits of precision).
13241 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13242                                             DAGCombinerInfo &DCI,
13243                                             unsigned &RefinementSteps) const {
13244   EVT VT = Op.getValueType();
13245   const char *RecipOp;
13246
13247   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13248   // TODO: Add support for AVX512 (v16f32).
13249   // It is likely not profitable to do this for f64 because a double-precision
13250   // reciprocal estimate with refinement on x86 prior to FMA requires
13251   // 15 instructions: convert to single, rcpss, convert back to double, refine
13252   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13253   // along with FMA, this could be a throughput win.
13254   if (VT == MVT::f32 && Subtarget->hasSSE1())
13255     RecipOp = "divf";
13256   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13257            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13258     RecipOp = "vec-divf";
13259   else
13260     return SDValue();
13261
13262   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13263   if (!Recips.isEnabled(RecipOp))
13264     return SDValue();
13265
13266   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13267   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13268 }
13269
13270 /// If we have at least two divisions that use the same divisor, convert to
13271 /// multplication by a reciprocal. This may need to be adjusted for a given
13272 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13273 /// This is because we still need one division to calculate the reciprocal and
13274 /// then we need two multiplies by that reciprocal as replacements for the
13275 /// original divisions.
13276 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13277   return NumUsers > 1;
13278 }
13279
13280 static bool isAllOnes(SDValue V) {
13281   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13282   return C && C->isAllOnesValue();
13283 }
13284
13285 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13286 /// if it's possible.
13287 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13288                                      SDLoc dl, SelectionDAG &DAG) const {
13289   SDValue Op0 = And.getOperand(0);
13290   SDValue Op1 = And.getOperand(1);
13291   if (Op0.getOpcode() == ISD::TRUNCATE)
13292     Op0 = Op0.getOperand(0);
13293   if (Op1.getOpcode() == ISD::TRUNCATE)
13294     Op1 = Op1.getOperand(0);
13295
13296   SDValue LHS, RHS;
13297   if (Op1.getOpcode() == ISD::SHL)
13298     std::swap(Op0, Op1);
13299   if (Op0.getOpcode() == ISD::SHL) {
13300     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13301       if (And00C->getZExtValue() == 1) {
13302         // If we looked past a truncate, check that it's only truncating away
13303         // known zeros.
13304         unsigned BitWidth = Op0.getValueSizeInBits();
13305         unsigned AndBitWidth = And.getValueSizeInBits();
13306         if (BitWidth > AndBitWidth) {
13307           APInt Zeros, Ones;
13308           DAG.computeKnownBits(Op0, Zeros, Ones);
13309           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13310             return SDValue();
13311         }
13312         LHS = Op1;
13313         RHS = Op0.getOperand(1);
13314       }
13315   } else if (Op1.getOpcode() == ISD::Constant) {
13316     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13317     uint64_t AndRHSVal = AndRHS->getZExtValue();
13318     SDValue AndLHS = Op0;
13319
13320     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13321       LHS = AndLHS.getOperand(0);
13322       RHS = AndLHS.getOperand(1);
13323     }
13324
13325     // Use BT if the immediate can't be encoded in a TEST instruction.
13326     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13327       LHS = AndLHS;
13328       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13329     }
13330   }
13331
13332   if (LHS.getNode()) {
13333     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13334     // instruction.  Since the shift amount is in-range-or-undefined, we know
13335     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13336     // the encoding for the i16 version is larger than the i32 version.
13337     // Also promote i16 to i32 for performance / code size reason.
13338     if (LHS.getValueType() == MVT::i8 ||
13339         LHS.getValueType() == MVT::i16)
13340       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13341
13342     // If the operand types disagree, extend the shift amount to match.  Since
13343     // BT ignores high bits (like shifts) we can use anyextend.
13344     if (LHS.getValueType() != RHS.getValueType())
13345       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13346
13347     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13348     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13349     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13350                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13351   }
13352
13353   return SDValue();
13354 }
13355
13356 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13357 /// mask CMPs.
13358 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13359                               SDValue &Op1) {
13360   unsigned SSECC;
13361   bool Swap = false;
13362
13363   // SSE Condition code mapping:
13364   //  0 - EQ
13365   //  1 - LT
13366   //  2 - LE
13367   //  3 - UNORD
13368   //  4 - NEQ
13369   //  5 - NLT
13370   //  6 - NLE
13371   //  7 - ORD
13372   switch (SetCCOpcode) {
13373   default: llvm_unreachable("Unexpected SETCC condition");
13374   case ISD::SETOEQ:
13375   case ISD::SETEQ:  SSECC = 0; break;
13376   case ISD::SETOGT:
13377   case ISD::SETGT:  Swap = true; // Fallthrough
13378   case ISD::SETLT:
13379   case ISD::SETOLT: SSECC = 1; break;
13380   case ISD::SETOGE:
13381   case ISD::SETGE:  Swap = true; // Fallthrough
13382   case ISD::SETLE:
13383   case ISD::SETOLE: SSECC = 2; break;
13384   case ISD::SETUO:  SSECC = 3; break;
13385   case ISD::SETUNE:
13386   case ISD::SETNE:  SSECC = 4; break;
13387   case ISD::SETULE: Swap = true; // Fallthrough
13388   case ISD::SETUGE: SSECC = 5; break;
13389   case ISD::SETULT: Swap = true; // Fallthrough
13390   case ISD::SETUGT: SSECC = 6; break;
13391   case ISD::SETO:   SSECC = 7; break;
13392   case ISD::SETUEQ:
13393   case ISD::SETONE: SSECC = 8; break;
13394   }
13395   if (Swap)
13396     std::swap(Op0, Op1);
13397
13398   return SSECC;
13399 }
13400
13401 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13402 // ones, and then concatenate the result back.
13403 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13404   MVT VT = Op.getSimpleValueType();
13405
13406   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13407          "Unsupported value type for operation");
13408
13409   unsigned NumElems = VT.getVectorNumElements();
13410   SDLoc dl(Op);
13411   SDValue CC = Op.getOperand(2);
13412
13413   // Extract the LHS vectors
13414   SDValue LHS = Op.getOperand(0);
13415   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13416   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13417
13418   // Extract the RHS vectors
13419   SDValue RHS = Op.getOperand(1);
13420   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13421   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13422
13423   // Issue the operation on the smaller types and concatenate the result back
13424   MVT EltVT = VT.getVectorElementType();
13425   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13426   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13427                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13428                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13429 }
13430
13431 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13432   SDValue Op0 = Op.getOperand(0);
13433   SDValue Op1 = Op.getOperand(1);
13434   SDValue CC = Op.getOperand(2);
13435   MVT VT = Op.getSimpleValueType();
13436   SDLoc dl(Op);
13437
13438   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13439          "Unexpected type for boolean compare operation");
13440   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13441   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13442                                DAG.getConstant(-1, dl, VT));
13443   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13444                                DAG.getConstant(-1, dl, VT));
13445   switch (SetCCOpcode) {
13446   default: llvm_unreachable("Unexpected SETCC condition");
13447   case ISD::SETEQ:
13448     // (x == y) -> ~(x ^ y)
13449     return DAG.getNode(ISD::XOR, dl, VT,
13450                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13451                        DAG.getConstant(-1, dl, VT));
13452   case ISD::SETNE:
13453     // (x != y) -> (x ^ y)
13454     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13455   case ISD::SETUGT:
13456   case ISD::SETGT:
13457     // (x > y) -> (x & ~y)
13458     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13459   case ISD::SETULT:
13460   case ISD::SETLT:
13461     // (x < y) -> (~x & y)
13462     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13463   case ISD::SETULE:
13464   case ISD::SETLE:
13465     // (x <= y) -> (~x | y)
13466     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13467   case ISD::SETUGE:
13468   case ISD::SETGE:
13469     // (x >=y) -> (x | ~y)
13470     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13471   }
13472 }
13473
13474 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13475                                      const X86Subtarget *Subtarget) {
13476   SDValue Op0 = Op.getOperand(0);
13477   SDValue Op1 = Op.getOperand(1);
13478   SDValue CC = Op.getOperand(2);
13479   MVT VT = Op.getSimpleValueType();
13480   SDLoc dl(Op);
13481
13482   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13483          Op.getValueType().getScalarType() == MVT::i1 &&
13484          "Cannot set masked compare for this operation");
13485
13486   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13487   unsigned  Opc = 0;
13488   bool Unsigned = false;
13489   bool Swap = false;
13490   unsigned SSECC;
13491   switch (SetCCOpcode) {
13492   default: llvm_unreachable("Unexpected SETCC condition");
13493   case ISD::SETNE:  SSECC = 4; break;
13494   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13495   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13496   case ISD::SETLT:  Swap = true; //fall-through
13497   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13498   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13499   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13500   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13501   case ISD::SETULE: Unsigned = true; //fall-through
13502   case ISD::SETLE:  SSECC = 2; break;
13503   }
13504
13505   if (Swap)
13506     std::swap(Op0, Op1);
13507   if (Opc)
13508     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13509   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13510   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13511                      DAG.getConstant(SSECC, dl, MVT::i8));
13512 }
13513
13514 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13515 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13516 /// return an empty value.
13517 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13518 {
13519   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13520   if (!BV)
13521     return SDValue();
13522
13523   MVT VT = Op1.getSimpleValueType();
13524   MVT EVT = VT.getVectorElementType();
13525   unsigned n = VT.getVectorNumElements();
13526   SmallVector<SDValue, 8> ULTOp1;
13527
13528   for (unsigned i = 0; i < n; ++i) {
13529     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13530     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13531       return SDValue();
13532
13533     // Avoid underflow.
13534     APInt Val = Elt->getAPIntValue();
13535     if (Val == 0)
13536       return SDValue();
13537
13538     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13539   }
13540
13541   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13542 }
13543
13544 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13545                            SelectionDAG &DAG) {
13546   SDValue Op0 = Op.getOperand(0);
13547   SDValue Op1 = Op.getOperand(1);
13548   SDValue CC = Op.getOperand(2);
13549   MVT VT = Op.getSimpleValueType();
13550   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13551   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13552   SDLoc dl(Op);
13553
13554   if (isFP) {
13555 #ifndef NDEBUG
13556     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13557     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13558 #endif
13559
13560     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13561     unsigned Opc = X86ISD::CMPP;
13562     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13563       assert(VT.getVectorNumElements() <= 16);
13564       Opc = X86ISD::CMPM;
13565     }
13566     // In the two special cases we can't handle, emit two comparisons.
13567     if (SSECC == 8) {
13568       unsigned CC0, CC1;
13569       unsigned CombineOpc;
13570       if (SetCCOpcode == ISD::SETUEQ) {
13571         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13572       } else {
13573         assert(SetCCOpcode == ISD::SETONE);
13574         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13575       }
13576
13577       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13578                                  DAG.getConstant(CC0, dl, MVT::i8));
13579       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13580                                  DAG.getConstant(CC1, dl, MVT::i8));
13581       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13582     }
13583     // Handle all other FP comparisons here.
13584     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13585                        DAG.getConstant(SSECC, dl, MVT::i8));
13586   }
13587
13588   // Break 256-bit integer vector compare into smaller ones.
13589   if (VT.is256BitVector() && !Subtarget->hasInt256())
13590     return Lower256IntVSETCC(Op, DAG);
13591
13592   EVT OpVT = Op1.getValueType();
13593   if (OpVT.getVectorElementType() == MVT::i1)
13594     return LowerBoolVSETCC_AVX512(Op, DAG);
13595
13596   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13597   if (Subtarget->hasAVX512()) {
13598     if (Op1.getValueType().is512BitVector() ||
13599         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13600         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13601       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13602
13603     // In AVX-512 architecture setcc returns mask with i1 elements,
13604     // But there is no compare instruction for i8 and i16 elements in KNL.
13605     // We are not talking about 512-bit operands in this case, these
13606     // types are illegal.
13607     if (MaskResult &&
13608         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13609          OpVT.getVectorElementType().getSizeInBits() >= 8))
13610       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13611                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13612   }
13613
13614   // We are handling one of the integer comparisons here.  Since SSE only has
13615   // GT and EQ comparisons for integer, swapping operands and multiple
13616   // operations may be required for some comparisons.
13617   unsigned Opc;
13618   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13619   bool Subus = false;
13620
13621   switch (SetCCOpcode) {
13622   default: llvm_unreachable("Unexpected SETCC condition");
13623   case ISD::SETNE:  Invert = true;
13624   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13625   case ISD::SETLT:  Swap = true;
13626   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13627   case ISD::SETGE:  Swap = true;
13628   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13629                     Invert = true; break;
13630   case ISD::SETULT: Swap = true;
13631   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13632                     FlipSigns = true; break;
13633   case ISD::SETUGE: Swap = true;
13634   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13635                     FlipSigns = true; Invert = true; break;
13636   }
13637
13638   // Special case: Use min/max operations for SETULE/SETUGE
13639   MVT VET = VT.getVectorElementType();
13640   bool hasMinMax =
13641        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13642     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13643
13644   if (hasMinMax) {
13645     switch (SetCCOpcode) {
13646     default: break;
13647     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13648     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13649     }
13650
13651     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13652   }
13653
13654   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13655   if (!MinMax && hasSubus) {
13656     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13657     // Op0 u<= Op1:
13658     //   t = psubus Op0, Op1
13659     //   pcmpeq t, <0..0>
13660     switch (SetCCOpcode) {
13661     default: break;
13662     case ISD::SETULT: {
13663       // If the comparison is against a constant we can turn this into a
13664       // setule.  With psubus, setule does not require a swap.  This is
13665       // beneficial because the constant in the register is no longer
13666       // destructed as the destination so it can be hoisted out of a loop.
13667       // Only do this pre-AVX since vpcmp* is no longer destructive.
13668       if (Subtarget->hasAVX())
13669         break;
13670       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13671       if (ULEOp1.getNode()) {
13672         Op1 = ULEOp1;
13673         Subus = true; Invert = false; Swap = false;
13674       }
13675       break;
13676     }
13677     // Psubus is better than flip-sign because it requires no inversion.
13678     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13679     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13680     }
13681
13682     if (Subus) {
13683       Opc = X86ISD::SUBUS;
13684       FlipSigns = false;
13685     }
13686   }
13687
13688   if (Swap)
13689     std::swap(Op0, Op1);
13690
13691   // Check that the operation in question is available (most are plain SSE2,
13692   // but PCMPGTQ and PCMPEQQ have different requirements).
13693   if (VT == MVT::v2i64) {
13694     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13695       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13696
13697       // First cast everything to the right type.
13698       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13699       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13700
13701       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13702       // bits of the inputs before performing those operations. The lower
13703       // compare is always unsigned.
13704       SDValue SB;
13705       if (FlipSigns) {
13706         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13707       } else {
13708         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13709         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13710         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13711                          Sign, Zero, Sign, Zero);
13712       }
13713       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13714       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13715
13716       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13717       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13718       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13719
13720       // Create masks for only the low parts/high parts of the 64 bit integers.
13721       static const int MaskHi[] = { 1, 1, 3, 3 };
13722       static const int MaskLo[] = { 0, 0, 2, 2 };
13723       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13724       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13725       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13726
13727       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13728       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13729
13730       if (Invert)
13731         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13732
13733       return DAG.getBitcast(VT, Result);
13734     }
13735
13736     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13737       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13738       // pcmpeqd + pshufd + pand.
13739       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13740
13741       // First cast everything to the right type.
13742       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13743       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13744
13745       // Do the compare.
13746       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13747
13748       // Make sure the lower and upper halves are both all-ones.
13749       static const int Mask[] = { 1, 0, 3, 2 };
13750       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13751       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13752
13753       if (Invert)
13754         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13755
13756       return DAG.getBitcast(VT, Result);
13757     }
13758   }
13759
13760   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13761   // bits of the inputs before performing those operations.
13762   if (FlipSigns) {
13763     EVT EltVT = VT.getVectorElementType();
13764     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13765                                  VT);
13766     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13767     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13768   }
13769
13770   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13771
13772   // If the logical-not of the result is required, perform that now.
13773   if (Invert)
13774     Result = DAG.getNOT(dl, Result, VT);
13775
13776   if (MinMax)
13777     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13778
13779   if (Subus)
13780     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13781                          getZeroVector(VT, Subtarget, DAG, dl));
13782
13783   return Result;
13784 }
13785
13786 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13787
13788   MVT VT = Op.getSimpleValueType();
13789
13790   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13791
13792   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13793          && "SetCC type must be 8-bit or 1-bit integer");
13794   SDValue Op0 = Op.getOperand(0);
13795   SDValue Op1 = Op.getOperand(1);
13796   SDLoc dl(Op);
13797   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13798
13799   // Optimize to BT if possible.
13800   // Lower (X & (1 << N)) == 0 to BT(X, N).
13801   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13802   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13803   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13804       Op1.getOpcode() == ISD::Constant &&
13805       cast<ConstantSDNode>(Op1)->isNullValue() &&
13806       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13807     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13808     if (NewSetCC.getNode()) {
13809       if (VT == MVT::i1)
13810         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13811       return NewSetCC;
13812     }
13813   }
13814
13815   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13816   // these.
13817   if (Op1.getOpcode() == ISD::Constant &&
13818       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13819        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13820       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13821
13822     // If the input is a setcc, then reuse the input setcc or use a new one with
13823     // the inverted condition.
13824     if (Op0.getOpcode() == X86ISD::SETCC) {
13825       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13826       bool Invert = (CC == ISD::SETNE) ^
13827         cast<ConstantSDNode>(Op1)->isNullValue();
13828       if (!Invert)
13829         return Op0;
13830
13831       CCode = X86::GetOppositeBranchCondition(CCode);
13832       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13833                                   DAG.getConstant(CCode, dl, MVT::i8),
13834                                   Op0.getOperand(1));
13835       if (VT == MVT::i1)
13836         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13837       return SetCC;
13838     }
13839   }
13840   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13841       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13842       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13843
13844     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13845     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13846   }
13847
13848   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13849   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13850   if (X86CC == X86::COND_INVALID)
13851     return SDValue();
13852
13853   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13854   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13855   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13856                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13857   if (VT == MVT::i1)
13858     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13859   return SetCC;
13860 }
13861
13862 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13863 static bool isX86LogicalCmp(SDValue Op) {
13864   unsigned Opc = Op.getNode()->getOpcode();
13865   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13866       Opc == X86ISD::SAHF)
13867     return true;
13868   if (Op.getResNo() == 1 &&
13869       (Opc == X86ISD::ADD ||
13870        Opc == X86ISD::SUB ||
13871        Opc == X86ISD::ADC ||
13872        Opc == X86ISD::SBB ||
13873        Opc == X86ISD::SMUL ||
13874        Opc == X86ISD::UMUL ||
13875        Opc == X86ISD::INC ||
13876        Opc == X86ISD::DEC ||
13877        Opc == X86ISD::OR ||
13878        Opc == X86ISD::XOR ||
13879        Opc == X86ISD::AND))
13880     return true;
13881
13882   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13883     return true;
13884
13885   return false;
13886 }
13887
13888 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13889   if (V.getOpcode() != ISD::TRUNCATE)
13890     return false;
13891
13892   SDValue VOp0 = V.getOperand(0);
13893   unsigned InBits = VOp0.getValueSizeInBits();
13894   unsigned Bits = V.getValueSizeInBits();
13895   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13896 }
13897
13898 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13899   bool addTest = true;
13900   SDValue Cond  = Op.getOperand(0);
13901   SDValue Op1 = Op.getOperand(1);
13902   SDValue Op2 = Op.getOperand(2);
13903   SDLoc DL(Op);
13904   EVT VT = Op1.getValueType();
13905   SDValue CC;
13906
13907   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13908   // are available or VBLENDV if AVX is available.
13909   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13910   if (Cond.getOpcode() == ISD::SETCC &&
13911       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13912        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13913       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13914     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13915     int SSECC = translateX86FSETCC(
13916         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13917
13918     if (SSECC != 8) {
13919       if (Subtarget->hasAVX512()) {
13920         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13921                                   DAG.getConstant(SSECC, DL, MVT::i8));
13922         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13923       }
13924
13925       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13926                                 DAG.getConstant(SSECC, DL, MVT::i8));
13927
13928       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13929       // of 3 logic instructions for size savings and potentially speed.
13930       // Unfortunately, there is no scalar form of VBLENDV.
13931
13932       // If either operand is a constant, don't try this. We can expect to
13933       // optimize away at least one of the logic instructions later in that
13934       // case, so that sequence would be faster than a variable blend.
13935
13936       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13937       // uses XMM0 as the selection register. That may need just as many
13938       // instructions as the AND/ANDN/OR sequence due to register moves, so
13939       // don't bother.
13940
13941       if (Subtarget->hasAVX() &&
13942           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13943
13944         // Convert to vectors, do a VSELECT, and convert back to scalar.
13945         // All of the conversions should be optimized away.
13946
13947         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13948         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13949         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13950         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13951
13952         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13953         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13954
13955         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13956
13957         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13958                            VSel, DAG.getIntPtrConstant(0, DL));
13959       }
13960       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13961       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13962       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13963     }
13964   }
13965
13966   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13967     SDValue Op1Scalar;
13968     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13969       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
13970     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13971       Op1Scalar = Op1.getOperand(0);
13972     SDValue Op2Scalar;
13973     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13974       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
13975     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13976       Op2Scalar = Op2.getOperand(0);
13977     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13978       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13979                                       Op1Scalar.getValueType(),
13980                                       Cond, Op1Scalar, Op2Scalar);
13981       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13982         return DAG.getBitcast(VT, newSelect);
13983       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
13984       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13985                          DAG.getIntPtrConstant(0, DL));
13986     }
13987   }
13988
13989   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13990     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13991     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13992                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13993     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13994                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13995     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13996                                     Cond, Op1, Op2);
13997     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13998   }
13999
14000   if (Cond.getOpcode() == ISD::SETCC) {
14001     SDValue NewCond = LowerSETCC(Cond, DAG);
14002     if (NewCond.getNode())
14003       Cond = NewCond;
14004   }
14005
14006   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14007   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14008   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14009   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14010   if (Cond.getOpcode() == X86ISD::SETCC &&
14011       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14012       isZero(Cond.getOperand(1).getOperand(1))) {
14013     SDValue Cmp = Cond.getOperand(1);
14014
14015     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14016
14017     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14018         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14019       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14020
14021       SDValue CmpOp0 = Cmp.getOperand(0);
14022       // Apply further optimizations for special cases
14023       // (select (x != 0), -1, 0) -> neg & sbb
14024       // (select (x == 0), 0, -1) -> neg & sbb
14025       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14026         if (YC->isNullValue() &&
14027             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14028           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14029           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14030                                     DAG.getConstant(0, DL,
14031                                                     CmpOp0.getValueType()),
14032                                     CmpOp0);
14033           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14034                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14035                                     SDValue(Neg.getNode(), 1));
14036           return Res;
14037         }
14038
14039       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14040                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14041       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14042
14043       SDValue Res =   // Res = 0 or -1.
14044         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14045                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14046
14047       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14048         Res = DAG.getNOT(DL, Res, Res.getValueType());
14049
14050       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14051       if (!N2C || !N2C->isNullValue())
14052         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14053       return Res;
14054     }
14055   }
14056
14057   // Look past (and (setcc_carry (cmp ...)), 1).
14058   if (Cond.getOpcode() == ISD::AND &&
14059       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14060     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14061     if (C && C->getAPIntValue() == 1)
14062       Cond = Cond.getOperand(0);
14063   }
14064
14065   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14066   // setting operand in place of the X86ISD::SETCC.
14067   unsigned CondOpcode = Cond.getOpcode();
14068   if (CondOpcode == X86ISD::SETCC ||
14069       CondOpcode == X86ISD::SETCC_CARRY) {
14070     CC = Cond.getOperand(0);
14071
14072     SDValue Cmp = Cond.getOperand(1);
14073     unsigned Opc = Cmp.getOpcode();
14074     MVT VT = Op.getSimpleValueType();
14075
14076     bool IllegalFPCMov = false;
14077     if (VT.isFloatingPoint() && !VT.isVector() &&
14078         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14079       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14080
14081     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14082         Opc == X86ISD::BT) { // FIXME
14083       Cond = Cmp;
14084       addTest = false;
14085     }
14086   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14087              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14088              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14089               Cond.getOperand(0).getValueType() != MVT::i8)) {
14090     SDValue LHS = Cond.getOperand(0);
14091     SDValue RHS = Cond.getOperand(1);
14092     unsigned X86Opcode;
14093     unsigned X86Cond;
14094     SDVTList VTs;
14095     switch (CondOpcode) {
14096     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14097     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14098     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14099     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14100     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14101     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14102     default: llvm_unreachable("unexpected overflowing operator");
14103     }
14104     if (CondOpcode == ISD::UMULO)
14105       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14106                           MVT::i32);
14107     else
14108       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14109
14110     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14111
14112     if (CondOpcode == ISD::UMULO)
14113       Cond = X86Op.getValue(2);
14114     else
14115       Cond = X86Op.getValue(1);
14116
14117     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14118     addTest = false;
14119   }
14120
14121   if (addTest) {
14122     // Look pass the truncate if the high bits are known zero.
14123     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14124         Cond = Cond.getOperand(0);
14125
14126     // We know the result of AND is compared against zero. Try to match
14127     // it to BT.
14128     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14129       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14130       if (NewSetCC.getNode()) {
14131         CC = NewSetCC.getOperand(0);
14132         Cond = NewSetCC.getOperand(1);
14133         addTest = false;
14134       }
14135     }
14136   }
14137
14138   if (addTest) {
14139     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14140     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14141   }
14142
14143   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14144   // a <  b ?  0 : -1 -> RES = setcc_carry
14145   // a >= b ? -1 :  0 -> RES = setcc_carry
14146   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14147   if (Cond.getOpcode() == X86ISD::SUB) {
14148     Cond = ConvertCmpIfNecessary(Cond, DAG);
14149     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14150
14151     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14152         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14153       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14154                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14155                                 Cond);
14156       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14157         return DAG.getNOT(DL, Res, Res.getValueType());
14158       return Res;
14159     }
14160   }
14161
14162   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14163   // widen the cmov and push the truncate through. This avoids introducing a new
14164   // branch during isel and doesn't add any extensions.
14165   if (Op.getValueType() == MVT::i8 &&
14166       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14167     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14168     if (T1.getValueType() == T2.getValueType() &&
14169         // Blacklist CopyFromReg to avoid partial register stalls.
14170         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14171       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14172       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14173       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14174     }
14175   }
14176
14177   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14178   // condition is true.
14179   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14180   SDValue Ops[] = { Op2, Op1, CC, Cond };
14181   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14182 }
14183
14184 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14185                                        const X86Subtarget *Subtarget,
14186                                        SelectionDAG &DAG) {
14187   MVT VT = Op->getSimpleValueType(0);
14188   SDValue In = Op->getOperand(0);
14189   MVT InVT = In.getSimpleValueType();
14190   MVT VTElt = VT.getVectorElementType();
14191   MVT InVTElt = InVT.getVectorElementType();
14192   SDLoc dl(Op);
14193
14194   // SKX processor
14195   if ((InVTElt == MVT::i1) &&
14196       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14197         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14198
14199        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14200         VTElt.getSizeInBits() <= 16)) ||
14201
14202        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14203         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14204
14205        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14206         VTElt.getSizeInBits() >= 32))))
14207     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14208
14209   unsigned int NumElts = VT.getVectorNumElements();
14210
14211   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14212     return SDValue();
14213
14214   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14215     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14216       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14217     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14218   }
14219
14220   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14221   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14222   SDValue NegOne =
14223    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14224                    ExtVT);
14225   SDValue Zero =
14226    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14227
14228   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14229   if (VT.is512BitVector())
14230     return V;
14231   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14232 }
14233
14234 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14235                                              const X86Subtarget *Subtarget,
14236                                              SelectionDAG &DAG) {
14237   SDValue In = Op->getOperand(0);
14238   MVT VT = Op->getSimpleValueType(0);
14239   MVT InVT = In.getSimpleValueType();
14240   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14241
14242   MVT InSVT = InVT.getScalarType();
14243   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14244
14245   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14246     return SDValue();
14247   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14248     return SDValue();
14249
14250   SDLoc dl(Op);
14251
14252   // SSE41 targets can use the pmovsx* instructions directly.
14253   if (Subtarget->hasSSE41())
14254     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14255
14256   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14257   SDValue Curr = In;
14258   MVT CurrVT = InVT;
14259
14260   // As SRAI is only available on i16/i32 types, we expand only up to i32
14261   // and handle i64 separately.
14262   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14263     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14264     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14265     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14266     Curr = DAG.getBitcast(CurrVT, Curr);
14267   }
14268
14269   SDValue SignExt = Curr;
14270   if (CurrVT != InVT) {
14271     unsigned SignExtShift =
14272         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14273     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14274                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14275   }
14276
14277   if (CurrVT == VT)
14278     return SignExt;
14279
14280   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14281     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14282                                DAG.getConstant(31, dl, MVT::i8));
14283     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14284     return DAG.getBitcast(VT, Ext);
14285   }
14286
14287   return SDValue();
14288 }
14289
14290 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14291                                 SelectionDAG &DAG) {
14292   MVT VT = Op->getSimpleValueType(0);
14293   SDValue In = Op->getOperand(0);
14294   MVT InVT = In.getSimpleValueType();
14295   SDLoc dl(Op);
14296
14297   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14298     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14299
14300   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14301       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14302       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14303     return SDValue();
14304
14305   if (Subtarget->hasInt256())
14306     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14307
14308   // Optimize vectors in AVX mode
14309   // Sign extend  v8i16 to v8i32 and
14310   //              v4i32 to v4i64
14311   //
14312   // Divide input vector into two parts
14313   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14314   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14315   // concat the vectors to original VT
14316
14317   unsigned NumElems = InVT.getVectorNumElements();
14318   SDValue Undef = DAG.getUNDEF(InVT);
14319
14320   SmallVector<int,8> ShufMask1(NumElems, -1);
14321   for (unsigned i = 0; i != NumElems/2; ++i)
14322     ShufMask1[i] = i;
14323
14324   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14325
14326   SmallVector<int,8> ShufMask2(NumElems, -1);
14327   for (unsigned i = 0; i != NumElems/2; ++i)
14328     ShufMask2[i] = i + NumElems/2;
14329
14330   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14331
14332   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14333                                 VT.getVectorNumElements()/2);
14334
14335   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14336   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14337
14338   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14339 }
14340
14341 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14342 // may emit an illegal shuffle but the expansion is still better than scalar
14343 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14344 // we'll emit a shuffle and a arithmetic shift.
14345 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14346 // TODO: It is possible to support ZExt by zeroing the undef values during
14347 // the shuffle phase or after the shuffle.
14348 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14349                                  SelectionDAG &DAG) {
14350   MVT RegVT = Op.getSimpleValueType();
14351   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14352   assert(RegVT.isInteger() &&
14353          "We only custom lower integer vector sext loads.");
14354
14355   // Nothing useful we can do without SSE2 shuffles.
14356   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14357
14358   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14359   SDLoc dl(Ld);
14360   EVT MemVT = Ld->getMemoryVT();
14361   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14362   unsigned RegSz = RegVT.getSizeInBits();
14363
14364   ISD::LoadExtType Ext = Ld->getExtensionType();
14365
14366   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14367          && "Only anyext and sext are currently implemented.");
14368   assert(MemVT != RegVT && "Cannot extend to the same type");
14369   assert(MemVT.isVector() && "Must load a vector from memory");
14370
14371   unsigned NumElems = RegVT.getVectorNumElements();
14372   unsigned MemSz = MemVT.getSizeInBits();
14373   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14374
14375   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14376     // The only way in which we have a legal 256-bit vector result but not the
14377     // integer 256-bit operations needed to directly lower a sextload is if we
14378     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14379     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14380     // correctly legalized. We do this late to allow the canonical form of
14381     // sextload to persist throughout the rest of the DAG combiner -- it wants
14382     // to fold together any extensions it can, and so will fuse a sign_extend
14383     // of an sextload into a sextload targeting a wider value.
14384     SDValue Load;
14385     if (MemSz == 128) {
14386       // Just switch this to a normal load.
14387       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14388                                        "it must be a legal 128-bit vector "
14389                                        "type!");
14390       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14391                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14392                   Ld->isInvariant(), Ld->getAlignment());
14393     } else {
14394       assert(MemSz < 128 &&
14395              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14396       // Do an sext load to a 128-bit vector type. We want to use the same
14397       // number of elements, but elements half as wide. This will end up being
14398       // recursively lowered by this routine, but will succeed as we definitely
14399       // have all the necessary features if we're using AVX1.
14400       EVT HalfEltVT =
14401           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14402       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14403       Load =
14404           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14405                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14406                          Ld->isNonTemporal(), Ld->isInvariant(),
14407                          Ld->getAlignment());
14408     }
14409
14410     // Replace chain users with the new chain.
14411     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14412     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14413
14414     // Finally, do a normal sign-extend to the desired register.
14415     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14416   }
14417
14418   // All sizes must be a power of two.
14419   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14420          "Non-power-of-two elements are not custom lowered!");
14421
14422   // Attempt to load the original value using scalar loads.
14423   // Find the largest scalar type that divides the total loaded size.
14424   MVT SclrLoadTy = MVT::i8;
14425   for (MVT Tp : MVT::integer_valuetypes()) {
14426     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14427       SclrLoadTy = Tp;
14428     }
14429   }
14430
14431   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14432   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14433       (64 <= MemSz))
14434     SclrLoadTy = MVT::f64;
14435
14436   // Calculate the number of scalar loads that we need to perform
14437   // in order to load our vector from memory.
14438   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14439
14440   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14441          "Can only lower sext loads with a single scalar load!");
14442
14443   unsigned loadRegZize = RegSz;
14444   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14445     loadRegZize = 128;
14446
14447   // Represent our vector as a sequence of elements which are the
14448   // largest scalar that we can load.
14449   EVT LoadUnitVecVT = EVT::getVectorVT(
14450       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14451
14452   // Represent the data using the same element type that is stored in
14453   // memory. In practice, we ''widen'' MemVT.
14454   EVT WideVecVT =
14455       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14456                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14457
14458   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14459          "Invalid vector type");
14460
14461   // We can't shuffle using an illegal type.
14462   assert(TLI.isTypeLegal(WideVecVT) &&
14463          "We only lower types that form legal widened vector types");
14464
14465   SmallVector<SDValue, 8> Chains;
14466   SDValue Ptr = Ld->getBasePtr();
14467   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14468                                       TLI.getPointerTy(DAG.getDataLayout()));
14469   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14470
14471   for (unsigned i = 0; i < NumLoads; ++i) {
14472     // Perform a single load.
14473     SDValue ScalarLoad =
14474         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14475                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14476                     Ld->getAlignment());
14477     Chains.push_back(ScalarLoad.getValue(1));
14478     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14479     // another round of DAGCombining.
14480     if (i == 0)
14481       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14482     else
14483       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14484                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14485
14486     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14487   }
14488
14489   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14490
14491   // Bitcast the loaded value to a vector of the original element type, in
14492   // the size of the target vector type.
14493   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14494   unsigned SizeRatio = RegSz / MemSz;
14495
14496   if (Ext == ISD::SEXTLOAD) {
14497     // If we have SSE4.1, we can directly emit a VSEXT node.
14498     if (Subtarget->hasSSE41()) {
14499       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14500       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14501       return Sext;
14502     }
14503
14504     // Otherwise we'll shuffle the small elements in the high bits of the
14505     // larger type and perform an arithmetic shift. If the shift is not legal
14506     // it's better to scalarize.
14507     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14508            "We can't implement a sext load without an arithmetic right shift!");
14509
14510     // Redistribute the loaded elements into the different locations.
14511     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14512     for (unsigned i = 0; i != NumElems; ++i)
14513       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14514
14515     SDValue Shuff = DAG.getVectorShuffle(
14516         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14517
14518     Shuff = DAG.getBitcast(RegVT, Shuff);
14519
14520     // Build the arithmetic shift.
14521     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14522                    MemVT.getVectorElementType().getSizeInBits();
14523     Shuff =
14524         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14525                     DAG.getConstant(Amt, dl, RegVT));
14526
14527     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14528     return Shuff;
14529   }
14530
14531   // Redistribute the loaded elements into the different locations.
14532   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14533   for (unsigned i = 0; i != NumElems; ++i)
14534     ShuffleVec[i * SizeRatio] = i;
14535
14536   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14537                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14538
14539   // Bitcast to the requested type.
14540   Shuff = DAG.getBitcast(RegVT, Shuff);
14541   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14542   return Shuff;
14543 }
14544
14545 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14546 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14547 // from the AND / OR.
14548 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14549   Opc = Op.getOpcode();
14550   if (Opc != ISD::OR && Opc != ISD::AND)
14551     return false;
14552   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14553           Op.getOperand(0).hasOneUse() &&
14554           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14555           Op.getOperand(1).hasOneUse());
14556 }
14557
14558 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14559 // 1 and that the SETCC node has a single use.
14560 static bool isXor1OfSetCC(SDValue Op) {
14561   if (Op.getOpcode() != ISD::XOR)
14562     return false;
14563   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14564   if (N1C && N1C->getAPIntValue() == 1) {
14565     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14566       Op.getOperand(0).hasOneUse();
14567   }
14568   return false;
14569 }
14570
14571 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14572   bool addTest = true;
14573   SDValue Chain = Op.getOperand(0);
14574   SDValue Cond  = Op.getOperand(1);
14575   SDValue Dest  = Op.getOperand(2);
14576   SDLoc dl(Op);
14577   SDValue CC;
14578   bool Inverted = false;
14579
14580   if (Cond.getOpcode() == ISD::SETCC) {
14581     // Check for setcc([su]{add,sub,mul}o == 0).
14582     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14583         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14584         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14585         Cond.getOperand(0).getResNo() == 1 &&
14586         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14587          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14588          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14589          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14590          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14591          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14592       Inverted = true;
14593       Cond = Cond.getOperand(0);
14594     } else {
14595       SDValue NewCond = LowerSETCC(Cond, DAG);
14596       if (NewCond.getNode())
14597         Cond = NewCond;
14598     }
14599   }
14600 #if 0
14601   // FIXME: LowerXALUO doesn't handle these!!
14602   else if (Cond.getOpcode() == X86ISD::ADD  ||
14603            Cond.getOpcode() == X86ISD::SUB  ||
14604            Cond.getOpcode() == X86ISD::SMUL ||
14605            Cond.getOpcode() == X86ISD::UMUL)
14606     Cond = LowerXALUO(Cond, DAG);
14607 #endif
14608
14609   // Look pass (and (setcc_carry (cmp ...)), 1).
14610   if (Cond.getOpcode() == ISD::AND &&
14611       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14612     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14613     if (C && C->getAPIntValue() == 1)
14614       Cond = Cond.getOperand(0);
14615   }
14616
14617   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14618   // setting operand in place of the X86ISD::SETCC.
14619   unsigned CondOpcode = Cond.getOpcode();
14620   if (CondOpcode == X86ISD::SETCC ||
14621       CondOpcode == X86ISD::SETCC_CARRY) {
14622     CC = Cond.getOperand(0);
14623
14624     SDValue Cmp = Cond.getOperand(1);
14625     unsigned Opc = Cmp.getOpcode();
14626     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14627     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14628       Cond = Cmp;
14629       addTest = false;
14630     } else {
14631       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14632       default: break;
14633       case X86::COND_O:
14634       case X86::COND_B:
14635         // These can only come from an arithmetic instruction with overflow,
14636         // e.g. SADDO, UADDO.
14637         Cond = Cond.getNode()->getOperand(1);
14638         addTest = false;
14639         break;
14640       }
14641     }
14642   }
14643   CondOpcode = Cond.getOpcode();
14644   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14645       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14646       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14647        Cond.getOperand(0).getValueType() != MVT::i8)) {
14648     SDValue LHS = Cond.getOperand(0);
14649     SDValue RHS = Cond.getOperand(1);
14650     unsigned X86Opcode;
14651     unsigned X86Cond;
14652     SDVTList VTs;
14653     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14654     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14655     // X86ISD::INC).
14656     switch (CondOpcode) {
14657     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14658     case ISD::SADDO:
14659       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14660         if (C->isOne()) {
14661           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14662           break;
14663         }
14664       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14665     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14666     case ISD::SSUBO:
14667       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14668         if (C->isOne()) {
14669           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14670           break;
14671         }
14672       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14673     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14674     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14675     default: llvm_unreachable("unexpected overflowing operator");
14676     }
14677     if (Inverted)
14678       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14679     if (CondOpcode == ISD::UMULO)
14680       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14681                           MVT::i32);
14682     else
14683       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14684
14685     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14686
14687     if (CondOpcode == ISD::UMULO)
14688       Cond = X86Op.getValue(2);
14689     else
14690       Cond = X86Op.getValue(1);
14691
14692     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14693     addTest = false;
14694   } else {
14695     unsigned CondOpc;
14696     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14697       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14698       if (CondOpc == ISD::OR) {
14699         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14700         // two branches instead of an explicit OR instruction with a
14701         // separate test.
14702         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14703             isX86LogicalCmp(Cmp)) {
14704           CC = Cond.getOperand(0).getOperand(0);
14705           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14706                               Chain, Dest, CC, Cmp);
14707           CC = Cond.getOperand(1).getOperand(0);
14708           Cond = Cmp;
14709           addTest = false;
14710         }
14711       } else { // ISD::AND
14712         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14713         // two branches instead of an explicit AND instruction with a
14714         // separate test. However, we only do this if this block doesn't
14715         // have a fall-through edge, because this requires an explicit
14716         // jmp when the condition is false.
14717         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14718             isX86LogicalCmp(Cmp) &&
14719             Op.getNode()->hasOneUse()) {
14720           X86::CondCode CCode =
14721             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14722           CCode = X86::GetOppositeBranchCondition(CCode);
14723           CC = DAG.getConstant(CCode, dl, MVT::i8);
14724           SDNode *User = *Op.getNode()->use_begin();
14725           // Look for an unconditional branch following this conditional branch.
14726           // We need this because we need to reverse the successors in order
14727           // to implement FCMP_OEQ.
14728           if (User->getOpcode() == ISD::BR) {
14729             SDValue FalseBB = User->getOperand(1);
14730             SDNode *NewBR =
14731               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14732             assert(NewBR == User);
14733             (void)NewBR;
14734             Dest = FalseBB;
14735
14736             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14737                                 Chain, Dest, CC, Cmp);
14738             X86::CondCode CCode =
14739               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14740             CCode = X86::GetOppositeBranchCondition(CCode);
14741             CC = DAG.getConstant(CCode, dl, MVT::i8);
14742             Cond = Cmp;
14743             addTest = false;
14744           }
14745         }
14746       }
14747     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14748       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14749       // It should be transformed during dag combiner except when the condition
14750       // is set by a arithmetics with overflow node.
14751       X86::CondCode CCode =
14752         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14753       CCode = X86::GetOppositeBranchCondition(CCode);
14754       CC = DAG.getConstant(CCode, dl, MVT::i8);
14755       Cond = Cond.getOperand(0).getOperand(1);
14756       addTest = false;
14757     } else if (Cond.getOpcode() == ISD::SETCC &&
14758                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14759       // For FCMP_OEQ, we can emit
14760       // two branches instead of an explicit AND instruction with a
14761       // separate test. However, we only do this if this block doesn't
14762       // have a fall-through edge, because this requires an explicit
14763       // jmp when the condition is false.
14764       if (Op.getNode()->hasOneUse()) {
14765         SDNode *User = *Op.getNode()->use_begin();
14766         // Look for an unconditional branch following this conditional branch.
14767         // We need this because we need to reverse the successors in order
14768         // to implement FCMP_OEQ.
14769         if (User->getOpcode() == ISD::BR) {
14770           SDValue FalseBB = User->getOperand(1);
14771           SDNode *NewBR =
14772             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14773           assert(NewBR == User);
14774           (void)NewBR;
14775           Dest = FalseBB;
14776
14777           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14778                                     Cond.getOperand(0), Cond.getOperand(1));
14779           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14780           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14781           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14782                               Chain, Dest, CC, Cmp);
14783           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14784           Cond = Cmp;
14785           addTest = false;
14786         }
14787       }
14788     } else if (Cond.getOpcode() == ISD::SETCC &&
14789                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14790       // For FCMP_UNE, we can emit
14791       // two branches instead of an explicit AND instruction with a
14792       // separate test. However, we only do this if this block doesn't
14793       // have a fall-through edge, because this requires an explicit
14794       // jmp when the condition is false.
14795       if (Op.getNode()->hasOneUse()) {
14796         SDNode *User = *Op.getNode()->use_begin();
14797         // Look for an unconditional branch following this conditional branch.
14798         // We need this because we need to reverse the successors in order
14799         // to implement FCMP_UNE.
14800         if (User->getOpcode() == ISD::BR) {
14801           SDValue FalseBB = User->getOperand(1);
14802           SDNode *NewBR =
14803             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14804           assert(NewBR == User);
14805           (void)NewBR;
14806
14807           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14808                                     Cond.getOperand(0), Cond.getOperand(1));
14809           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14810           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14811           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14812                               Chain, Dest, CC, Cmp);
14813           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14814           Cond = Cmp;
14815           addTest = false;
14816           Dest = FalseBB;
14817         }
14818       }
14819     }
14820   }
14821
14822   if (addTest) {
14823     // Look pass the truncate if the high bits are known zero.
14824     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14825         Cond = Cond.getOperand(0);
14826
14827     // We know the result of AND is compared against zero. Try to match
14828     // it to BT.
14829     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14830       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14831       if (NewSetCC.getNode()) {
14832         CC = NewSetCC.getOperand(0);
14833         Cond = NewSetCC.getOperand(1);
14834         addTest = false;
14835       }
14836     }
14837   }
14838
14839   if (addTest) {
14840     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14841     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14842     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14843   }
14844   Cond = ConvertCmpIfNecessary(Cond, DAG);
14845   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14846                      Chain, Dest, CC, Cond);
14847 }
14848
14849 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14850 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14851 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14852 // that the guard pages used by the OS virtual memory manager are allocated in
14853 // correct sequence.
14854 SDValue
14855 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14856                                            SelectionDAG &DAG) const {
14857   MachineFunction &MF = DAG.getMachineFunction();
14858   bool SplitStack = MF.shouldSplitStack();
14859   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14860                SplitStack;
14861   SDLoc dl(Op);
14862
14863   if (!Lower) {
14864     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14865     SDNode* Node = Op.getNode();
14866
14867     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14868     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14869         " not tell us which reg is the stack pointer!");
14870     EVT VT = Node->getValueType(0);
14871     SDValue Tmp1 = SDValue(Node, 0);
14872     SDValue Tmp2 = SDValue(Node, 1);
14873     SDValue Tmp3 = Node->getOperand(2);
14874     SDValue Chain = Tmp1.getOperand(0);
14875
14876     // Chain the dynamic stack allocation so that it doesn't modify the stack
14877     // pointer when other instructions are using the stack.
14878     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14879         SDLoc(Node));
14880
14881     SDValue Size = Tmp2.getOperand(1);
14882     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14883     Chain = SP.getValue(1);
14884     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14885     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14886     unsigned StackAlign = TFI.getStackAlignment();
14887     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14888     if (Align > StackAlign)
14889       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14890           DAG.getConstant(-(uint64_t)Align, dl, VT));
14891     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14892
14893     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14894         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14895         SDLoc(Node));
14896
14897     SDValue Ops[2] = { Tmp1, Tmp2 };
14898     return DAG.getMergeValues(Ops, dl);
14899   }
14900
14901   // Get the inputs.
14902   SDValue Chain = Op.getOperand(0);
14903   SDValue Size  = Op.getOperand(1);
14904   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14905   EVT VT = Op.getNode()->getValueType(0);
14906
14907   bool Is64Bit = Subtarget->is64Bit();
14908   MVT SPTy = getPointerTy(DAG.getDataLayout());
14909
14910   if (SplitStack) {
14911     MachineRegisterInfo &MRI = MF.getRegInfo();
14912
14913     if (Is64Bit) {
14914       // The 64 bit implementation of segmented stacks needs to clobber both r10
14915       // r11. This makes it impossible to use it along with nested parameters.
14916       const Function *F = MF.getFunction();
14917
14918       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14919            I != E; ++I)
14920         if (I->hasNestAttr())
14921           report_fatal_error("Cannot use segmented stacks with functions that "
14922                              "have nested arguments.");
14923     }
14924
14925     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14926     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14927     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14928     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14929                                 DAG.getRegister(Vreg, SPTy));
14930     SDValue Ops1[2] = { Value, Chain };
14931     return DAG.getMergeValues(Ops1, dl);
14932   } else {
14933     SDValue Flag;
14934     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14935
14936     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14937     Flag = Chain.getValue(1);
14938     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14939
14940     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14941
14942     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14943     unsigned SPReg = RegInfo->getStackRegister();
14944     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14945     Chain = SP.getValue(1);
14946
14947     if (Align) {
14948       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14949                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14950       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14951     }
14952
14953     SDValue Ops1[2] = { SP, Chain };
14954     return DAG.getMergeValues(Ops1, dl);
14955   }
14956 }
14957
14958 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14959   MachineFunction &MF = DAG.getMachineFunction();
14960   auto PtrVT = getPointerTy(MF.getDataLayout());
14961   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14962
14963   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14964   SDLoc DL(Op);
14965
14966   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14967     // vastart just stores the address of the VarArgsFrameIndex slot into the
14968     // memory location argument.
14969     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14970     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14971                         MachinePointerInfo(SV), false, false, 0);
14972   }
14973
14974   // __va_list_tag:
14975   //   gp_offset         (0 - 6 * 8)
14976   //   fp_offset         (48 - 48 + 8 * 16)
14977   //   overflow_arg_area (point to parameters coming in memory).
14978   //   reg_save_area
14979   SmallVector<SDValue, 8> MemOps;
14980   SDValue FIN = Op.getOperand(1);
14981   // Store gp_offset
14982   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14983                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14984                                                DL, MVT::i32),
14985                                FIN, MachinePointerInfo(SV), false, false, 0);
14986   MemOps.push_back(Store);
14987
14988   // Store fp_offset
14989   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
14990   Store = DAG.getStore(Op.getOperand(0), DL,
14991                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14992                                        MVT::i32),
14993                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14994   MemOps.push_back(Store);
14995
14996   // Store ptr to overflow_arg_area
14997   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
14998   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14999   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15000                        MachinePointerInfo(SV, 8),
15001                        false, false, 0);
15002   MemOps.push_back(Store);
15003
15004   // Store ptr to reg_save_area.
15005   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15006   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15007   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15008                        MachinePointerInfo(SV, 16), false, false, 0);
15009   MemOps.push_back(Store);
15010   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15011 }
15012
15013 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15014   assert(Subtarget->is64Bit() &&
15015          "LowerVAARG only handles 64-bit va_arg!");
15016   assert((Subtarget->isTargetLinux() ||
15017           Subtarget->isTargetDarwin()) &&
15018           "Unhandled target in LowerVAARG");
15019   assert(Op.getNode()->getNumOperands() == 4);
15020   SDValue Chain = Op.getOperand(0);
15021   SDValue SrcPtr = Op.getOperand(1);
15022   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15023   unsigned Align = Op.getConstantOperandVal(3);
15024   SDLoc dl(Op);
15025
15026   EVT ArgVT = Op.getNode()->getValueType(0);
15027   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15028   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15029   uint8_t ArgMode;
15030
15031   // Decide which area this value should be read from.
15032   // TODO: Implement the AMD64 ABI in its entirety. This simple
15033   // selection mechanism works only for the basic types.
15034   if (ArgVT == MVT::f80) {
15035     llvm_unreachable("va_arg for f80 not yet implemented");
15036   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15037     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15038   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15039     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15040   } else {
15041     llvm_unreachable("Unhandled argument type in LowerVAARG");
15042   }
15043
15044   if (ArgMode == 2) {
15045     // Sanity Check: Make sure using fp_offset makes sense.
15046     assert(!Subtarget->useSoftFloat() &&
15047            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15048                Attribute::NoImplicitFloat)) &&
15049            Subtarget->hasSSE1());
15050   }
15051
15052   // Insert VAARG_64 node into the DAG
15053   // VAARG_64 returns two values: Variable Argument Address, Chain
15054   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15055                        DAG.getConstant(ArgMode, dl, MVT::i8),
15056                        DAG.getConstant(Align, dl, MVT::i32)};
15057   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15058   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15059                                           VTs, InstOps, MVT::i64,
15060                                           MachinePointerInfo(SV),
15061                                           /*Align=*/0,
15062                                           /*Volatile=*/false,
15063                                           /*ReadMem=*/true,
15064                                           /*WriteMem=*/true);
15065   Chain = VAARG.getValue(1);
15066
15067   // Load the next argument and return it
15068   return DAG.getLoad(ArgVT, dl,
15069                      Chain,
15070                      VAARG,
15071                      MachinePointerInfo(),
15072                      false, false, false, 0);
15073 }
15074
15075 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15076                            SelectionDAG &DAG) {
15077   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15078   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15079   SDValue Chain = Op.getOperand(0);
15080   SDValue DstPtr = Op.getOperand(1);
15081   SDValue SrcPtr = Op.getOperand(2);
15082   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15083   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15084   SDLoc DL(Op);
15085
15086   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15087                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15088                        false, false,
15089                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15090 }
15091
15092 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15093 // amount is a constant. Takes immediate version of shift as input.
15094 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15095                                           SDValue SrcOp, uint64_t ShiftAmt,
15096                                           SelectionDAG &DAG) {
15097   MVT ElementType = VT.getVectorElementType();
15098
15099   // Fold this packed shift into its first operand if ShiftAmt is 0.
15100   if (ShiftAmt == 0)
15101     return SrcOp;
15102
15103   // Check for ShiftAmt >= element width
15104   if (ShiftAmt >= ElementType.getSizeInBits()) {
15105     if (Opc == X86ISD::VSRAI)
15106       ShiftAmt = ElementType.getSizeInBits() - 1;
15107     else
15108       return DAG.getConstant(0, dl, VT);
15109   }
15110
15111   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15112          && "Unknown target vector shift-by-constant node");
15113
15114   // Fold this packed vector shift into a build vector if SrcOp is a
15115   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15116   if (VT == SrcOp.getSimpleValueType() &&
15117       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15118     SmallVector<SDValue, 8> Elts;
15119     unsigned NumElts = SrcOp->getNumOperands();
15120     ConstantSDNode *ND;
15121
15122     switch(Opc) {
15123     default: llvm_unreachable(nullptr);
15124     case X86ISD::VSHLI:
15125       for (unsigned i=0; i!=NumElts; ++i) {
15126         SDValue CurrentOp = SrcOp->getOperand(i);
15127         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15128           Elts.push_back(CurrentOp);
15129           continue;
15130         }
15131         ND = cast<ConstantSDNode>(CurrentOp);
15132         const APInt &C = ND->getAPIntValue();
15133         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15134       }
15135       break;
15136     case X86ISD::VSRLI:
15137       for (unsigned i=0; i!=NumElts; ++i) {
15138         SDValue CurrentOp = SrcOp->getOperand(i);
15139         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15140           Elts.push_back(CurrentOp);
15141           continue;
15142         }
15143         ND = cast<ConstantSDNode>(CurrentOp);
15144         const APInt &C = ND->getAPIntValue();
15145         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15146       }
15147       break;
15148     case X86ISD::VSRAI:
15149       for (unsigned i=0; i!=NumElts; ++i) {
15150         SDValue CurrentOp = SrcOp->getOperand(i);
15151         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15152           Elts.push_back(CurrentOp);
15153           continue;
15154         }
15155         ND = cast<ConstantSDNode>(CurrentOp);
15156         const APInt &C = ND->getAPIntValue();
15157         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15158       }
15159       break;
15160     }
15161
15162     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15163   }
15164
15165   return DAG.getNode(Opc, dl, VT, SrcOp,
15166                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15167 }
15168
15169 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15170 // may or may not be a constant. Takes immediate version of shift as input.
15171 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15172                                    SDValue SrcOp, SDValue ShAmt,
15173                                    SelectionDAG &DAG) {
15174   MVT SVT = ShAmt.getSimpleValueType();
15175   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15176
15177   // Catch shift-by-constant.
15178   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15179     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15180                                       CShAmt->getZExtValue(), DAG);
15181
15182   // Change opcode to non-immediate version
15183   switch (Opc) {
15184     default: llvm_unreachable("Unknown target vector shift node");
15185     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15186     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15187     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15188   }
15189
15190   const X86Subtarget &Subtarget =
15191       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15192   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15193       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15194     // Let the shuffle legalizer expand this shift amount node.
15195     SDValue Op0 = ShAmt.getOperand(0);
15196     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15197     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15198   } else {
15199     // Need to build a vector containing shift amount.
15200     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15201     SmallVector<SDValue, 4> ShOps;
15202     ShOps.push_back(ShAmt);
15203     if (SVT == MVT::i32) {
15204       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15205       ShOps.push_back(DAG.getUNDEF(SVT));
15206     }
15207     ShOps.push_back(DAG.getUNDEF(SVT));
15208
15209     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15210     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15211   }
15212
15213   // The return type has to be a 128-bit type with the same element
15214   // type as the input type.
15215   MVT EltVT = VT.getVectorElementType();
15216   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15217
15218   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15219   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15220 }
15221
15222 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15223 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15224 /// necessary casting for \p Mask when lowering masking intrinsics.
15225 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15226                                     SDValue PreservedSrc,
15227                                     const X86Subtarget *Subtarget,
15228                                     SelectionDAG &DAG) {
15229     EVT VT = Op.getValueType();
15230     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15231                                   MVT::i1, VT.getVectorNumElements());
15232     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15233                                      Mask.getValueType().getSizeInBits());
15234     SDLoc dl(Op);
15235
15236     assert(MaskVT.isSimple() && "invalid mask type");
15237
15238     if (isAllOnes(Mask))
15239       return Op;
15240
15241     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15242     // are extracted by EXTRACT_SUBVECTOR.
15243     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15244                                 DAG.getBitcast(BitcastVT, Mask),
15245                                 DAG.getIntPtrConstant(0, dl));
15246
15247     switch (Op.getOpcode()) {
15248       default: break;
15249       case X86ISD::PCMPEQM:
15250       case X86ISD::PCMPGTM:
15251       case X86ISD::CMPM:
15252       case X86ISD::CMPMU:
15253         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15254     }
15255     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15256       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15257     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
15258 }
15259
15260 /// \brief Creates an SDNode for a predicated scalar operation.
15261 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15262 /// The mask is comming as MVT::i8 and it should be truncated
15263 /// to MVT::i1 while lowering masking intrinsics.
15264 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15265 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15266 /// a scalar instruction.
15267 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15268                                     SDValue PreservedSrc,
15269                                     const X86Subtarget *Subtarget,
15270                                     SelectionDAG &DAG) {
15271     if (isAllOnes(Mask))
15272       return Op;
15273
15274     EVT VT = Op.getValueType();
15275     SDLoc dl(Op);
15276     // The mask should be of type MVT::i1
15277     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15278
15279     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15280       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15281     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15282 }
15283
15284 static int getSEHRegistrationNodeSize(const Function *Fn) {
15285   if (!Fn->hasPersonalityFn())
15286     report_fatal_error(
15287         "querying registration node size for function without personality");
15288   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15289   // WinEHStatePass for the full struct definition.
15290   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15291   case EHPersonality::MSVC_X86SEH: return 24;
15292   case EHPersonality::MSVC_CXX: return 16;
15293   default: break;
15294   }
15295   report_fatal_error("can only recover FP for MSVC EH personality functions");
15296 }
15297
15298 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15299 /// function or when returning to a parent frame after catching an exception, we
15300 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15301 /// Here's the math:
15302 ///   RegNodeBase = EntryEBP - RegNodeSize
15303 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15304 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15305 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15306 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15307                                    SDValue EntryEBP) {
15308   MachineFunction &MF = DAG.getMachineFunction();
15309   SDLoc dl;
15310
15311   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15312   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15313
15314   // It's possible that the parent function no longer has a personality function
15315   // if the exceptional code was optimized away, in which case we just return
15316   // the incoming EBP.
15317   if (!Fn->hasPersonalityFn())
15318     return EntryEBP;
15319
15320   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15321
15322   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15323   // registration.
15324   MCSymbol *OffsetSym =
15325       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15326           GlobalValue::getRealLinkageName(Fn->getName()));
15327   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15328   SDValue RegNodeFrameOffset =
15329       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15330
15331   // RegNodeBase = EntryEBP - RegNodeSize
15332   // ParentFP = RegNodeBase - RegNodeFrameOffset
15333   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15334                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15335   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15336 }
15337
15338 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15339                                        SelectionDAG &DAG) {
15340   SDLoc dl(Op);
15341   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15342   EVT VT = Op.getValueType();
15343   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15344   if (IntrData) {
15345     switch(IntrData->Type) {
15346     case INTR_TYPE_1OP:
15347       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15348     case INTR_TYPE_2OP:
15349       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15350         Op.getOperand(2));
15351     case INTR_TYPE_3OP:
15352       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15353         Op.getOperand(2), Op.getOperand(3));
15354     case INTR_TYPE_4OP:
15355       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15356         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15357     case INTR_TYPE_1OP_MASK_RM: {
15358       SDValue Src = Op.getOperand(1);
15359       SDValue PassThru = Op.getOperand(2);
15360       SDValue Mask = Op.getOperand(3);
15361       SDValue RoundingMode;
15362       // We allways add rounding mode to the Node.
15363       // If the rounding mode is not specified, we add the 
15364       // "current direction" mode.
15365       if (Op.getNumOperands() == 4)
15366         RoundingMode =
15367           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15368       else
15369         RoundingMode = Op.getOperand(4);
15370       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15371       if (IntrWithRoundingModeOpcode != 0)
15372         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15373             X86::STATIC_ROUNDING::CUR_DIRECTION)
15374           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15375                                       dl, Op.getValueType(), Src, RoundingMode),
15376                                       Mask, PassThru, Subtarget, DAG);
15377       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15378                                               RoundingMode),
15379                                   Mask, PassThru, Subtarget, DAG);
15380     }
15381     case INTR_TYPE_1OP_MASK: {
15382       SDValue Src = Op.getOperand(1);
15383       SDValue PassThru = Op.getOperand(2);
15384       SDValue Mask = Op.getOperand(3);
15385       // We add rounding mode to the Node when
15386       //   - RM Opcode is specified and
15387       //   - RM is not "current direction".
15388       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15389       if (IntrWithRoundingModeOpcode != 0) {
15390         SDValue Rnd = Op.getOperand(4);
15391         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15392         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15393           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15394                                       dl, Op.getValueType(),
15395                                       Src, Rnd),
15396                                       Mask, PassThru, Subtarget, DAG);
15397         }
15398       }
15399       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15400                                   Mask, PassThru, Subtarget, DAG);
15401     }
15402     case INTR_TYPE_SCALAR_MASK_RM: {
15403       SDValue Src1 = Op.getOperand(1);
15404       SDValue Src2 = Op.getOperand(2);
15405       SDValue Src0 = Op.getOperand(3);
15406       SDValue Mask = Op.getOperand(4);
15407       // There are 2 kinds of intrinsics in this group:
15408       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15409       // (2) With rounding mode and sae - 7 operands.
15410       if (Op.getNumOperands() == 6) {
15411         SDValue Sae  = Op.getOperand(5);
15412         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15413         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15414                                                 Sae),
15415                                     Mask, Src0, Subtarget, DAG);
15416       }
15417       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15418       SDValue RoundingMode  = Op.getOperand(5);
15419       SDValue Sae  = Op.getOperand(6);
15420       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15421                                               RoundingMode, Sae),
15422                                   Mask, Src0, Subtarget, DAG);
15423     }
15424     case INTR_TYPE_2OP_MASK: {
15425       SDValue Src1 = Op.getOperand(1);
15426       SDValue Src2 = Op.getOperand(2);
15427       SDValue PassThru = Op.getOperand(3);
15428       SDValue Mask = Op.getOperand(4);
15429       // We specify 2 possible opcodes for intrinsics with rounding modes.
15430       // First, we check if the intrinsic may have non-default rounding mode,
15431       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15432       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15433       if (IntrWithRoundingModeOpcode != 0) {
15434         SDValue Rnd = Op.getOperand(5);
15435         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15436         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15437           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15438                                       dl, Op.getValueType(),
15439                                       Src1, Src2, Rnd),
15440                                       Mask, PassThru, Subtarget, DAG);
15441         }
15442       }
15443       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15444                                               Src1,Src2),
15445                                   Mask, PassThru, Subtarget, DAG);
15446     }
15447     case INTR_TYPE_2OP_MASK_RM: {
15448       SDValue Src1 = Op.getOperand(1);
15449       SDValue Src2 = Op.getOperand(2);
15450       SDValue PassThru = Op.getOperand(3);
15451       SDValue Mask = Op.getOperand(4);
15452       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15453       // First, we check if the intrinsic have rounding mode (6 operands),
15454       // if not, we set rounding mode to "current".
15455       SDValue Rnd;
15456       if (Op.getNumOperands() == 6)
15457         Rnd = Op.getOperand(5);
15458       else
15459         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15460       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15461                                               Src1, Src2, Rnd),
15462                                   Mask, PassThru, Subtarget, DAG);
15463     }
15464     case INTR_TYPE_3OP_MASK_RM: {
15465       SDValue Src1 = Op.getOperand(1);
15466       SDValue Src2 = Op.getOperand(2);
15467       SDValue Imm = Op.getOperand(3);
15468       SDValue PassThru = Op.getOperand(4);
15469       SDValue Mask = Op.getOperand(5);
15470       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15471       // First, we check if the intrinsic have rounding mode (7 operands),
15472       // if not, we set rounding mode to "current".
15473       SDValue Rnd;
15474       if (Op.getNumOperands() == 7)
15475         Rnd = Op.getOperand(6);
15476       else
15477         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15478       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15479         Src1, Src2, Imm, Rnd),
15480         Mask, PassThru, Subtarget, DAG);
15481     }
15482     case INTR_TYPE_3OP_MASK: {
15483       SDValue Src1 = Op.getOperand(1);
15484       SDValue Src2 = Op.getOperand(2);
15485       SDValue Src3 = Op.getOperand(3);
15486       SDValue PassThru = Op.getOperand(4);
15487       SDValue Mask = Op.getOperand(5);
15488       // We specify 2 possible opcodes for intrinsics with rounding modes.
15489       // First, we check if the intrinsic may have non-default rounding mode,
15490       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15491       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15492       if (IntrWithRoundingModeOpcode != 0) {
15493         SDValue Rnd = Op.getOperand(6);
15494         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15495         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15496           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15497                                       dl, Op.getValueType(),
15498                                       Src1, Src2, Src3, Rnd),
15499                                       Mask, PassThru, Subtarget, DAG);
15500         }
15501       }
15502       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15503                                               Src1, Src2, Src3),
15504                                   Mask, PassThru, Subtarget, DAG);
15505     }
15506     case VPERM_3OP_MASKZ:
15507     case VPERM_3OP_MASK:
15508     case FMA_OP_MASK3:
15509     case FMA_OP_MASKZ:
15510     case FMA_OP_MASK: {
15511       SDValue Src1 = Op.getOperand(1);
15512       SDValue Src2 = Op.getOperand(2);
15513       SDValue Src3 = Op.getOperand(3);
15514       SDValue Mask = Op.getOperand(4);
15515       EVT VT = Op.getValueType();
15516       SDValue PassThru = SDValue();
15517
15518       // set PassThru element
15519       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15520         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15521       else if (IntrData->Type == FMA_OP_MASK3)
15522         PassThru = Src3;
15523       else
15524         PassThru = Src1;
15525
15526       // We specify 2 possible opcodes for intrinsics with rounding modes.
15527       // First, we check if the intrinsic may have non-default rounding mode,
15528       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15529       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15530       if (IntrWithRoundingModeOpcode != 0) {
15531         SDValue Rnd = Op.getOperand(5);
15532         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15533             X86::STATIC_ROUNDING::CUR_DIRECTION)
15534           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15535                                                   dl, Op.getValueType(),
15536                                                   Src1, Src2, Src3, Rnd),
15537                                       Mask, PassThru, Subtarget, DAG);
15538       }
15539       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15540                                               dl, Op.getValueType(),
15541                                               Src1, Src2, Src3),
15542                                   Mask, PassThru, Subtarget, DAG);
15543     }
15544     case CMP_MASK:
15545     case CMP_MASK_CC: {
15546       // Comparison intrinsics with masks.
15547       // Example of transformation:
15548       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15549       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15550       // (i8 (bitcast
15551       //   (v8i1 (insert_subvector undef,
15552       //           (v2i1 (and (PCMPEQM %a, %b),
15553       //                      (extract_subvector
15554       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15555       EVT VT = Op.getOperand(1).getValueType();
15556       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15557                                     VT.getVectorNumElements());
15558       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15559       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15560                                        Mask.getValueType().getSizeInBits());
15561       SDValue Cmp;
15562       if (IntrData->Type == CMP_MASK_CC) {
15563         SDValue CC = Op.getOperand(3);
15564         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15565         // We specify 2 possible opcodes for intrinsics with rounding modes.
15566         // First, we check if the intrinsic may have non-default rounding mode,
15567         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15568         if (IntrData->Opc1 != 0) {
15569           SDValue Rnd = Op.getOperand(5);
15570           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15571               X86::STATIC_ROUNDING::CUR_DIRECTION)
15572             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15573                               Op.getOperand(2), CC, Rnd);
15574         }
15575         //default rounding mode
15576         if(!Cmp.getNode())
15577             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15578                               Op.getOperand(2), CC);
15579
15580       } else {
15581         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15582         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15583                           Op.getOperand(2));
15584       }
15585       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15586                                              DAG.getTargetConstant(0, dl,
15587                                                                    MaskVT),
15588                                              Subtarget, DAG);
15589       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15590                                 DAG.getUNDEF(BitcastVT), CmpMask,
15591                                 DAG.getIntPtrConstant(0, dl));
15592       return DAG.getBitcast(Op.getValueType(), Res);
15593     }
15594     case COMI: { // Comparison intrinsics
15595       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15596       SDValue LHS = Op.getOperand(1);
15597       SDValue RHS = Op.getOperand(2);
15598       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15599       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15600       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15601       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15602                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15603       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15604     }
15605     case VSHIFT:
15606       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15607                                  Op.getOperand(1), Op.getOperand(2), DAG);
15608     case VSHIFT_MASK:
15609       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15610                                                       Op.getSimpleValueType(),
15611                                                       Op.getOperand(1),
15612                                                       Op.getOperand(2), DAG),
15613                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15614                                   DAG);
15615     case COMPRESS_EXPAND_IN_REG: {
15616       SDValue Mask = Op.getOperand(3);
15617       SDValue DataToCompress = Op.getOperand(1);
15618       SDValue PassThru = Op.getOperand(2);
15619       if (isAllOnes(Mask)) // return data as is
15620         return Op.getOperand(1);
15621
15622       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15623                                               DataToCompress),
15624                                   Mask, PassThru, Subtarget, DAG);
15625     }
15626     case BLEND: {
15627       SDValue Mask = Op.getOperand(3);
15628       EVT VT = Op.getValueType();
15629       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15630                                     VT.getVectorNumElements());
15631       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15632                                        Mask.getValueType().getSizeInBits());
15633       SDLoc dl(Op);
15634       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15635                                   DAG.getBitcast(BitcastVT, Mask),
15636                                   DAG.getIntPtrConstant(0, dl));
15637       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15638                          Op.getOperand(2));
15639     }
15640     default:
15641       break;
15642     }
15643   }
15644
15645   switch (IntNo) {
15646   default: return SDValue();    // Don't custom lower most intrinsics.
15647
15648   case Intrinsic::x86_avx2_permd:
15649   case Intrinsic::x86_avx2_permps:
15650     // Operands intentionally swapped. Mask is last operand to intrinsic,
15651     // but second operand for node/instruction.
15652     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15653                        Op.getOperand(2), Op.getOperand(1));
15654
15655   // ptest and testp intrinsics. The intrinsic these come from are designed to
15656   // return an integer value, not just an instruction so lower it to the ptest
15657   // or testp pattern and a setcc for the result.
15658   case Intrinsic::x86_sse41_ptestz:
15659   case Intrinsic::x86_sse41_ptestc:
15660   case Intrinsic::x86_sse41_ptestnzc:
15661   case Intrinsic::x86_avx_ptestz_256:
15662   case Intrinsic::x86_avx_ptestc_256:
15663   case Intrinsic::x86_avx_ptestnzc_256:
15664   case Intrinsic::x86_avx_vtestz_ps:
15665   case Intrinsic::x86_avx_vtestc_ps:
15666   case Intrinsic::x86_avx_vtestnzc_ps:
15667   case Intrinsic::x86_avx_vtestz_pd:
15668   case Intrinsic::x86_avx_vtestc_pd:
15669   case Intrinsic::x86_avx_vtestnzc_pd:
15670   case Intrinsic::x86_avx_vtestz_ps_256:
15671   case Intrinsic::x86_avx_vtestc_ps_256:
15672   case Intrinsic::x86_avx_vtestnzc_ps_256:
15673   case Intrinsic::x86_avx_vtestz_pd_256:
15674   case Intrinsic::x86_avx_vtestc_pd_256:
15675   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15676     bool IsTestPacked = false;
15677     unsigned X86CC;
15678     switch (IntNo) {
15679     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15680     case Intrinsic::x86_avx_vtestz_ps:
15681     case Intrinsic::x86_avx_vtestz_pd:
15682     case Intrinsic::x86_avx_vtestz_ps_256:
15683     case Intrinsic::x86_avx_vtestz_pd_256:
15684       IsTestPacked = true; // Fallthrough
15685     case Intrinsic::x86_sse41_ptestz:
15686     case Intrinsic::x86_avx_ptestz_256:
15687       // ZF = 1
15688       X86CC = X86::COND_E;
15689       break;
15690     case Intrinsic::x86_avx_vtestc_ps:
15691     case Intrinsic::x86_avx_vtestc_pd:
15692     case Intrinsic::x86_avx_vtestc_ps_256:
15693     case Intrinsic::x86_avx_vtestc_pd_256:
15694       IsTestPacked = true; // Fallthrough
15695     case Intrinsic::x86_sse41_ptestc:
15696     case Intrinsic::x86_avx_ptestc_256:
15697       // CF = 1
15698       X86CC = X86::COND_B;
15699       break;
15700     case Intrinsic::x86_avx_vtestnzc_ps:
15701     case Intrinsic::x86_avx_vtestnzc_pd:
15702     case Intrinsic::x86_avx_vtestnzc_ps_256:
15703     case Intrinsic::x86_avx_vtestnzc_pd_256:
15704       IsTestPacked = true; // Fallthrough
15705     case Intrinsic::x86_sse41_ptestnzc:
15706     case Intrinsic::x86_avx_ptestnzc_256:
15707       // ZF and CF = 0
15708       X86CC = X86::COND_A;
15709       break;
15710     }
15711
15712     SDValue LHS = Op.getOperand(1);
15713     SDValue RHS = Op.getOperand(2);
15714     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15715     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15716     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15717     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15718     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15719   }
15720   case Intrinsic::x86_avx512_kortestz_w:
15721   case Intrinsic::x86_avx512_kortestc_w: {
15722     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15723     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15724     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15725     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15726     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15727     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15728     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15729   }
15730
15731   case Intrinsic::x86_sse42_pcmpistria128:
15732   case Intrinsic::x86_sse42_pcmpestria128:
15733   case Intrinsic::x86_sse42_pcmpistric128:
15734   case Intrinsic::x86_sse42_pcmpestric128:
15735   case Intrinsic::x86_sse42_pcmpistrio128:
15736   case Intrinsic::x86_sse42_pcmpestrio128:
15737   case Intrinsic::x86_sse42_pcmpistris128:
15738   case Intrinsic::x86_sse42_pcmpestris128:
15739   case Intrinsic::x86_sse42_pcmpistriz128:
15740   case Intrinsic::x86_sse42_pcmpestriz128: {
15741     unsigned Opcode;
15742     unsigned X86CC;
15743     switch (IntNo) {
15744     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15745     case Intrinsic::x86_sse42_pcmpistria128:
15746       Opcode = X86ISD::PCMPISTRI;
15747       X86CC = X86::COND_A;
15748       break;
15749     case Intrinsic::x86_sse42_pcmpestria128:
15750       Opcode = X86ISD::PCMPESTRI;
15751       X86CC = X86::COND_A;
15752       break;
15753     case Intrinsic::x86_sse42_pcmpistric128:
15754       Opcode = X86ISD::PCMPISTRI;
15755       X86CC = X86::COND_B;
15756       break;
15757     case Intrinsic::x86_sse42_pcmpestric128:
15758       Opcode = X86ISD::PCMPESTRI;
15759       X86CC = X86::COND_B;
15760       break;
15761     case Intrinsic::x86_sse42_pcmpistrio128:
15762       Opcode = X86ISD::PCMPISTRI;
15763       X86CC = X86::COND_O;
15764       break;
15765     case Intrinsic::x86_sse42_pcmpestrio128:
15766       Opcode = X86ISD::PCMPESTRI;
15767       X86CC = X86::COND_O;
15768       break;
15769     case Intrinsic::x86_sse42_pcmpistris128:
15770       Opcode = X86ISD::PCMPISTRI;
15771       X86CC = X86::COND_S;
15772       break;
15773     case Intrinsic::x86_sse42_pcmpestris128:
15774       Opcode = X86ISD::PCMPESTRI;
15775       X86CC = X86::COND_S;
15776       break;
15777     case Intrinsic::x86_sse42_pcmpistriz128:
15778       Opcode = X86ISD::PCMPISTRI;
15779       X86CC = X86::COND_E;
15780       break;
15781     case Intrinsic::x86_sse42_pcmpestriz128:
15782       Opcode = X86ISD::PCMPESTRI;
15783       X86CC = X86::COND_E;
15784       break;
15785     }
15786     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15787     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15788     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15789     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15790                                 DAG.getConstant(X86CC, dl, MVT::i8),
15791                                 SDValue(PCMP.getNode(), 1));
15792     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15793   }
15794
15795   case Intrinsic::x86_sse42_pcmpistri128:
15796   case Intrinsic::x86_sse42_pcmpestri128: {
15797     unsigned Opcode;
15798     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15799       Opcode = X86ISD::PCMPISTRI;
15800     else
15801       Opcode = X86ISD::PCMPESTRI;
15802
15803     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15804     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15805     return DAG.getNode(Opcode, dl, VTs, NewOps);
15806   }
15807
15808   case Intrinsic::x86_seh_lsda: {
15809     // Compute the symbol for the LSDA. We know it'll get emitted later.
15810     MachineFunction &MF = DAG.getMachineFunction();
15811     SDValue Op1 = Op.getOperand(1);
15812     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15813     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15814         GlobalValue::getRealLinkageName(Fn->getName()));
15815
15816     // Generate a simple absolute symbol reference. This intrinsic is only
15817     // supported on 32-bit Windows, which isn't PIC.
15818     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15819     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15820   }
15821
15822   case Intrinsic::x86_seh_recoverfp: {
15823     SDValue FnOp = Op.getOperand(1);
15824     SDValue IncomingFPOp = Op.getOperand(2);
15825     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15826     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15827     if (!Fn)
15828       report_fatal_error(
15829           "llvm.x86.seh.recoverfp must take a function as the first argument");
15830     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15831   }
15832
15833   case Intrinsic::localaddress: {
15834     // Returns one of the stack, base, or frame pointer registers, depending on
15835     // which is used to reference local variables.
15836     MachineFunction &MF = DAG.getMachineFunction();
15837     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15838     unsigned Reg;
15839     if (RegInfo->hasBasePointer(MF))
15840       Reg = RegInfo->getBaseRegister();
15841     else // This function handles the SP or FP case.
15842       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15843     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15844   }
15845   }
15846 }
15847
15848 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15849                               SDValue Src, SDValue Mask, SDValue Base,
15850                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15851                               const X86Subtarget * Subtarget) {
15852   SDLoc dl(Op);
15853   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15854   if (!C)
15855     llvm_unreachable("Invalid scale type");
15856   unsigned ScaleVal = C->getZExtValue();
15857   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15858     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15859
15860   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15861   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15862                              Index.getSimpleValueType().getVectorNumElements());
15863   SDValue MaskInReg;
15864   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15865   if (MaskC)
15866     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15867   else {
15868     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15869                                      Mask.getValueType().getSizeInBits());
15870
15871     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15872     // are extracted by EXTRACT_SUBVECTOR.
15873     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15874                             DAG.getBitcast(BitcastVT, Mask),
15875                             DAG.getIntPtrConstant(0, dl));
15876   }
15877   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15878   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15879   SDValue Segment = DAG.getRegister(0, MVT::i32);
15880   if (Src.getOpcode() == ISD::UNDEF)
15881     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15882   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15883   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15884   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15885   return DAG.getMergeValues(RetOps, dl);
15886 }
15887
15888 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15889                                SDValue Src, SDValue Mask, SDValue Base,
15890                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15891   SDLoc dl(Op);
15892   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15893   if (!C)
15894     llvm_unreachable("Invalid scale type");
15895   unsigned ScaleVal = C->getZExtValue();
15896   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15897     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15898
15899   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15900   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15901   SDValue Segment = DAG.getRegister(0, MVT::i32);
15902   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15903                              Index.getSimpleValueType().getVectorNumElements());
15904   SDValue MaskInReg;
15905   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15906   if (MaskC)
15907     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15908   else {
15909     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15910                                      Mask.getValueType().getSizeInBits());
15911
15912     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15913     // are extracted by EXTRACT_SUBVECTOR.
15914     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15915                             DAG.getBitcast(BitcastVT, Mask),
15916                             DAG.getIntPtrConstant(0, dl));
15917   }
15918   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15919   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15920   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15921   return SDValue(Res, 1);
15922 }
15923
15924 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15925                                SDValue Mask, SDValue Base, SDValue Index,
15926                                SDValue ScaleOp, SDValue Chain) {
15927   SDLoc dl(Op);
15928   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15929   assert(C && "Invalid scale type");
15930   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15931   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15932   SDValue Segment = DAG.getRegister(0, MVT::i32);
15933   EVT MaskVT =
15934     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15935   SDValue MaskInReg;
15936   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15937   if (MaskC)
15938     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15939   else
15940     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15941   //SDVTList VTs = DAG.getVTList(MVT::Other);
15942   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15943   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15944   return SDValue(Res, 0);
15945 }
15946
15947 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15948 // read performance monitor counters (x86_rdpmc).
15949 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15950                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15951                               SmallVectorImpl<SDValue> &Results) {
15952   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15953   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15954   SDValue LO, HI;
15955
15956   // The ECX register is used to select the index of the performance counter
15957   // to read.
15958   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15959                                    N->getOperand(2));
15960   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15961
15962   // Reads the content of a 64-bit performance counter and returns it in the
15963   // registers EDX:EAX.
15964   if (Subtarget->is64Bit()) {
15965     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15966     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15967                             LO.getValue(2));
15968   } else {
15969     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15970     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15971                             LO.getValue(2));
15972   }
15973   Chain = HI.getValue(1);
15974
15975   if (Subtarget->is64Bit()) {
15976     // The EAX register is loaded with the low-order 32 bits. The EDX register
15977     // is loaded with the supported high-order bits of the counter.
15978     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15979                               DAG.getConstant(32, DL, MVT::i8));
15980     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15981     Results.push_back(Chain);
15982     return;
15983   }
15984
15985   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15986   SDValue Ops[] = { LO, HI };
15987   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15988   Results.push_back(Pair);
15989   Results.push_back(Chain);
15990 }
15991
15992 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15993 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15994 // also used to custom lower READCYCLECOUNTER nodes.
15995 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15996                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15997                               SmallVectorImpl<SDValue> &Results) {
15998   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15999   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16000   SDValue LO, HI;
16001
16002   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16003   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16004   // and the EAX register is loaded with the low-order 32 bits.
16005   if (Subtarget->is64Bit()) {
16006     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16007     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16008                             LO.getValue(2));
16009   } else {
16010     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16011     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16012                             LO.getValue(2));
16013   }
16014   SDValue Chain = HI.getValue(1);
16015
16016   if (Opcode == X86ISD::RDTSCP_DAG) {
16017     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16018
16019     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16020     // the ECX register. Add 'ecx' explicitly to the chain.
16021     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16022                                      HI.getValue(2));
16023     // Explicitly store the content of ECX at the location passed in input
16024     // to the 'rdtscp' intrinsic.
16025     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16026                          MachinePointerInfo(), false, false, 0);
16027   }
16028
16029   if (Subtarget->is64Bit()) {
16030     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16031     // the EAX register is loaded with the low-order 32 bits.
16032     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16033                               DAG.getConstant(32, DL, MVT::i8));
16034     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16035     Results.push_back(Chain);
16036     return;
16037   }
16038
16039   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16040   SDValue Ops[] = { LO, HI };
16041   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16042   Results.push_back(Pair);
16043   Results.push_back(Chain);
16044 }
16045
16046 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16047                                      SelectionDAG &DAG) {
16048   SmallVector<SDValue, 2> Results;
16049   SDLoc DL(Op);
16050   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16051                           Results);
16052   return DAG.getMergeValues(Results, DL);
16053 }
16054
16055 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16056                                     SelectionDAG &DAG) {
16057   MachineFunction &MF = DAG.getMachineFunction();
16058   const Function *Fn = MF.getFunction();
16059   SDLoc dl(Op);
16060   SDValue Chain = Op.getOperand(0);
16061
16062   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16063          "using llvm.x86.seh.restoreframe requires a frame pointer");
16064
16065   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16066   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16067
16068   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16069   unsigned FrameReg =
16070       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16071   unsigned SPReg = RegInfo->getStackRegister();
16072   unsigned SlotSize = RegInfo->getSlotSize();
16073
16074   // Get incoming EBP.
16075   SDValue IncomingEBP =
16076       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16077
16078   // SP is saved in the first field of every registration node, so load
16079   // [EBP-RegNodeSize] into SP.
16080   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16081   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16082                                DAG.getConstant(-RegNodeSize, dl, VT));
16083   SDValue NewSP =
16084       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16085                   false, VT.getScalarSizeInBits() / 8);
16086   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16087
16088   if (!RegInfo->needsStackRealignment(MF)) {
16089     // Adjust EBP to point back to the original frame position.
16090     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16091     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16092   } else {
16093     assert(RegInfo->hasBasePointer(MF) &&
16094            "functions with Win32 EH must use frame or base pointer register");
16095
16096     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16097     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16098     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16099
16100     // Reload the spilled EBP value, now that the stack and base pointers are
16101     // set up.
16102     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16103     X86FI->setHasSEHFramePtrSave(true);
16104     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16105     X86FI->setSEHFramePtrSaveIndex(FI);
16106     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16107                                 MachinePointerInfo(), false, false, false,
16108                                 VT.getScalarSizeInBits() / 8);
16109     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16110   }
16111
16112   return Chain;
16113 }
16114
16115 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16116                                       SelectionDAG &DAG) {
16117   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16118
16119   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16120   if (!IntrData) {
16121     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16122       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16123     return SDValue();
16124   }
16125
16126   SDLoc dl(Op);
16127   switch(IntrData->Type) {
16128   default:
16129     llvm_unreachable("Unknown Intrinsic Type");
16130     break;
16131   case RDSEED:
16132   case RDRAND: {
16133     // Emit the node with the right value type.
16134     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16135     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16136
16137     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16138     // Otherwise return the value from Rand, which is always 0, casted to i32.
16139     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16140                       DAG.getConstant(1, dl, Op->getValueType(1)),
16141                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16142                       SDValue(Result.getNode(), 1) };
16143     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16144                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16145                                   Ops);
16146
16147     // Return { result, isValid, chain }.
16148     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16149                        SDValue(Result.getNode(), 2));
16150   }
16151   case GATHER: {
16152   //gather(v1, mask, index, base, scale);
16153     SDValue Chain = Op.getOperand(0);
16154     SDValue Src   = Op.getOperand(2);
16155     SDValue Base  = Op.getOperand(3);
16156     SDValue Index = Op.getOperand(4);
16157     SDValue Mask  = Op.getOperand(5);
16158     SDValue Scale = Op.getOperand(6);
16159     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16160                          Chain, Subtarget);
16161   }
16162   case SCATTER: {
16163   //scatter(base, mask, index, v1, scale);
16164     SDValue Chain = Op.getOperand(0);
16165     SDValue Base  = Op.getOperand(2);
16166     SDValue Mask  = Op.getOperand(3);
16167     SDValue Index = Op.getOperand(4);
16168     SDValue Src   = Op.getOperand(5);
16169     SDValue Scale = Op.getOperand(6);
16170     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16171                           Scale, Chain);
16172   }
16173   case PREFETCH: {
16174     SDValue Hint = Op.getOperand(6);
16175     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16176     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16177     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16178     SDValue Chain = Op.getOperand(0);
16179     SDValue Mask  = Op.getOperand(2);
16180     SDValue Index = Op.getOperand(3);
16181     SDValue Base  = Op.getOperand(4);
16182     SDValue Scale = Op.getOperand(5);
16183     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16184   }
16185   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16186   case RDTSC: {
16187     SmallVector<SDValue, 2> Results;
16188     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16189                             Results);
16190     return DAG.getMergeValues(Results, dl);
16191   }
16192   // Read Performance Monitoring Counters.
16193   case RDPMC: {
16194     SmallVector<SDValue, 2> Results;
16195     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16196     return DAG.getMergeValues(Results, dl);
16197   }
16198   // XTEST intrinsics.
16199   case XTEST: {
16200     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16201     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16202     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16203                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16204                                 InTrans);
16205     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16206     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16207                        Ret, SDValue(InTrans.getNode(), 1));
16208   }
16209   // ADC/ADCX/SBB
16210   case ADX: {
16211     SmallVector<SDValue, 2> Results;
16212     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16213     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16214     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16215                                 DAG.getConstant(-1, dl, MVT::i8));
16216     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16217                               Op.getOperand(4), GenCF.getValue(1));
16218     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16219                                  Op.getOperand(5), MachinePointerInfo(),
16220                                  false, false, 0);
16221     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16222                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16223                                 Res.getValue(1));
16224     Results.push_back(SetCC);
16225     Results.push_back(Store);
16226     return DAG.getMergeValues(Results, dl);
16227   }
16228   case COMPRESS_TO_MEM: {
16229     SDLoc dl(Op);
16230     SDValue Mask = Op.getOperand(4);
16231     SDValue DataToCompress = Op.getOperand(3);
16232     SDValue Addr = Op.getOperand(2);
16233     SDValue Chain = Op.getOperand(0);
16234
16235     EVT VT = DataToCompress.getValueType();
16236     if (isAllOnes(Mask)) // return just a store
16237       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16238                           MachinePointerInfo(), false, false,
16239                           VT.getScalarSizeInBits()/8);
16240
16241     SDValue Compressed =
16242       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16243                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16244     return DAG.getStore(Chain, dl, Compressed, Addr,
16245                         MachinePointerInfo(), false, false,
16246                         VT.getScalarSizeInBits()/8);
16247   }
16248   case EXPAND_FROM_MEM: {
16249     SDLoc dl(Op);
16250     SDValue Mask = Op.getOperand(4);
16251     SDValue PassThru = Op.getOperand(3);
16252     SDValue Addr = Op.getOperand(2);
16253     SDValue Chain = Op.getOperand(0);
16254     EVT VT = Op.getValueType();
16255
16256     if (isAllOnes(Mask)) // return just a load
16257       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16258                          false, VT.getScalarSizeInBits()/8);
16259
16260     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16261                                        false, false, false,
16262                                        VT.getScalarSizeInBits()/8);
16263
16264     SDValue Results[] = {
16265       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16266                            Mask, PassThru, Subtarget, DAG), Chain};
16267     return DAG.getMergeValues(Results, dl);
16268   }
16269   }
16270 }
16271
16272 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16273                                            SelectionDAG &DAG) const {
16274   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16275   MFI->setReturnAddressIsTaken(true);
16276
16277   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16278     return SDValue();
16279
16280   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16281   SDLoc dl(Op);
16282   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16283
16284   if (Depth > 0) {
16285     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16286     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16287     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16288     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16289                        DAG.getNode(ISD::ADD, dl, PtrVT,
16290                                    FrameAddr, Offset),
16291                        MachinePointerInfo(), false, false, false, 0);
16292   }
16293
16294   // Just load the return address.
16295   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16296   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16297                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16298 }
16299
16300 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16301   MachineFunction &MF = DAG.getMachineFunction();
16302   MachineFrameInfo *MFI = MF.getFrameInfo();
16303   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16304   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16305   EVT VT = Op.getValueType();
16306
16307   MFI->setFrameAddressIsTaken(true);
16308
16309   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16310     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16311     // is not possible to crawl up the stack without looking at the unwind codes
16312     // simultaneously.
16313     int FrameAddrIndex = FuncInfo->getFAIndex();
16314     if (!FrameAddrIndex) {
16315       // Set up a frame object for the return address.
16316       unsigned SlotSize = RegInfo->getSlotSize();
16317       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16318           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16319       FuncInfo->setFAIndex(FrameAddrIndex);
16320     }
16321     return DAG.getFrameIndex(FrameAddrIndex, VT);
16322   }
16323
16324   unsigned FrameReg =
16325       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16326   SDLoc dl(Op);  // FIXME probably not meaningful
16327   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16328   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16329           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16330          "Invalid Frame Register!");
16331   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16332   while (Depth--)
16333     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16334                             MachinePointerInfo(),
16335                             false, false, false, 0);
16336   return FrameAddr;
16337 }
16338
16339 // FIXME? Maybe this could be a TableGen attribute on some registers and
16340 // this table could be generated automatically from RegInfo.
16341 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16342                                               SelectionDAG &DAG) const {
16343   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16344   const MachineFunction &MF = DAG.getMachineFunction();
16345
16346   unsigned Reg = StringSwitch<unsigned>(RegName)
16347                        .Case("esp", X86::ESP)
16348                        .Case("rsp", X86::RSP)
16349                        .Case("ebp", X86::EBP)
16350                        .Case("rbp", X86::RBP)
16351                        .Default(0);
16352
16353   if (Reg == X86::EBP || Reg == X86::RBP) {
16354     if (!TFI.hasFP(MF))
16355       report_fatal_error("register " + StringRef(RegName) +
16356                          " is allocatable: function has no frame pointer");
16357 #ifndef NDEBUG
16358     else {
16359       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16360       unsigned FrameReg =
16361           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16362       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16363              "Invalid Frame Register!");
16364     }
16365 #endif
16366   }
16367
16368   if (Reg)
16369     return Reg;
16370
16371   report_fatal_error("Invalid register name global variable");
16372 }
16373
16374 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16375                                                      SelectionDAG &DAG) const {
16376   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16377   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16378 }
16379
16380 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16381   SDValue Chain     = Op.getOperand(0);
16382   SDValue Offset    = Op.getOperand(1);
16383   SDValue Handler   = Op.getOperand(2);
16384   SDLoc dl      (Op);
16385
16386   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16387   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16388   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16389   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16390           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16391          "Invalid Frame Register!");
16392   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16393   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16394
16395   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16396                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16397                                                        dl));
16398   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16399   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16400                        false, false, 0);
16401   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16402
16403   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16404                      DAG.getRegister(StoreAddrReg, PtrVT));
16405 }
16406
16407 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16408                                                SelectionDAG &DAG) const {
16409   SDLoc DL(Op);
16410   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16411                      DAG.getVTList(MVT::i32, MVT::Other),
16412                      Op.getOperand(0), Op.getOperand(1));
16413 }
16414
16415 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16416                                                 SelectionDAG &DAG) const {
16417   SDLoc DL(Op);
16418   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16419                      Op.getOperand(0), Op.getOperand(1));
16420 }
16421
16422 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16423   return Op.getOperand(0);
16424 }
16425
16426 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16427                                                 SelectionDAG &DAG) const {
16428   SDValue Root = Op.getOperand(0);
16429   SDValue Trmp = Op.getOperand(1); // trampoline
16430   SDValue FPtr = Op.getOperand(2); // nested function
16431   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16432   SDLoc dl (Op);
16433
16434   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16435   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16436
16437   if (Subtarget->is64Bit()) {
16438     SDValue OutChains[6];
16439
16440     // Large code-model.
16441     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16442     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16443
16444     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16445     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16446
16447     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16448
16449     // Load the pointer to the nested function into R11.
16450     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16451     SDValue Addr = Trmp;
16452     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16453                                 Addr, MachinePointerInfo(TrmpAddr),
16454                                 false, false, 0);
16455
16456     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16457                        DAG.getConstant(2, dl, MVT::i64));
16458     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16459                                 MachinePointerInfo(TrmpAddr, 2),
16460                                 false, false, 2);
16461
16462     // Load the 'nest' parameter value into R10.
16463     // R10 is specified in X86CallingConv.td
16464     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16465     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16466                        DAG.getConstant(10, dl, MVT::i64));
16467     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16468                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16469                                 false, false, 0);
16470
16471     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16472                        DAG.getConstant(12, dl, MVT::i64));
16473     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16474                                 MachinePointerInfo(TrmpAddr, 12),
16475                                 false, false, 2);
16476
16477     // Jump to the nested function.
16478     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16479     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16480                        DAG.getConstant(20, dl, MVT::i64));
16481     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16482                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16483                                 false, false, 0);
16484
16485     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16486     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16487                        DAG.getConstant(22, dl, MVT::i64));
16488     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16489                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16490                                 false, false, 0);
16491
16492     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16493   } else {
16494     const Function *Func =
16495       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16496     CallingConv::ID CC = Func->getCallingConv();
16497     unsigned NestReg;
16498
16499     switch (CC) {
16500     default:
16501       llvm_unreachable("Unsupported calling convention");
16502     case CallingConv::C:
16503     case CallingConv::X86_StdCall: {
16504       // Pass 'nest' parameter in ECX.
16505       // Must be kept in sync with X86CallingConv.td
16506       NestReg = X86::ECX;
16507
16508       // Check that ECX wasn't needed by an 'inreg' parameter.
16509       FunctionType *FTy = Func->getFunctionType();
16510       const AttributeSet &Attrs = Func->getAttributes();
16511
16512       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16513         unsigned InRegCount = 0;
16514         unsigned Idx = 1;
16515
16516         for (FunctionType::param_iterator I = FTy->param_begin(),
16517              E = FTy->param_end(); I != E; ++I, ++Idx)
16518           if (Attrs.hasAttribute(Idx, Attribute::InReg))
16519             // FIXME: should only count parameters that are lowered to integers.
16520             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
16521
16522         if (InRegCount > 2) {
16523           report_fatal_error("Nest register in use - reduce number of inreg"
16524                              " parameters!");
16525         }
16526       }
16527       break;
16528     }
16529     case CallingConv::X86_FastCall:
16530     case CallingConv::X86_ThisCall:
16531     case CallingConv::Fast:
16532       // Pass 'nest' parameter in EAX.
16533       // Must be kept in sync with X86CallingConv.td
16534       NestReg = X86::EAX;
16535       break;
16536     }
16537
16538     SDValue OutChains[4];
16539     SDValue Addr, Disp;
16540
16541     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16542                        DAG.getConstant(10, dl, MVT::i32));
16543     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16544
16545     // This is storing the opcode for MOV32ri.
16546     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16547     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16548     OutChains[0] = DAG.getStore(Root, dl,
16549                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16550                                 Trmp, MachinePointerInfo(TrmpAddr),
16551                                 false, false, 0);
16552
16553     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16554                        DAG.getConstant(1, dl, MVT::i32));
16555     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16556                                 MachinePointerInfo(TrmpAddr, 1),
16557                                 false, false, 1);
16558
16559     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16560     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16561                        DAG.getConstant(5, dl, MVT::i32));
16562     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16563                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16564                                 false, false, 1);
16565
16566     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16567                        DAG.getConstant(6, dl, MVT::i32));
16568     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16569                                 MachinePointerInfo(TrmpAddr, 6),
16570                                 false, false, 1);
16571
16572     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16573   }
16574 }
16575
16576 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16577                                             SelectionDAG &DAG) const {
16578   /*
16579    The rounding mode is in bits 11:10 of FPSR, and has the following
16580    settings:
16581      00 Round to nearest
16582      01 Round to -inf
16583      10 Round to +inf
16584      11 Round to 0
16585
16586   FLT_ROUNDS, on the other hand, expects the following:
16587     -1 Undefined
16588      0 Round to 0
16589      1 Round to nearest
16590      2 Round to +inf
16591      3 Round to -inf
16592
16593   To perform the conversion, we do:
16594     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16595   */
16596
16597   MachineFunction &MF = DAG.getMachineFunction();
16598   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16599   unsigned StackAlignment = TFI.getStackAlignment();
16600   MVT VT = Op.getSimpleValueType();
16601   SDLoc DL(Op);
16602
16603   // Save FP Control Word to stack slot
16604   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16605   SDValue StackSlot =
16606       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16607
16608   MachineMemOperand *MMO =
16609    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16610                            MachineMemOperand::MOStore, 2, 2);
16611
16612   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16613   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16614                                           DAG.getVTList(MVT::Other),
16615                                           Ops, MVT::i16, MMO);
16616
16617   // Load FP Control Word from stack slot
16618   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16619                             MachinePointerInfo(), false, false, false, 0);
16620
16621   // Transform as necessary
16622   SDValue CWD1 =
16623     DAG.getNode(ISD::SRL, DL, MVT::i16,
16624                 DAG.getNode(ISD::AND, DL, MVT::i16,
16625                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16626                 DAG.getConstant(11, DL, MVT::i8));
16627   SDValue CWD2 =
16628     DAG.getNode(ISD::SRL, DL, MVT::i16,
16629                 DAG.getNode(ISD::AND, DL, MVT::i16,
16630                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16631                 DAG.getConstant(9, DL, MVT::i8));
16632
16633   SDValue RetVal =
16634     DAG.getNode(ISD::AND, DL, MVT::i16,
16635                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16636                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16637                             DAG.getConstant(1, DL, MVT::i16)),
16638                 DAG.getConstant(3, DL, MVT::i16));
16639
16640   return DAG.getNode((VT.getSizeInBits() < 16 ?
16641                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16642 }
16643
16644 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16645   MVT VT = Op.getSimpleValueType();
16646   EVT OpVT = VT;
16647   unsigned NumBits = VT.getSizeInBits();
16648   SDLoc dl(Op);
16649
16650   Op = Op.getOperand(0);
16651   if (VT == MVT::i8) {
16652     // Zero extend to i32 since there is not an i8 bsr.
16653     OpVT = MVT::i32;
16654     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16655   }
16656
16657   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16658   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16659   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16660
16661   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16662   SDValue Ops[] = {
16663     Op,
16664     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16665     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16666     Op.getValue(1)
16667   };
16668   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16669
16670   // Finally xor with NumBits-1.
16671   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16672                    DAG.getConstant(NumBits - 1, dl, OpVT));
16673
16674   if (VT == MVT::i8)
16675     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16676   return Op;
16677 }
16678
16679 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16680   MVT VT = Op.getSimpleValueType();
16681   EVT OpVT = VT;
16682   unsigned NumBits = VT.getSizeInBits();
16683   SDLoc dl(Op);
16684
16685   Op = Op.getOperand(0);
16686   if (VT == MVT::i8) {
16687     // Zero extend to i32 since there is not an i8 bsr.
16688     OpVT = MVT::i32;
16689     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16690   }
16691
16692   // Issue a bsr (scan bits in reverse).
16693   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16694   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16695
16696   // And xor with NumBits-1.
16697   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16698                    DAG.getConstant(NumBits - 1, dl, OpVT));
16699
16700   if (VT == MVT::i8)
16701     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16702   return Op;
16703 }
16704
16705 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16706   MVT VT = Op.getSimpleValueType();
16707   unsigned NumBits = VT.getSizeInBits();
16708   SDLoc dl(Op);
16709   Op = Op.getOperand(0);
16710
16711   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16712   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16713   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16714
16715   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16716   SDValue Ops[] = {
16717     Op,
16718     DAG.getConstant(NumBits, dl, VT),
16719     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16720     Op.getValue(1)
16721   };
16722   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16723 }
16724
16725 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16726 // ones, and then concatenate the result back.
16727 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16728   MVT VT = Op.getSimpleValueType();
16729
16730   assert(VT.is256BitVector() && VT.isInteger() &&
16731          "Unsupported value type for operation");
16732
16733   unsigned NumElems = VT.getVectorNumElements();
16734   SDLoc dl(Op);
16735
16736   // Extract the LHS vectors
16737   SDValue LHS = Op.getOperand(0);
16738   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16739   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16740
16741   // Extract the RHS vectors
16742   SDValue RHS = Op.getOperand(1);
16743   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16744   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16745
16746   MVT EltVT = VT.getVectorElementType();
16747   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16748
16749   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16750                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16751                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16752 }
16753
16754 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16755   if (Op.getValueType() == MVT::i1)
16756     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16757                        Op.getOperand(0), Op.getOperand(1));
16758   assert(Op.getSimpleValueType().is256BitVector() &&
16759          Op.getSimpleValueType().isInteger() &&
16760          "Only handle AVX 256-bit vector integer operation");
16761   return Lower256IntArith(Op, DAG);
16762 }
16763
16764 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16765   if (Op.getValueType() == MVT::i1)
16766     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16767                        Op.getOperand(0), Op.getOperand(1));
16768   assert(Op.getSimpleValueType().is256BitVector() &&
16769          Op.getSimpleValueType().isInteger() &&
16770          "Only handle AVX 256-bit vector integer operation");
16771   return Lower256IntArith(Op, DAG);
16772 }
16773
16774 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16775                         SelectionDAG &DAG) {
16776   SDLoc dl(Op);
16777   MVT VT = Op.getSimpleValueType();
16778
16779   if (VT == MVT::i1)
16780     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16781
16782   // Decompose 256-bit ops into smaller 128-bit ops.
16783   if (VT.is256BitVector() && !Subtarget->hasInt256())
16784     return Lower256IntArith(Op, DAG);
16785
16786   SDValue A = Op.getOperand(0);
16787   SDValue B = Op.getOperand(1);
16788
16789   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16790   // pairs, multiply and truncate.
16791   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16792     if (Subtarget->hasInt256()) {
16793       if (VT == MVT::v32i8) {
16794         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16795         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16796         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16797         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16798         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16799         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16800         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16801         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16802                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16803                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16804       }
16805
16806       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16807       return DAG.getNode(
16808           ISD::TRUNCATE, dl, VT,
16809           DAG.getNode(ISD::MUL, dl, ExVT,
16810                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16811                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16812     }
16813
16814     assert(VT == MVT::v16i8 &&
16815            "Pre-AVX2 support only supports v16i8 multiplication");
16816     MVT ExVT = MVT::v8i16;
16817
16818     // Extract the lo parts and sign extend to i16
16819     SDValue ALo, BLo;
16820     if (Subtarget->hasSSE41()) {
16821       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16822       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16823     } else {
16824       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16825                               -1, 4, -1, 5, -1, 6, -1, 7};
16826       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16827       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16828       ALo = DAG.getBitcast(ExVT, ALo);
16829       BLo = DAG.getBitcast(ExVT, BLo);
16830       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16831       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16832     }
16833
16834     // Extract the hi parts and sign extend to i16
16835     SDValue AHi, BHi;
16836     if (Subtarget->hasSSE41()) {
16837       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16838                               -1, -1, -1, -1, -1, -1, -1, -1};
16839       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16840       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16841       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16842       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16843     } else {
16844       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16845                               -1, 12, -1, 13, -1, 14, -1, 15};
16846       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16847       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16848       AHi = DAG.getBitcast(ExVT, AHi);
16849       BHi = DAG.getBitcast(ExVT, BHi);
16850       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16851       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16852     }
16853
16854     // Multiply, mask the lower 8bits of the lo/hi results and pack
16855     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16856     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16857     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16858     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16859     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16860   }
16861
16862   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16863   if (VT == MVT::v4i32) {
16864     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16865            "Should not custom lower when pmuldq is available!");
16866
16867     // Extract the odd parts.
16868     static const int UnpackMask[] = { 1, -1, 3, -1 };
16869     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16870     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16871
16872     // Multiply the even parts.
16873     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16874     // Now multiply odd parts.
16875     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16876
16877     Evens = DAG.getBitcast(VT, Evens);
16878     Odds = DAG.getBitcast(VT, Odds);
16879
16880     // Merge the two vectors back together with a shuffle. This expands into 2
16881     // shuffles.
16882     static const int ShufMask[] = { 0, 4, 2, 6 };
16883     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16884   }
16885
16886   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16887          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16888
16889   //  Ahi = psrlqi(a, 32);
16890   //  Bhi = psrlqi(b, 32);
16891   //
16892   //  AloBlo = pmuludq(a, b);
16893   //  AloBhi = pmuludq(a, Bhi);
16894   //  AhiBlo = pmuludq(Ahi, b);
16895
16896   //  AloBhi = psllqi(AloBhi, 32);
16897   //  AhiBlo = psllqi(AhiBlo, 32);
16898   //  return AloBlo + AloBhi + AhiBlo;
16899
16900   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16901   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16902
16903   SDValue AhiBlo = Ahi;
16904   SDValue AloBhi = Bhi;
16905   // Bit cast to 32-bit vectors for MULUDQ
16906   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16907                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16908   A = DAG.getBitcast(MulVT, A);
16909   B = DAG.getBitcast(MulVT, B);
16910   Ahi = DAG.getBitcast(MulVT, Ahi);
16911   Bhi = DAG.getBitcast(MulVT, Bhi);
16912
16913   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16914   // After shifting right const values the result may be all-zero.
16915   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
16916     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16917     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16918   }
16919   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
16920     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16921     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16922   }
16923
16924   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16925   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16926 }
16927
16928 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16929   assert(Subtarget->isTargetWin64() && "Unexpected target");
16930   EVT VT = Op.getValueType();
16931   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16932          "Unexpected return type for lowering");
16933
16934   RTLIB::Libcall LC;
16935   bool isSigned;
16936   switch (Op->getOpcode()) {
16937   default: llvm_unreachable("Unexpected request for libcall!");
16938   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16939   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16940   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16941   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16942   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16943   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16944   }
16945
16946   SDLoc dl(Op);
16947   SDValue InChain = DAG.getEntryNode();
16948
16949   TargetLowering::ArgListTy Args;
16950   TargetLowering::ArgListEntry Entry;
16951   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16952     EVT ArgVT = Op->getOperand(i).getValueType();
16953     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16954            "Unexpected argument type for lowering");
16955     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16956     Entry.Node = StackPtr;
16957     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16958                            false, false, 16);
16959     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16960     Entry.Ty = PointerType::get(ArgTy,0);
16961     Entry.isSExt = false;
16962     Entry.isZExt = false;
16963     Args.push_back(Entry);
16964   }
16965
16966   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16967                                          getPointerTy(DAG.getDataLayout()));
16968
16969   TargetLowering::CallLoweringInfo CLI(DAG);
16970   CLI.setDebugLoc(dl).setChain(InChain)
16971     .setCallee(getLibcallCallingConv(LC),
16972                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16973                Callee, std::move(Args), 0)
16974     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16975
16976   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16977   return DAG.getBitcast(VT, CallInfo.first);
16978 }
16979
16980 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16981                              SelectionDAG &DAG) {
16982   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16983   EVT VT = Op0.getValueType();
16984   SDLoc dl(Op);
16985
16986   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16987          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16988
16989   // PMULxD operations multiply each even value (starting at 0) of LHS with
16990   // the related value of RHS and produce a widen result.
16991   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16992   // => <2 x i64> <ae|cg>
16993   //
16994   // In other word, to have all the results, we need to perform two PMULxD:
16995   // 1. one with the even values.
16996   // 2. one with the odd values.
16997   // To achieve #2, with need to place the odd values at an even position.
16998   //
16999   // Place the odd value at an even position (basically, shift all values 1
17000   // step to the left):
17001   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17002   // <a|b|c|d> => <b|undef|d|undef>
17003   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17004   // <e|f|g|h> => <f|undef|h|undef>
17005   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17006
17007   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17008   // ints.
17009   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17010   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17011   unsigned Opcode =
17012       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17013   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17014   // => <2 x i64> <ae|cg>
17015   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17016   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17017   // => <2 x i64> <bf|dh>
17018   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17019
17020   // Shuffle it back into the right order.
17021   SDValue Highs, Lows;
17022   if (VT == MVT::v8i32) {
17023     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17024     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17025     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17026     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17027   } else {
17028     const int HighMask[] = {1, 5, 3, 7};
17029     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17030     const int LowMask[] = {0, 4, 2, 6};
17031     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17032   }
17033
17034   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17035   // unsigned multiply.
17036   if (IsSigned && !Subtarget->hasSSE41()) {
17037     SDValue ShAmt = DAG.getConstant(
17038         31, dl,
17039         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17040     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17041                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17042     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17043                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17044
17045     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17046     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17047   }
17048
17049   // The first result of MUL_LOHI is actually the low value, followed by the
17050   // high value.
17051   SDValue Ops[] = {Lows, Highs};
17052   return DAG.getMergeValues(Ops, dl);
17053 }
17054
17055 // Return true if the required (according to Opcode) shift-imm form is natively
17056 // supported by the Subtarget
17057 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17058                                         unsigned Opcode) {
17059   if (VT.getScalarSizeInBits() < 16)
17060     return false;
17061
17062   if (VT.is512BitVector() &&
17063       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17064     return true;
17065
17066   bool LShift = VT.is128BitVector() ||
17067     (VT.is256BitVector() && Subtarget->hasInt256());
17068
17069   bool AShift = LShift && (Subtarget->hasVLX() ||
17070     (VT != MVT::v2i64 && VT != MVT::v4i64));
17071   return (Opcode == ISD::SRA) ? AShift : LShift;
17072 }
17073
17074 // The shift amount is a variable, but it is the same for all vector lanes.
17075 // These instructions are defined together with shift-immediate.
17076 static
17077 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17078                                       unsigned Opcode) {
17079   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17080 }
17081
17082 // Return true if the required (according to Opcode) variable-shift form is
17083 // natively supported by the Subtarget
17084 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17085                                     unsigned Opcode) {
17086
17087   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17088     return false;
17089
17090   // vXi16 supported only on AVX-512, BWI
17091   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17092     return false;
17093
17094   if (VT.is512BitVector() || Subtarget->hasVLX())
17095     return true;
17096
17097   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17098   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17099   return (Opcode == ISD::SRA) ? AShift : LShift;
17100 }
17101
17102 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17103                                          const X86Subtarget *Subtarget) {
17104   MVT VT = Op.getSimpleValueType();
17105   SDLoc dl(Op);
17106   SDValue R = Op.getOperand(0);
17107   SDValue Amt = Op.getOperand(1);
17108
17109   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17110     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17111
17112   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17113     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17114     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17115     SDValue Ex = DAG.getBitcast(ExVT, R);
17116
17117     if (ShiftAmt >= 32) {
17118       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17119       SDValue Upper =
17120           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17121       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17122                                                  ShiftAmt - 32, DAG);
17123       if (VT == MVT::v2i64)
17124         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17125       if (VT == MVT::v4i64)
17126         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17127                                   {9, 1, 11, 3, 13, 5, 15, 7});
17128     } else {
17129       // SRA upper i32, SHL whole i64 and select lower i32.
17130       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17131                                                  ShiftAmt, DAG);
17132       SDValue Lower =
17133           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17134       Lower = DAG.getBitcast(ExVT, Lower);
17135       if (VT == MVT::v2i64)
17136         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17137       if (VT == MVT::v4i64)
17138         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17139                                   {8, 1, 10, 3, 12, 5, 14, 7});
17140     }
17141     return DAG.getBitcast(VT, Ex);
17142   };
17143
17144   // Optimize shl/srl/sra with constant shift amount.
17145   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17146     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17147       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17148
17149       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17150         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17151
17152       // i64 SRA needs to be performed as partial shifts.
17153       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17154           Op.getOpcode() == ISD::SRA)
17155         return ArithmeticShiftRight64(ShiftAmt);
17156
17157       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17158         unsigned NumElts = VT.getVectorNumElements();
17159         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17160
17161         if (Op.getOpcode() == ISD::SHL) {
17162           // Simple i8 add case
17163           if (ShiftAmt == 1)
17164             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17165
17166           // Make a large shift.
17167           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17168                                                    R, ShiftAmt, DAG);
17169           SHL = DAG.getBitcast(VT, SHL);
17170           // Zero out the rightmost bits.
17171           SmallVector<SDValue, 32> V(
17172               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17173           return DAG.getNode(ISD::AND, dl, VT, SHL,
17174                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17175         }
17176         if (Op.getOpcode() == ISD::SRL) {
17177           // Make a large shift.
17178           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17179                                                    R, ShiftAmt, DAG);
17180           SRL = DAG.getBitcast(VT, SRL);
17181           // Zero out the leftmost bits.
17182           SmallVector<SDValue, 32> V(
17183               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17184           return DAG.getNode(ISD::AND, dl, VT, SRL,
17185                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17186         }
17187         if (Op.getOpcode() == ISD::SRA) {
17188           if (ShiftAmt == 7) {
17189             // R s>> 7  ===  R s< 0
17190             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17191             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17192           }
17193
17194           // R s>> a === ((R u>> a) ^ m) - m
17195           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17196           SmallVector<SDValue, 32> V(NumElts,
17197                                      DAG.getConstant(128 >> ShiftAmt, dl,
17198                                                      MVT::i8));
17199           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17200           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17201           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17202           return Res;
17203         }
17204         llvm_unreachable("Unknown shift opcode.");
17205       }
17206     }
17207   }
17208
17209   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17210   if (!Subtarget->is64Bit() &&
17211       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17212       Amt.getOpcode() == ISD::BITCAST &&
17213       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17214     Amt = Amt.getOperand(0);
17215     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17216                      VT.getVectorNumElements();
17217     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17218     uint64_t ShiftAmt = 0;
17219     for (unsigned i = 0; i != Ratio; ++i) {
17220       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17221       if (!C)
17222         return SDValue();
17223       // 6 == Log2(64)
17224       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17225     }
17226     // Check remaining shift amounts.
17227     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17228       uint64_t ShAmt = 0;
17229       for (unsigned j = 0; j != Ratio; ++j) {
17230         ConstantSDNode *C =
17231           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17232         if (!C)
17233           return SDValue();
17234         // 6 == Log2(64)
17235         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17236       }
17237       if (ShAmt != ShiftAmt)
17238         return SDValue();
17239     }
17240
17241     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17242       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17243
17244     if (Op.getOpcode() == ISD::SRA)
17245       return ArithmeticShiftRight64(ShiftAmt);
17246   }
17247
17248   return SDValue();
17249 }
17250
17251 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17252                                         const X86Subtarget* Subtarget) {
17253   MVT VT = Op.getSimpleValueType();
17254   SDLoc dl(Op);
17255   SDValue R = Op.getOperand(0);
17256   SDValue Amt = Op.getOperand(1);
17257
17258   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17259     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17260
17261   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17262     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17263
17264   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17265     SDValue BaseShAmt;
17266     EVT EltVT = VT.getVectorElementType();
17267
17268     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17269       // Check if this build_vector node is doing a splat.
17270       // If so, then set BaseShAmt equal to the splat value.
17271       BaseShAmt = BV->getSplatValue();
17272       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17273         BaseShAmt = SDValue();
17274     } else {
17275       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17276         Amt = Amt.getOperand(0);
17277
17278       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17279       if (SVN && SVN->isSplat()) {
17280         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17281         SDValue InVec = Amt.getOperand(0);
17282         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17283           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17284                  "Unexpected shuffle index found!");
17285           BaseShAmt = InVec.getOperand(SplatIdx);
17286         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17287            if (ConstantSDNode *C =
17288                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17289              if (C->getZExtValue() == SplatIdx)
17290                BaseShAmt = InVec.getOperand(1);
17291            }
17292         }
17293
17294         if (!BaseShAmt)
17295           // Avoid introducing an extract element from a shuffle.
17296           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17297                                   DAG.getIntPtrConstant(SplatIdx, dl));
17298       }
17299     }
17300
17301     if (BaseShAmt.getNode()) {
17302       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17303       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17304         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17305       else if (EltVT.bitsLT(MVT::i32))
17306         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17307
17308       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17309     }
17310   }
17311
17312   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17313   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17314       Amt.getOpcode() == ISD::BITCAST &&
17315       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17316     Amt = Amt.getOperand(0);
17317     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17318                      VT.getVectorNumElements();
17319     std::vector<SDValue> Vals(Ratio);
17320     for (unsigned i = 0; i != Ratio; ++i)
17321       Vals[i] = Amt.getOperand(i);
17322     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17323       for (unsigned j = 0; j != Ratio; ++j)
17324         if (Vals[j] != Amt.getOperand(i + j))
17325           return SDValue();
17326     }
17327
17328     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17329       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17330   }
17331   return SDValue();
17332 }
17333
17334 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17335                           SelectionDAG &DAG) {
17336   MVT VT = Op.getSimpleValueType();
17337   SDLoc dl(Op);
17338   SDValue R = Op.getOperand(0);
17339   SDValue Amt = Op.getOperand(1);
17340
17341   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17342   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17343
17344   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17345     return V;
17346
17347   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17348       return V;
17349
17350   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17351     return Op;
17352
17353   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17354   // shifts per-lane and then shuffle the partial results back together.
17355   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17356     // Splat the shift amounts so the scalar shifts above will catch it.
17357     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17358     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17359     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17360     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17361     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17362   }
17363
17364   // If possible, lower this packed shift into a vector multiply instead of
17365   // expanding it into a sequence of scalar shifts.
17366   // Do this only if the vector shift count is a constant build_vector.
17367   if (Op.getOpcode() == ISD::SHL &&
17368       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17369        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17370       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17371     SmallVector<SDValue, 8> Elts;
17372     EVT SVT = VT.getScalarType();
17373     unsigned SVTBits = SVT.getSizeInBits();
17374     const APInt &One = APInt(SVTBits, 1);
17375     unsigned NumElems = VT.getVectorNumElements();
17376
17377     for (unsigned i=0; i !=NumElems; ++i) {
17378       SDValue Op = Amt->getOperand(i);
17379       if (Op->getOpcode() == ISD::UNDEF) {
17380         Elts.push_back(Op);
17381         continue;
17382       }
17383
17384       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17385       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17386       uint64_t ShAmt = C.getZExtValue();
17387       if (ShAmt >= SVTBits) {
17388         Elts.push_back(DAG.getUNDEF(SVT));
17389         continue;
17390       }
17391       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17392     }
17393     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17394     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17395   }
17396
17397   // Lower SHL with variable shift amount.
17398   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17399     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17400
17401     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17402                      DAG.getConstant(0x3f800000U, dl, VT));
17403     Op = DAG.getBitcast(MVT::v4f32, Op);
17404     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17405     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17406   }
17407
17408   // If possible, lower this shift as a sequence of two shifts by
17409   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17410   // Example:
17411   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17412   //
17413   // Could be rewritten as:
17414   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17415   //
17416   // The advantage is that the two shifts from the example would be
17417   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17418   // the vector shift into four scalar shifts plus four pairs of vector
17419   // insert/extract.
17420   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17421       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17422     unsigned TargetOpcode = X86ISD::MOVSS;
17423     bool CanBeSimplified;
17424     // The splat value for the first packed shift (the 'X' from the example).
17425     SDValue Amt1 = Amt->getOperand(0);
17426     // The splat value for the second packed shift (the 'Y' from the example).
17427     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17428                                         Amt->getOperand(2);
17429
17430     // See if it is possible to replace this node with a sequence of
17431     // two shifts followed by a MOVSS/MOVSD
17432     if (VT == MVT::v4i32) {
17433       // Check if it is legal to use a MOVSS.
17434       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17435                         Amt2 == Amt->getOperand(3);
17436       if (!CanBeSimplified) {
17437         // Otherwise, check if we can still simplify this node using a MOVSD.
17438         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17439                           Amt->getOperand(2) == Amt->getOperand(3);
17440         TargetOpcode = X86ISD::MOVSD;
17441         Amt2 = Amt->getOperand(2);
17442       }
17443     } else {
17444       // Do similar checks for the case where the machine value type
17445       // is MVT::v8i16.
17446       CanBeSimplified = Amt1 == Amt->getOperand(1);
17447       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17448         CanBeSimplified = Amt2 == Amt->getOperand(i);
17449
17450       if (!CanBeSimplified) {
17451         TargetOpcode = X86ISD::MOVSD;
17452         CanBeSimplified = true;
17453         Amt2 = Amt->getOperand(4);
17454         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17455           CanBeSimplified = Amt1 == Amt->getOperand(i);
17456         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17457           CanBeSimplified = Amt2 == Amt->getOperand(j);
17458       }
17459     }
17460
17461     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17462         isa<ConstantSDNode>(Amt2)) {
17463       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17464       EVT CastVT = MVT::v4i32;
17465       SDValue Splat1 =
17466         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17467       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17468       SDValue Splat2 =
17469         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17470       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17471       if (TargetOpcode == X86ISD::MOVSD)
17472         CastVT = MVT::v2i64;
17473       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17474       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17475       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17476                                             BitCast1, DAG);
17477       return DAG.getBitcast(VT, Result);
17478     }
17479   }
17480
17481   // v4i32 Non Uniform Shifts.
17482   // If the shift amount is constant we can shift each lane using the SSE2
17483   // immediate shifts, else we need to zero-extend each lane to the lower i64
17484   // and shift using the SSE2 variable shifts.
17485   // The separate results can then be blended together.
17486   if (VT == MVT::v4i32) {
17487     unsigned Opc = Op.getOpcode();
17488     SDValue Amt0, Amt1, Amt2, Amt3;
17489     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17490       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17491       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17492       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17493       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17494     } else {
17495       // ISD::SHL is handled above but we include it here for completeness.
17496       switch (Opc) {
17497       default:
17498         llvm_unreachable("Unknown target vector shift node");
17499       case ISD::SHL:
17500         Opc = X86ISD::VSHL;
17501         break;
17502       case ISD::SRL:
17503         Opc = X86ISD::VSRL;
17504         break;
17505       case ISD::SRA:
17506         Opc = X86ISD::VSRA;
17507         break;
17508       }
17509       // The SSE2 shifts use the lower i64 as the same shift amount for
17510       // all lanes and the upper i64 is ignored. These shuffle masks
17511       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17512       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17513       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17514       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17515       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17516       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17517     }
17518
17519     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17520     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17521     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17522     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17523     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17524     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17525     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17526   }
17527
17528   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17529     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17530     unsigned ShiftOpcode = Op->getOpcode();
17531
17532     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17533       // On SSE41 targets we make use of the fact that VSELECT lowers
17534       // to PBLENDVB which selects bytes based just on the sign bit.
17535       if (Subtarget->hasSSE41()) {
17536         V0 = DAG.getBitcast(VT, V0);
17537         V1 = DAG.getBitcast(VT, V1);
17538         Sel = DAG.getBitcast(VT, Sel);
17539         return DAG.getBitcast(SelVT,
17540                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17541       }
17542       // On pre-SSE41 targets we test for the sign bit by comparing to
17543       // zero - a negative value will set all bits of the lanes to true
17544       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17545       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17546       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17547       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17548     };
17549
17550     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17551     // We can safely do this using i16 shifts as we're only interested in
17552     // the 3 lower bits of each byte.
17553     Amt = DAG.getBitcast(ExtVT, Amt);
17554     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17555     Amt = DAG.getBitcast(VT, Amt);
17556
17557     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17558       // r = VSELECT(r, shift(r, 4), a);
17559       SDValue M =
17560           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17561       R = SignBitSelect(VT, Amt, M, R);
17562
17563       // a += a
17564       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17565
17566       // r = VSELECT(r, shift(r, 2), a);
17567       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17568       R = SignBitSelect(VT, Amt, M, R);
17569
17570       // a += a
17571       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17572
17573       // return VSELECT(r, shift(r, 1), a);
17574       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17575       R = SignBitSelect(VT, Amt, M, R);
17576       return R;
17577     }
17578
17579     if (Op->getOpcode() == ISD::SRA) {
17580       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17581       // so we can correctly sign extend. We don't care what happens to the
17582       // lower byte.
17583       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17584       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17585       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17586       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17587       ALo = DAG.getBitcast(ExtVT, ALo);
17588       AHi = DAG.getBitcast(ExtVT, AHi);
17589       RLo = DAG.getBitcast(ExtVT, RLo);
17590       RHi = DAG.getBitcast(ExtVT, RHi);
17591
17592       // r = VSELECT(r, shift(r, 4), a);
17593       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17594                                 DAG.getConstant(4, dl, ExtVT));
17595       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17596                                 DAG.getConstant(4, dl, ExtVT));
17597       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17598       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17599
17600       // a += a
17601       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17602       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17603
17604       // r = VSELECT(r, shift(r, 2), a);
17605       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17606                         DAG.getConstant(2, dl, ExtVT));
17607       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17608                         DAG.getConstant(2, dl, ExtVT));
17609       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17610       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17611
17612       // a += a
17613       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17614       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17615
17616       // r = VSELECT(r, shift(r, 1), a);
17617       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17618                         DAG.getConstant(1, dl, ExtVT));
17619       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17620                         DAG.getConstant(1, dl, ExtVT));
17621       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17622       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17623
17624       // Logical shift the result back to the lower byte, leaving a zero upper
17625       // byte
17626       // meaning that we can safely pack with PACKUSWB.
17627       RLo =
17628           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17629       RHi =
17630           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17631       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17632     }
17633   }
17634
17635   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17636   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17637   // solution better.
17638   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17639     MVT ExtVT = MVT::v8i32;
17640     unsigned ExtOpc =
17641         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17642     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17643     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17644     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17645                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17646   }
17647
17648   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17649     MVT ExtVT = MVT::v8i32;
17650     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17651     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17652     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17653     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17654     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17655     ALo = DAG.getBitcast(ExtVT, ALo);
17656     AHi = DAG.getBitcast(ExtVT, AHi);
17657     RLo = DAG.getBitcast(ExtVT, RLo);
17658     RHi = DAG.getBitcast(ExtVT, RHi);
17659     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17660     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17661     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17662     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17663     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17664   }
17665
17666   if (VT == MVT::v8i16) {
17667     unsigned ShiftOpcode = Op->getOpcode();
17668
17669     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17670       // On SSE41 targets we make use of the fact that VSELECT lowers
17671       // to PBLENDVB which selects bytes based just on the sign bit.
17672       if (Subtarget->hasSSE41()) {
17673         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17674         V0 = DAG.getBitcast(ExtVT, V0);
17675         V1 = DAG.getBitcast(ExtVT, V1);
17676         Sel = DAG.getBitcast(ExtVT, Sel);
17677         return DAG.getBitcast(
17678             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17679       }
17680       // On pre-SSE41 targets we splat the sign bit - a negative value will
17681       // set all bits of the lanes to true and VSELECT uses that in
17682       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17683       SDValue C =
17684           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17685       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17686     };
17687
17688     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17689     if (Subtarget->hasSSE41()) {
17690       // On SSE41 targets we need to replicate the shift mask in both
17691       // bytes for PBLENDVB.
17692       Amt = DAG.getNode(
17693           ISD::OR, dl, VT,
17694           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17695           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17696     } else {
17697       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17698     }
17699
17700     // r = VSELECT(r, shift(r, 8), a);
17701     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17702     R = SignBitSelect(Amt, M, R);
17703
17704     // a += a
17705     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17706
17707     // r = VSELECT(r, shift(r, 4), a);
17708     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17709     R = SignBitSelect(Amt, M, R);
17710
17711     // a += a
17712     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17713
17714     // r = VSELECT(r, shift(r, 2), a);
17715     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17716     R = SignBitSelect(Amt, M, R);
17717
17718     // a += a
17719     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17720
17721     // return VSELECT(r, shift(r, 1), a);
17722     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17723     R = SignBitSelect(Amt, M, R);
17724     return R;
17725   }
17726
17727   // Decompose 256-bit shifts into smaller 128-bit shifts.
17728   if (VT.is256BitVector()) {
17729     unsigned NumElems = VT.getVectorNumElements();
17730     MVT EltVT = VT.getVectorElementType();
17731     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17732
17733     // Extract the two vectors
17734     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17735     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17736
17737     // Recreate the shift amount vectors
17738     SDValue Amt1, Amt2;
17739     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17740       // Constant shift amount
17741       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17742       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17743       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17744
17745       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17746       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17747     } else {
17748       // Variable shift amount
17749       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17750       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17751     }
17752
17753     // Issue new vector shifts for the smaller types
17754     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17755     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17756
17757     // Concatenate the result back
17758     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17759   }
17760
17761   return SDValue();
17762 }
17763
17764 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17765   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17766   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17767   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17768   // has only one use.
17769   SDNode *N = Op.getNode();
17770   SDValue LHS = N->getOperand(0);
17771   SDValue RHS = N->getOperand(1);
17772   unsigned BaseOp = 0;
17773   unsigned Cond = 0;
17774   SDLoc DL(Op);
17775   switch (Op.getOpcode()) {
17776   default: llvm_unreachable("Unknown ovf instruction!");
17777   case ISD::SADDO:
17778     // A subtract of one will be selected as a INC. Note that INC doesn't
17779     // set CF, so we can't do this for UADDO.
17780     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17781       if (C->isOne()) {
17782         BaseOp = X86ISD::INC;
17783         Cond = X86::COND_O;
17784         break;
17785       }
17786     BaseOp = X86ISD::ADD;
17787     Cond = X86::COND_O;
17788     break;
17789   case ISD::UADDO:
17790     BaseOp = X86ISD::ADD;
17791     Cond = X86::COND_B;
17792     break;
17793   case ISD::SSUBO:
17794     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17795     // set CF, so we can't do this for USUBO.
17796     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17797       if (C->isOne()) {
17798         BaseOp = X86ISD::DEC;
17799         Cond = X86::COND_O;
17800         break;
17801       }
17802     BaseOp = X86ISD::SUB;
17803     Cond = X86::COND_O;
17804     break;
17805   case ISD::USUBO:
17806     BaseOp = X86ISD::SUB;
17807     Cond = X86::COND_B;
17808     break;
17809   case ISD::SMULO:
17810     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17811     Cond = X86::COND_O;
17812     break;
17813   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17814     if (N->getValueType(0) == MVT::i8) {
17815       BaseOp = X86ISD::UMUL8;
17816       Cond = X86::COND_O;
17817       break;
17818     }
17819     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17820                                  MVT::i32);
17821     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17822
17823     SDValue SetCC =
17824       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17825                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17826                   SDValue(Sum.getNode(), 2));
17827
17828     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17829   }
17830   }
17831
17832   // Also sets EFLAGS.
17833   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17834   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17835
17836   SDValue SetCC =
17837     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17838                 DAG.getConstant(Cond, DL, MVT::i32),
17839                 SDValue(Sum.getNode(), 1));
17840
17841   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17842 }
17843
17844 /// Returns true if the operand type is exactly twice the native width, and
17845 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17846 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17847 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17848 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17849   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17850
17851   if (OpWidth == 64)
17852     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17853   else if (OpWidth == 128)
17854     return Subtarget->hasCmpxchg16b();
17855   else
17856     return false;
17857 }
17858
17859 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17860   return needsCmpXchgNb(SI->getValueOperand()->getType());
17861 }
17862
17863 // Note: this turns large loads into lock cmpxchg8b/16b.
17864 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17865 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17866   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17867   return needsCmpXchgNb(PTy->getElementType());
17868 }
17869
17870 TargetLoweringBase::AtomicRMWExpansionKind
17871 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17872   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17873   const Type *MemType = AI->getType();
17874
17875   // If the operand is too big, we must see if cmpxchg8/16b is available
17876   // and default to library calls otherwise.
17877   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17878     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17879                                    : AtomicRMWExpansionKind::None;
17880   }
17881
17882   AtomicRMWInst::BinOp Op = AI->getOperation();
17883   switch (Op) {
17884   default:
17885     llvm_unreachable("Unknown atomic operation");
17886   case AtomicRMWInst::Xchg:
17887   case AtomicRMWInst::Add:
17888   case AtomicRMWInst::Sub:
17889     // It's better to use xadd, xsub or xchg for these in all cases.
17890     return AtomicRMWExpansionKind::None;
17891   case AtomicRMWInst::Or:
17892   case AtomicRMWInst::And:
17893   case AtomicRMWInst::Xor:
17894     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17895     // prefix to a normal instruction for these operations.
17896     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17897                             : AtomicRMWExpansionKind::None;
17898   case AtomicRMWInst::Nand:
17899   case AtomicRMWInst::Max:
17900   case AtomicRMWInst::Min:
17901   case AtomicRMWInst::UMax:
17902   case AtomicRMWInst::UMin:
17903     // These always require a non-trivial set of data operations on x86. We must
17904     // use a cmpxchg loop.
17905     return AtomicRMWExpansionKind::CmpXChg;
17906   }
17907 }
17908
17909 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17910   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17911   // no-sse2). There isn't any reason to disable it if the target processor
17912   // supports it.
17913   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17914 }
17915
17916 LoadInst *
17917 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17918   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17919   const Type *MemType = AI->getType();
17920   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17921   // there is no benefit in turning such RMWs into loads, and it is actually
17922   // harmful as it introduces a mfence.
17923   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17924     return nullptr;
17925
17926   auto Builder = IRBuilder<>(AI);
17927   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17928   auto SynchScope = AI->getSynchScope();
17929   // We must restrict the ordering to avoid generating loads with Release or
17930   // ReleaseAcquire orderings.
17931   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17932   auto Ptr = AI->getPointerOperand();
17933
17934   // Before the load we need a fence. Here is an example lifted from
17935   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17936   // is required:
17937   // Thread 0:
17938   //   x.store(1, relaxed);
17939   //   r1 = y.fetch_add(0, release);
17940   // Thread 1:
17941   //   y.fetch_add(42, acquire);
17942   //   r2 = x.load(relaxed);
17943   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17944   // lowered to just a load without a fence. A mfence flushes the store buffer,
17945   // making the optimization clearly correct.
17946   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17947   // otherwise, we might be able to be more agressive on relaxed idempotent
17948   // rmw. In practice, they do not look useful, so we don't try to be
17949   // especially clever.
17950   if (SynchScope == SingleThread)
17951     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17952     // the IR level, so we must wrap it in an intrinsic.
17953     return nullptr;
17954
17955   if (!hasMFENCE(*Subtarget))
17956     // FIXME: it might make sense to use a locked operation here but on a
17957     // different cache-line to prevent cache-line bouncing. In practice it
17958     // is probably a small win, and x86 processors without mfence are rare
17959     // enough that we do not bother.
17960     return nullptr;
17961
17962   Function *MFence =
17963       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17964   Builder.CreateCall(MFence, {});
17965
17966   // Finally we can emit the atomic load.
17967   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17968           AI->getType()->getPrimitiveSizeInBits());
17969   Loaded->setAtomic(Order, SynchScope);
17970   AI->replaceAllUsesWith(Loaded);
17971   AI->eraseFromParent();
17972   return Loaded;
17973 }
17974
17975 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17976                                  SelectionDAG &DAG) {
17977   SDLoc dl(Op);
17978   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17979     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17980   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17981     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17982
17983   // The only fence that needs an instruction is a sequentially-consistent
17984   // cross-thread fence.
17985   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17986     if (hasMFENCE(*Subtarget))
17987       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17988
17989     SDValue Chain = Op.getOperand(0);
17990     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17991     SDValue Ops[] = {
17992       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17993       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17994       DAG.getRegister(0, MVT::i32),            // Index
17995       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17996       DAG.getRegister(0, MVT::i32),            // Segment.
17997       Zero,
17998       Chain
17999     };
18000     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18001     return SDValue(Res, 0);
18002   }
18003
18004   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18005   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18006 }
18007
18008 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18009                              SelectionDAG &DAG) {
18010   MVT T = Op.getSimpleValueType();
18011   SDLoc DL(Op);
18012   unsigned Reg = 0;
18013   unsigned size = 0;
18014   switch(T.SimpleTy) {
18015   default: llvm_unreachable("Invalid value type!");
18016   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18017   case MVT::i16: Reg = X86::AX;  size = 2; break;
18018   case MVT::i32: Reg = X86::EAX; size = 4; break;
18019   case MVT::i64:
18020     assert(Subtarget->is64Bit() && "Node not type legal!");
18021     Reg = X86::RAX; size = 8;
18022     break;
18023   }
18024   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18025                                   Op.getOperand(2), SDValue());
18026   SDValue Ops[] = { cpIn.getValue(0),
18027                     Op.getOperand(1),
18028                     Op.getOperand(3),
18029                     DAG.getTargetConstant(size, DL, MVT::i8),
18030                     cpIn.getValue(1) };
18031   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18032   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18033   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18034                                            Ops, T, MMO);
18035
18036   SDValue cpOut =
18037     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18038   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18039                                       MVT::i32, cpOut.getValue(2));
18040   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18041                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18042                                 EFLAGS);
18043
18044   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18045   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18046   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18047   return SDValue();
18048 }
18049
18050 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18051                             SelectionDAG &DAG) {
18052   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18053   MVT DstVT = Op.getSimpleValueType();
18054
18055   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18056     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18057     if (DstVT != MVT::f64)
18058       // This conversion needs to be expanded.
18059       return SDValue();
18060
18061     SDValue InVec = Op->getOperand(0);
18062     SDLoc dl(Op);
18063     unsigned NumElts = SrcVT.getVectorNumElements();
18064     EVT SVT = SrcVT.getVectorElementType();
18065
18066     // Widen the vector in input in the case of MVT::v2i32.
18067     // Example: from MVT::v2i32 to MVT::v4i32.
18068     SmallVector<SDValue, 16> Elts;
18069     for (unsigned i = 0, e = NumElts; i != e; ++i)
18070       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18071                                  DAG.getIntPtrConstant(i, dl)));
18072
18073     // Explicitly mark the extra elements as Undef.
18074     Elts.append(NumElts, DAG.getUNDEF(SVT));
18075
18076     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18077     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18078     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18079     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18080                        DAG.getIntPtrConstant(0, dl));
18081   }
18082
18083   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18084          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18085   assert((DstVT == MVT::i64 ||
18086           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18087          "Unexpected custom BITCAST");
18088   // i64 <=> MMX conversions are Legal.
18089   if (SrcVT==MVT::i64 && DstVT.isVector())
18090     return Op;
18091   if (DstVT==MVT::i64 && SrcVT.isVector())
18092     return Op;
18093   // MMX <=> MMX conversions are Legal.
18094   if (SrcVT.isVector() && DstVT.isVector())
18095     return Op;
18096   // All other conversions need to be expanded.
18097   return SDValue();
18098 }
18099
18100 /// Compute the horizontal sum of bytes in V for the elements of VT.
18101 ///
18102 /// Requires V to be a byte vector and VT to be an integer vector type with
18103 /// wider elements than V's type. The width of the elements of VT determines
18104 /// how many bytes of V are summed horizontally to produce each element of the
18105 /// result.
18106 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18107                                       const X86Subtarget *Subtarget,
18108                                       SelectionDAG &DAG) {
18109   SDLoc DL(V);
18110   MVT ByteVecVT = V.getSimpleValueType();
18111   MVT EltVT = VT.getVectorElementType();
18112   int NumElts = VT.getVectorNumElements();
18113   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18114          "Expected value to have byte element type.");
18115   assert(EltVT != MVT::i8 &&
18116          "Horizontal byte sum only makes sense for wider elements!");
18117   unsigned VecSize = VT.getSizeInBits();
18118   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18119
18120   // PSADBW instruction horizontally add all bytes and leave the result in i64
18121   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18122   if (EltVT == MVT::i64) {
18123     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18124     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18125     return DAG.getBitcast(VT, V);
18126   }
18127
18128   if (EltVT == MVT::i32) {
18129     // We unpack the low half and high half into i32s interleaved with zeros so
18130     // that we can use PSADBW to horizontally sum them. The most useful part of
18131     // this is that it lines up the results of two PSADBW instructions to be
18132     // two v2i64 vectors which concatenated are the 4 population counts. We can
18133     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18134     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18135     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18136     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18137
18138     // Do the horizontal sums into two v2i64s.
18139     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18140     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18141                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18142     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18143                        DAG.getBitcast(ByteVecVT, High), Zeros);
18144
18145     // Merge them together.
18146     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18147     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18148                     DAG.getBitcast(ShortVecVT, Low),
18149                     DAG.getBitcast(ShortVecVT, High));
18150
18151     return DAG.getBitcast(VT, V);
18152   }
18153
18154   // The only element type left is i16.
18155   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18156
18157   // To obtain pop count for each i16 element starting from the pop count for
18158   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18159   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18160   // directly supported.
18161   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18162   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18163   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18164   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18165                   DAG.getBitcast(ByteVecVT, V));
18166   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18167 }
18168
18169 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18170                                         const X86Subtarget *Subtarget,
18171                                         SelectionDAG &DAG) {
18172   MVT VT = Op.getSimpleValueType();
18173   MVT EltVT = VT.getVectorElementType();
18174   unsigned VecSize = VT.getSizeInBits();
18175
18176   // Implement a lookup table in register by using an algorithm based on:
18177   // http://wm.ite.pl/articles/sse-popcount.html
18178   //
18179   // The general idea is that every lower byte nibble in the input vector is an
18180   // index into a in-register pre-computed pop count table. We then split up the
18181   // input vector in two new ones: (1) a vector with only the shifted-right
18182   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18183   // masked out higher ones) for each byte. PSHUB is used separately with both
18184   // to index the in-register table. Next, both are added and the result is a
18185   // i8 vector where each element contains the pop count for input byte.
18186   //
18187   // To obtain the pop count for elements != i8, we follow up with the same
18188   // approach and use additional tricks as described below.
18189   //
18190   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18191                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18192                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18193                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18194
18195   int NumByteElts = VecSize / 8;
18196   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18197   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18198   SmallVector<SDValue, 16> LUTVec;
18199   for (int i = 0; i < NumByteElts; ++i)
18200     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18201   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18202   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18203                                   DAG.getConstant(0x0F, DL, MVT::i8));
18204   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18205
18206   // High nibbles
18207   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18208   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18209   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18210
18211   // Low nibbles
18212   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18213
18214   // The input vector is used as the shuffle mask that index elements into the
18215   // LUT. After counting low and high nibbles, add the vector to obtain the
18216   // final pop count per i8 element.
18217   SDValue HighPopCnt =
18218       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18219   SDValue LowPopCnt =
18220       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18221   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18222
18223   if (EltVT == MVT::i8)
18224     return PopCnt;
18225
18226   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18227 }
18228
18229 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18230                                        const X86Subtarget *Subtarget,
18231                                        SelectionDAG &DAG) {
18232   MVT VT = Op.getSimpleValueType();
18233   assert(VT.is128BitVector() &&
18234          "Only 128-bit vector bitmath lowering supported.");
18235
18236   int VecSize = VT.getSizeInBits();
18237   MVT EltVT = VT.getVectorElementType();
18238   int Len = EltVT.getSizeInBits();
18239
18240   // This is the vectorized version of the "best" algorithm from
18241   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18242   // with a minor tweak to use a series of adds + shifts instead of vector
18243   // multiplications. Implemented for all integer vector types. We only use
18244   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18245   // much faster, even faster than using native popcnt instructions.
18246
18247   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18248     MVT VT = V.getSimpleValueType();
18249     SmallVector<SDValue, 32> Shifters(
18250         VT.getVectorNumElements(),
18251         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18252     return DAG.getNode(OpCode, DL, VT, V,
18253                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18254   };
18255   auto GetMask = [&](SDValue V, APInt Mask) {
18256     MVT VT = V.getSimpleValueType();
18257     SmallVector<SDValue, 32> Masks(
18258         VT.getVectorNumElements(),
18259         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18260     return DAG.getNode(ISD::AND, DL, VT, V,
18261                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18262   };
18263
18264   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18265   // x86, so set the SRL type to have elements at least i16 wide. This is
18266   // correct because all of our SRLs are followed immediately by a mask anyways
18267   // that handles any bits that sneak into the high bits of the byte elements.
18268   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18269
18270   SDValue V = Op;
18271
18272   // v = v - ((v >> 1) & 0x55555555...)
18273   SDValue Srl =
18274       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18275   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18276   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18277
18278   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18279   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18280   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18281   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18282   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18283
18284   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18285   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18286   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18287   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18288
18289   // At this point, V contains the byte-wise population count, and we are
18290   // merely doing a horizontal sum if necessary to get the wider element
18291   // counts.
18292   if (EltVT == MVT::i8)
18293     return V;
18294
18295   return LowerHorizontalByteSum(
18296       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18297       DAG);
18298 }
18299
18300 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18301                                 SelectionDAG &DAG) {
18302   MVT VT = Op.getSimpleValueType();
18303   // FIXME: Need to add AVX-512 support here!
18304   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18305          "Unknown CTPOP type to handle");
18306   SDLoc DL(Op.getNode());
18307   SDValue Op0 = Op.getOperand(0);
18308
18309   if (!Subtarget->hasSSSE3()) {
18310     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18311     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18312     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18313   }
18314
18315   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18316     unsigned NumElems = VT.getVectorNumElements();
18317
18318     // Extract each 128-bit vector, compute pop count and concat the result.
18319     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18320     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18321
18322     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18323                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18324                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18325   }
18326
18327   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18328 }
18329
18330 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18331                           SelectionDAG &DAG) {
18332   assert(Op.getValueType().isVector() &&
18333          "We only do custom lowering for vector population count.");
18334   return LowerVectorCTPOP(Op, Subtarget, DAG);
18335 }
18336
18337 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18338   SDNode *Node = Op.getNode();
18339   SDLoc dl(Node);
18340   EVT T = Node->getValueType(0);
18341   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18342                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18343   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18344                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18345                        Node->getOperand(0),
18346                        Node->getOperand(1), negOp,
18347                        cast<AtomicSDNode>(Node)->getMemOperand(),
18348                        cast<AtomicSDNode>(Node)->getOrdering(),
18349                        cast<AtomicSDNode>(Node)->getSynchScope());
18350 }
18351
18352 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18353   SDNode *Node = Op.getNode();
18354   SDLoc dl(Node);
18355   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18356
18357   // Convert seq_cst store -> xchg
18358   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18359   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18360   //        (The only way to get a 16-byte store is cmpxchg16b)
18361   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18362   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18363       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18364     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18365                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18366                                  Node->getOperand(0),
18367                                  Node->getOperand(1), Node->getOperand(2),
18368                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18369                                  cast<AtomicSDNode>(Node)->getOrdering(),
18370                                  cast<AtomicSDNode>(Node)->getSynchScope());
18371     return Swap.getValue(1);
18372   }
18373   // Other atomic stores have a simple pattern.
18374   return Op;
18375 }
18376
18377 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18378   EVT VT = Op.getNode()->getSimpleValueType(0);
18379
18380   // Let legalize expand this if it isn't a legal type yet.
18381   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18382     return SDValue();
18383
18384   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18385
18386   unsigned Opc;
18387   bool ExtraOp = false;
18388   switch (Op.getOpcode()) {
18389   default: llvm_unreachable("Invalid code");
18390   case ISD::ADDC: Opc = X86ISD::ADD; break;
18391   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18392   case ISD::SUBC: Opc = X86ISD::SUB; break;
18393   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18394   }
18395
18396   if (!ExtraOp)
18397     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18398                        Op.getOperand(1));
18399   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18400                      Op.getOperand(1), Op.getOperand(2));
18401 }
18402
18403 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18404                             SelectionDAG &DAG) {
18405   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18406
18407   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18408   // which returns the values as { float, float } (in XMM0) or
18409   // { double, double } (which is returned in XMM0, XMM1).
18410   SDLoc dl(Op);
18411   SDValue Arg = Op.getOperand(0);
18412   EVT ArgVT = Arg.getValueType();
18413   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18414
18415   TargetLowering::ArgListTy Args;
18416   TargetLowering::ArgListEntry Entry;
18417
18418   Entry.Node = Arg;
18419   Entry.Ty = ArgTy;
18420   Entry.isSExt = false;
18421   Entry.isZExt = false;
18422   Args.push_back(Entry);
18423
18424   bool isF64 = ArgVT == MVT::f64;
18425   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18426   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18427   // the results are returned via SRet in memory.
18428   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18429   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18430   SDValue Callee =
18431       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18432
18433   Type *RetTy = isF64
18434     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18435     : (Type*)VectorType::get(ArgTy, 4);
18436
18437   TargetLowering::CallLoweringInfo CLI(DAG);
18438   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18439     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18440
18441   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18442
18443   if (isF64)
18444     // Returned in xmm0 and xmm1.
18445     return CallResult.first;
18446
18447   // Returned in bits 0:31 and 32:64 xmm0.
18448   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18449                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18450   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18451                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18452   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18453   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18454 }
18455
18456 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18457                              SelectionDAG &DAG) {
18458   assert(Subtarget->hasAVX512() &&
18459          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18460
18461   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18462   EVT VT = N->getValue().getValueType();
18463   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18464   SDLoc dl(Op);
18465
18466   // X86 scatter kills mask register, so its type should be added to
18467   // the list of return values
18468   if (N->getNumValues() == 1) {
18469     SDValue Index = N->getIndex();
18470     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18471         !Index.getValueType().is512BitVector())
18472       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18473
18474     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18475     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18476                       N->getOperand(3), Index };
18477
18478     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18479     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18480     return SDValue(NewScatter.getNode(), 0);
18481   }
18482   return Op;
18483 }
18484
18485 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18486                             SelectionDAG &DAG) {
18487   assert(Subtarget->hasAVX512() &&
18488          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18489
18490   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18491   EVT VT = Op.getValueType();
18492   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18493   SDLoc dl(Op);
18494
18495   SDValue Index = N->getIndex();
18496   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18497       !Index.getValueType().is512BitVector()) {
18498     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18499     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18500                       N->getOperand(3), Index };
18501     DAG.UpdateNodeOperands(N, Ops);
18502   }
18503   return Op;
18504 }
18505
18506 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18507                                                     SelectionDAG &DAG) const {
18508   // TODO: Eventually, the lowering of these nodes should be informed by or
18509   // deferred to the GC strategy for the function in which they appear. For
18510   // now, however, they must be lowered to something. Since they are logically
18511   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18512   // require special handling for these nodes), lower them as literal NOOPs for
18513   // the time being.
18514   SmallVector<SDValue, 2> Ops;
18515
18516   Ops.push_back(Op.getOperand(0));
18517   if (Op->getGluedNode())
18518     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18519
18520   SDLoc OpDL(Op);
18521   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18522   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18523
18524   return NOOP;
18525 }
18526
18527 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18528                                                   SelectionDAG &DAG) const {
18529   // TODO: Eventually, the lowering of these nodes should be informed by or
18530   // deferred to the GC strategy for the function in which they appear. For
18531   // now, however, they must be lowered to something. Since they are logically
18532   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18533   // require special handling for these nodes), lower them as literal NOOPs for
18534   // the time being.
18535   SmallVector<SDValue, 2> Ops;
18536
18537   Ops.push_back(Op.getOperand(0));
18538   if (Op->getGluedNode())
18539     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18540
18541   SDLoc OpDL(Op);
18542   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18543   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18544
18545   return NOOP;
18546 }
18547
18548 /// LowerOperation - Provide custom lowering hooks for some operations.
18549 ///
18550 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18551   switch (Op.getOpcode()) {
18552   default: llvm_unreachable("Should not custom lower this!");
18553   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18554   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18555     return LowerCMP_SWAP(Op, Subtarget, DAG);
18556   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18557   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18558   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18559   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18560   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18561   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18562   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18563   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18564   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18565   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18566   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18567   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18568   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18569   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18570   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18571   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18572   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18573   case ISD::SHL_PARTS:
18574   case ISD::SRA_PARTS:
18575   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18576   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18577   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18578   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18579   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18580   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18581   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18582   case ISD::SIGN_EXTEND_VECTOR_INREG:
18583     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18584   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18585   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18586   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18587   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18588   case ISD::FABS:
18589   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18590   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18591   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18592   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18593   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18594   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18595   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18596   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18597   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18598   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18599   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18600   case ISD::INTRINSIC_VOID:
18601   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18602   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18603   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18604   case ISD::FRAME_TO_ARGS_OFFSET:
18605                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18606   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18607   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18608   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18609   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18610   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18611   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18612   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18613   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18614   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18615   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18616   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18617   case ISD::UMUL_LOHI:
18618   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18619   case ISD::SRA:
18620   case ISD::SRL:
18621   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18622   case ISD::SADDO:
18623   case ISD::UADDO:
18624   case ISD::SSUBO:
18625   case ISD::USUBO:
18626   case ISD::SMULO:
18627   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18628   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18629   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18630   case ISD::ADDC:
18631   case ISD::ADDE:
18632   case ISD::SUBC:
18633   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18634   case ISD::ADD:                return LowerADD(Op, DAG);
18635   case ISD::SUB:                return LowerSUB(Op, DAG);
18636   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18637   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18638   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18639   case ISD::GC_TRANSITION_START:
18640                                 return LowerGC_TRANSITION_START(Op, DAG);
18641   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18642   }
18643 }
18644
18645 /// ReplaceNodeResults - Replace a node with an illegal result type
18646 /// with a new node built out of custom code.
18647 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18648                                            SmallVectorImpl<SDValue>&Results,
18649                                            SelectionDAG &DAG) const {
18650   SDLoc dl(N);
18651   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18652   switch (N->getOpcode()) {
18653   default:
18654     llvm_unreachable("Do not know how to custom type legalize this operation!");
18655   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18656   case X86ISD::FMINC:
18657   case X86ISD::FMIN:
18658   case X86ISD::FMAXC:
18659   case X86ISD::FMAX: {
18660     EVT VT = N->getValueType(0);
18661     if (VT != MVT::v2f32)
18662       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18663     SDValue UNDEF = DAG.getUNDEF(VT);
18664     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18665                               N->getOperand(0), UNDEF);
18666     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18667                               N->getOperand(1), UNDEF);
18668     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18669     return;
18670   }
18671   case ISD::SIGN_EXTEND_INREG:
18672   case ISD::ADDC:
18673   case ISD::ADDE:
18674   case ISD::SUBC:
18675   case ISD::SUBE:
18676     // We don't want to expand or promote these.
18677     return;
18678   case ISD::SDIV:
18679   case ISD::UDIV:
18680   case ISD::SREM:
18681   case ISD::UREM:
18682   case ISD::SDIVREM:
18683   case ISD::UDIVREM: {
18684     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18685     Results.push_back(V);
18686     return;
18687   }
18688   case ISD::FP_TO_SINT:
18689     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18690     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18691     if (N->getOperand(0).getValueType() == MVT::f16)
18692       break;
18693     // fallthrough
18694   case ISD::FP_TO_UINT: {
18695     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18696
18697     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18698       return;
18699
18700     std::pair<SDValue,SDValue> Vals =
18701         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18702     SDValue FIST = Vals.first, StackSlot = Vals.second;
18703     if (FIST.getNode()) {
18704       EVT VT = N->getValueType(0);
18705       // Return a load from the stack slot.
18706       if (StackSlot.getNode())
18707         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18708                                       MachinePointerInfo(),
18709                                       false, false, false, 0));
18710       else
18711         Results.push_back(FIST);
18712     }
18713     return;
18714   }
18715   case ISD::UINT_TO_FP: {
18716     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18717     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18718         N->getValueType(0) != MVT::v2f32)
18719       return;
18720     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18721                                  N->getOperand(0));
18722     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18723                                      MVT::f64);
18724     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18725     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18726                              DAG.getBitcast(MVT::v2i64, VBias));
18727     Or = DAG.getBitcast(MVT::v2f64, Or);
18728     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18729     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18730     return;
18731   }
18732   case ISD::FP_ROUND: {
18733     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18734         return;
18735     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18736     Results.push_back(V);
18737     return;
18738   }
18739   case ISD::FP_EXTEND: {
18740     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18741     // No other ValueType for FP_EXTEND should reach this point.
18742     assert(N->getValueType(0) == MVT::v2f32 &&
18743            "Do not know how to legalize this Node");
18744     return;
18745   }
18746   case ISD::INTRINSIC_W_CHAIN: {
18747     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18748     switch (IntNo) {
18749     default : llvm_unreachable("Do not know how to custom type "
18750                                "legalize this intrinsic operation!");
18751     case Intrinsic::x86_rdtsc:
18752       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18753                                      Results);
18754     case Intrinsic::x86_rdtscp:
18755       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18756                                      Results);
18757     case Intrinsic::x86_rdpmc:
18758       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18759     }
18760   }
18761   case ISD::READCYCLECOUNTER: {
18762     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18763                                    Results);
18764   }
18765   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18766     EVT T = N->getValueType(0);
18767     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18768     bool Regs64bit = T == MVT::i128;
18769     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18770     SDValue cpInL, cpInH;
18771     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18772                         DAG.getConstant(0, dl, HalfT));
18773     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18774                         DAG.getConstant(1, dl, HalfT));
18775     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18776                              Regs64bit ? X86::RAX : X86::EAX,
18777                              cpInL, SDValue());
18778     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18779                              Regs64bit ? X86::RDX : X86::EDX,
18780                              cpInH, cpInL.getValue(1));
18781     SDValue swapInL, swapInH;
18782     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18783                           DAG.getConstant(0, dl, HalfT));
18784     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18785                           DAG.getConstant(1, dl, HalfT));
18786     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18787                                Regs64bit ? X86::RBX : X86::EBX,
18788                                swapInL, cpInH.getValue(1));
18789     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18790                                Regs64bit ? X86::RCX : X86::ECX,
18791                                swapInH, swapInL.getValue(1));
18792     SDValue Ops[] = { swapInH.getValue(0),
18793                       N->getOperand(1),
18794                       swapInH.getValue(1) };
18795     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18796     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18797     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18798                                   X86ISD::LCMPXCHG8_DAG;
18799     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18800     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18801                                         Regs64bit ? X86::RAX : X86::EAX,
18802                                         HalfT, Result.getValue(1));
18803     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18804                                         Regs64bit ? X86::RDX : X86::EDX,
18805                                         HalfT, cpOutL.getValue(2));
18806     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18807
18808     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18809                                         MVT::i32, cpOutH.getValue(2));
18810     SDValue Success =
18811         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18812                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18813     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18814
18815     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18816     Results.push_back(Success);
18817     Results.push_back(EFLAGS.getValue(1));
18818     return;
18819   }
18820   case ISD::ATOMIC_SWAP:
18821   case ISD::ATOMIC_LOAD_ADD:
18822   case ISD::ATOMIC_LOAD_SUB:
18823   case ISD::ATOMIC_LOAD_AND:
18824   case ISD::ATOMIC_LOAD_OR:
18825   case ISD::ATOMIC_LOAD_XOR:
18826   case ISD::ATOMIC_LOAD_NAND:
18827   case ISD::ATOMIC_LOAD_MIN:
18828   case ISD::ATOMIC_LOAD_MAX:
18829   case ISD::ATOMIC_LOAD_UMIN:
18830   case ISD::ATOMIC_LOAD_UMAX:
18831   case ISD::ATOMIC_LOAD: {
18832     // Delegate to generic TypeLegalization. Situations we can really handle
18833     // should have already been dealt with by AtomicExpandPass.cpp.
18834     break;
18835   }
18836   case ISD::BITCAST: {
18837     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18838     EVT DstVT = N->getValueType(0);
18839     EVT SrcVT = N->getOperand(0)->getValueType(0);
18840
18841     if (SrcVT != MVT::f64 ||
18842         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18843       return;
18844
18845     unsigned NumElts = DstVT.getVectorNumElements();
18846     EVT SVT = DstVT.getVectorElementType();
18847     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18848     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18849                                    MVT::v2f64, N->getOperand(0));
18850     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18851
18852     if (ExperimentalVectorWideningLegalization) {
18853       // If we are legalizing vectors by widening, we already have the desired
18854       // legal vector type, just return it.
18855       Results.push_back(ToVecInt);
18856       return;
18857     }
18858
18859     SmallVector<SDValue, 8> Elts;
18860     for (unsigned i = 0, e = NumElts; i != e; ++i)
18861       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18862                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18863
18864     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18865   }
18866   }
18867 }
18868
18869 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18870   switch ((X86ISD::NodeType)Opcode) {
18871   case X86ISD::FIRST_NUMBER:       break;
18872   case X86ISD::BSF:                return "X86ISD::BSF";
18873   case X86ISD::BSR:                return "X86ISD::BSR";
18874   case X86ISD::SHLD:               return "X86ISD::SHLD";
18875   case X86ISD::SHRD:               return "X86ISD::SHRD";
18876   case X86ISD::FAND:               return "X86ISD::FAND";
18877   case X86ISD::FANDN:              return "X86ISD::FANDN";
18878   case X86ISD::FOR:                return "X86ISD::FOR";
18879   case X86ISD::FXOR:               return "X86ISD::FXOR";
18880   case X86ISD::FILD:               return "X86ISD::FILD";
18881   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18882   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18883   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18884   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18885   case X86ISD::FLD:                return "X86ISD::FLD";
18886   case X86ISD::FST:                return "X86ISD::FST";
18887   case X86ISD::CALL:               return "X86ISD::CALL";
18888   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18889   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18890   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18891   case X86ISD::BT:                 return "X86ISD::BT";
18892   case X86ISD::CMP:                return "X86ISD::CMP";
18893   case X86ISD::COMI:               return "X86ISD::COMI";
18894   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18895   case X86ISD::CMPM:               return "X86ISD::CMPM";
18896   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18897   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18898   case X86ISD::SETCC:              return "X86ISD::SETCC";
18899   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18900   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18901   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18902   case X86ISD::CMOV:               return "X86ISD::CMOV";
18903   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18904   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18905   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18906   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18907   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18908   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18909   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18910   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
18911   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
18912   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
18913   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
18914   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
18915   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
18916   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
18917   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
18918   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
18919   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
18920   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
18921   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
18922   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
18923   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
18924   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
18925   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
18926   case X86ISD::HADD:               return "X86ISD::HADD";
18927   case X86ISD::HSUB:               return "X86ISD::HSUB";
18928   case X86ISD::FHADD:              return "X86ISD::FHADD";
18929   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
18930   case X86ISD::ABS:                return "X86ISD::ABS";
18931   case X86ISD::FMAX:               return "X86ISD::FMAX";
18932   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
18933   case X86ISD::FMIN:               return "X86ISD::FMIN";
18934   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18935   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18936   case X86ISD::FMINC:              return "X86ISD::FMINC";
18937   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18938   case X86ISD::FRCP:               return "X86ISD::FRCP";
18939   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
18940   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
18941   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18942   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18943   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18944   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18945   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18946   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18947   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18948   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18949   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18950   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18951   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18952   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18953   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18954   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18955   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18956   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18957   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18958   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18959   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18960   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18961   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18962   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
18963   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
18964   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18965   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18966   case X86ISD::VSHL:               return "X86ISD::VSHL";
18967   case X86ISD::VSRL:               return "X86ISD::VSRL";
18968   case X86ISD::VSRA:               return "X86ISD::VSRA";
18969   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18970   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18971   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18972   case X86ISD::CMPP:               return "X86ISD::CMPP";
18973   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18974   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18975   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18976   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18977   case X86ISD::ADD:                return "X86ISD::ADD";
18978   case X86ISD::SUB:                return "X86ISD::SUB";
18979   case X86ISD::ADC:                return "X86ISD::ADC";
18980   case X86ISD::SBB:                return "X86ISD::SBB";
18981   case X86ISD::SMUL:               return "X86ISD::SMUL";
18982   case X86ISD::UMUL:               return "X86ISD::UMUL";
18983   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18984   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18985   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18986   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18987   case X86ISD::INC:                return "X86ISD::INC";
18988   case X86ISD::DEC:                return "X86ISD::DEC";
18989   case X86ISD::OR:                 return "X86ISD::OR";
18990   case X86ISD::XOR:                return "X86ISD::XOR";
18991   case X86ISD::AND:                return "X86ISD::AND";
18992   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18993   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18994   case X86ISD::PTEST:              return "X86ISD::PTEST";
18995   case X86ISD::TESTP:              return "X86ISD::TESTP";
18996   case X86ISD::TESTM:              return "X86ISD::TESTM";
18997   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18998   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18999   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19000   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19001   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19002   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19003   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19004   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19005   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19006   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19007   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19008   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19009   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19010   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19011   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19012   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19013   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19014   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19015   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19016   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19017   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19018   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19019   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19020   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19021   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19022   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19023   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19024   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19025   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19026   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19027   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19028   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19029   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19030   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19031   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19032   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19033   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19034   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19035   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19036   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19037   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19038   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19039   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19040   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19041   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19042   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19043   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19044   case X86ISD::SAHF:               return "X86ISD::SAHF";
19045   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19046   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19047   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19048   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19049   case X86ISD::FMADD:              return "X86ISD::FMADD";
19050   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19051   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19052   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19053   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19054   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19055   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19056   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19057   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19058   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19059   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19060   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19061   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19062   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19063   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19064   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19065   case X86ISD::XTEST:              return "X86ISD::XTEST";
19066   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19067   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19068   case X86ISD::SELECT:             return "X86ISD::SELECT";
19069   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19070   case X86ISD::RCP28:              return "X86ISD::RCP28";
19071   case X86ISD::EXP2:               return "X86ISD::EXP2";
19072   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19073   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19074   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19075   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19076   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19077   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19078   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19079   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19080   case X86ISD::ADDS:               return "X86ISD::ADDS";
19081   case X86ISD::SUBS:               return "X86ISD::SUBS";
19082   case X86ISD::AVG:                return "X86ISD::AVG";
19083   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19084   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19085   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19086   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19087   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19088   }
19089   return nullptr;
19090 }
19091
19092 // isLegalAddressingMode - Return true if the addressing mode represented
19093 // by AM is legal for this target, for a load/store of the specified type.
19094 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19095                                               const AddrMode &AM, Type *Ty,
19096                                               unsigned AS) const {
19097   // X86 supports extremely general addressing modes.
19098   CodeModel::Model M = getTargetMachine().getCodeModel();
19099   Reloc::Model R = getTargetMachine().getRelocationModel();
19100
19101   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19102   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19103     return false;
19104
19105   if (AM.BaseGV) {
19106     unsigned GVFlags =
19107       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19108
19109     // If a reference to this global requires an extra load, we can't fold it.
19110     if (isGlobalStubReference(GVFlags))
19111       return false;
19112
19113     // If BaseGV requires a register for the PIC base, we cannot also have a
19114     // BaseReg specified.
19115     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19116       return false;
19117
19118     // If lower 4G is not available, then we must use rip-relative addressing.
19119     if ((M != CodeModel::Small || R != Reloc::Static) &&
19120         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19121       return false;
19122   }
19123
19124   switch (AM.Scale) {
19125   case 0:
19126   case 1:
19127   case 2:
19128   case 4:
19129   case 8:
19130     // These scales always work.
19131     break;
19132   case 3:
19133   case 5:
19134   case 9:
19135     // These scales are formed with basereg+scalereg.  Only accept if there is
19136     // no basereg yet.
19137     if (AM.HasBaseReg)
19138       return false;
19139     break;
19140   default:  // Other stuff never works.
19141     return false;
19142   }
19143
19144   return true;
19145 }
19146
19147 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19148   unsigned Bits = Ty->getScalarSizeInBits();
19149
19150   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19151   // particularly cheaper than those without.
19152   if (Bits == 8)
19153     return false;
19154
19155   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19156   // variable shifts just as cheap as scalar ones.
19157   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19158     return false;
19159
19160   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19161   // fully general vector.
19162   return true;
19163 }
19164
19165 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19166   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19167     return false;
19168   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19169   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19170   return NumBits1 > NumBits2;
19171 }
19172
19173 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19174   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19175     return false;
19176
19177   if (!isTypeLegal(EVT::getEVT(Ty1)))
19178     return false;
19179
19180   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19181
19182   // Assuming the caller doesn't have a zeroext or signext return parameter,
19183   // truncation all the way down to i1 is valid.
19184   return true;
19185 }
19186
19187 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19188   return isInt<32>(Imm);
19189 }
19190
19191 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19192   // Can also use sub to handle negated immediates.
19193   return isInt<32>(Imm);
19194 }
19195
19196 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19197   if (!VT1.isInteger() || !VT2.isInteger())
19198     return false;
19199   unsigned NumBits1 = VT1.getSizeInBits();
19200   unsigned NumBits2 = VT2.getSizeInBits();
19201   return NumBits1 > NumBits2;
19202 }
19203
19204 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19205   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19206   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19207 }
19208
19209 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19210   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19211   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19212 }
19213
19214 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19215   EVT VT1 = Val.getValueType();
19216   if (isZExtFree(VT1, VT2))
19217     return true;
19218
19219   if (Val.getOpcode() != ISD::LOAD)
19220     return false;
19221
19222   if (!VT1.isSimple() || !VT1.isInteger() ||
19223       !VT2.isSimple() || !VT2.isInteger())
19224     return false;
19225
19226   switch (VT1.getSimpleVT().SimpleTy) {
19227   default: break;
19228   case MVT::i8:
19229   case MVT::i16:
19230   case MVT::i32:
19231     // X86 has 8, 16, and 32-bit zero-extending loads.
19232     return true;
19233   }
19234
19235   return false;
19236 }
19237
19238 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19239
19240 bool
19241 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19242   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19243     return false;
19244
19245   VT = VT.getScalarType();
19246
19247   if (!VT.isSimple())
19248     return false;
19249
19250   switch (VT.getSimpleVT().SimpleTy) {
19251   case MVT::f32:
19252   case MVT::f64:
19253     return true;
19254   default:
19255     break;
19256   }
19257
19258   return false;
19259 }
19260
19261 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19262   // i16 instructions are longer (0x66 prefix) and potentially slower.
19263   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19264 }
19265
19266 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19267 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19268 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19269 /// are assumed to be legal.
19270 bool
19271 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19272                                       EVT VT) const {
19273   if (!VT.isSimple())
19274     return false;
19275
19276   // Not for i1 vectors
19277   if (VT.getScalarType() == MVT::i1)
19278     return false;
19279
19280   // Very little shuffling can be done for 64-bit vectors right now.
19281   if (VT.getSizeInBits() == 64)
19282     return false;
19283
19284   // We only care that the types being shuffled are legal. The lowering can
19285   // handle any possible shuffle mask that results.
19286   return isTypeLegal(VT.getSimpleVT());
19287 }
19288
19289 bool
19290 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19291                                           EVT VT) const {
19292   // Just delegate to the generic legality, clear masks aren't special.
19293   return isShuffleMaskLegal(Mask, VT);
19294 }
19295
19296 //===----------------------------------------------------------------------===//
19297 //                           X86 Scheduler Hooks
19298 //===----------------------------------------------------------------------===//
19299
19300 /// Utility function to emit xbegin specifying the start of an RTM region.
19301 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19302                                      const TargetInstrInfo *TII) {
19303   DebugLoc DL = MI->getDebugLoc();
19304
19305   const BasicBlock *BB = MBB->getBasicBlock();
19306   MachineFunction::iterator I = MBB;
19307   ++I;
19308
19309   // For the v = xbegin(), we generate
19310   //
19311   // thisMBB:
19312   //  xbegin sinkMBB
19313   //
19314   // mainMBB:
19315   //  eax = -1
19316   //
19317   // sinkMBB:
19318   //  v = eax
19319
19320   MachineBasicBlock *thisMBB = MBB;
19321   MachineFunction *MF = MBB->getParent();
19322   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19323   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19324   MF->insert(I, mainMBB);
19325   MF->insert(I, sinkMBB);
19326
19327   // Transfer the remainder of BB and its successor edges to sinkMBB.
19328   sinkMBB->splice(sinkMBB->begin(), MBB,
19329                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19330   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19331
19332   // thisMBB:
19333   //  xbegin sinkMBB
19334   //  # fallthrough to mainMBB
19335   //  # abortion to sinkMBB
19336   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19337   thisMBB->addSuccessor(mainMBB);
19338   thisMBB->addSuccessor(sinkMBB);
19339
19340   // mainMBB:
19341   //  EAX = -1
19342   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19343   mainMBB->addSuccessor(sinkMBB);
19344
19345   // sinkMBB:
19346   // EAX is live into the sinkMBB
19347   sinkMBB->addLiveIn(X86::EAX);
19348   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19349           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19350     .addReg(X86::EAX);
19351
19352   MI->eraseFromParent();
19353   return sinkMBB;
19354 }
19355
19356 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19357 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19358 // in the .td file.
19359 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19360                                        const TargetInstrInfo *TII) {
19361   unsigned Opc;
19362   switch (MI->getOpcode()) {
19363   default: llvm_unreachable("illegal opcode!");
19364   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19365   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19366   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19367   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19368   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19369   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19370   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19371   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19372   }
19373
19374   DebugLoc dl = MI->getDebugLoc();
19375   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19376
19377   unsigned NumArgs = MI->getNumOperands();
19378   for (unsigned i = 1; i < NumArgs; ++i) {
19379     MachineOperand &Op = MI->getOperand(i);
19380     if (!(Op.isReg() && Op.isImplicit()))
19381       MIB.addOperand(Op);
19382   }
19383   if (MI->hasOneMemOperand())
19384     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19385
19386   BuildMI(*BB, MI, dl,
19387     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19388     .addReg(X86::XMM0);
19389
19390   MI->eraseFromParent();
19391   return BB;
19392 }
19393
19394 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19395 // defs in an instruction pattern
19396 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19397                                        const TargetInstrInfo *TII) {
19398   unsigned Opc;
19399   switch (MI->getOpcode()) {
19400   default: llvm_unreachable("illegal opcode!");
19401   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19402   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19403   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19404   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19405   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19406   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19407   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19408   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19409   }
19410
19411   DebugLoc dl = MI->getDebugLoc();
19412   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19413
19414   unsigned NumArgs = MI->getNumOperands(); // remove the results
19415   for (unsigned i = 1; i < NumArgs; ++i) {
19416     MachineOperand &Op = MI->getOperand(i);
19417     if (!(Op.isReg() && Op.isImplicit()))
19418       MIB.addOperand(Op);
19419   }
19420   if (MI->hasOneMemOperand())
19421     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19422
19423   BuildMI(*BB, MI, dl,
19424     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19425     .addReg(X86::ECX);
19426
19427   MI->eraseFromParent();
19428   return BB;
19429 }
19430
19431 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19432                                       const X86Subtarget *Subtarget) {
19433   DebugLoc dl = MI->getDebugLoc();
19434   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19435   // Address into RAX/EAX, other two args into ECX, EDX.
19436   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19437   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19438   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19439   for (int i = 0; i < X86::AddrNumOperands; ++i)
19440     MIB.addOperand(MI->getOperand(i));
19441
19442   unsigned ValOps = X86::AddrNumOperands;
19443   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19444     .addReg(MI->getOperand(ValOps).getReg());
19445   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19446     .addReg(MI->getOperand(ValOps+1).getReg());
19447
19448   // The instruction doesn't actually take any operands though.
19449   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19450
19451   MI->eraseFromParent(); // The pseudo is gone now.
19452   return BB;
19453 }
19454
19455 MachineBasicBlock *
19456 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19457                                                  MachineBasicBlock *MBB) const {
19458   // Emit va_arg instruction on X86-64.
19459
19460   // Operands to this pseudo-instruction:
19461   // 0  ) Output        : destination address (reg)
19462   // 1-5) Input         : va_list address (addr, i64mem)
19463   // 6  ) ArgSize       : Size (in bytes) of vararg type
19464   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19465   // 8  ) Align         : Alignment of type
19466   // 9  ) EFLAGS (implicit-def)
19467
19468   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19469   static_assert(X86::AddrNumOperands == 5,
19470                 "VAARG_64 assumes 5 address operands");
19471
19472   unsigned DestReg = MI->getOperand(0).getReg();
19473   MachineOperand &Base = MI->getOperand(1);
19474   MachineOperand &Scale = MI->getOperand(2);
19475   MachineOperand &Index = MI->getOperand(3);
19476   MachineOperand &Disp = MI->getOperand(4);
19477   MachineOperand &Segment = MI->getOperand(5);
19478   unsigned ArgSize = MI->getOperand(6).getImm();
19479   unsigned ArgMode = MI->getOperand(7).getImm();
19480   unsigned Align = MI->getOperand(8).getImm();
19481
19482   // Memory Reference
19483   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19484   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19485   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19486
19487   // Machine Information
19488   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19489   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19490   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19491   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19492   DebugLoc DL = MI->getDebugLoc();
19493
19494   // struct va_list {
19495   //   i32   gp_offset
19496   //   i32   fp_offset
19497   //   i64   overflow_area (address)
19498   //   i64   reg_save_area (address)
19499   // }
19500   // sizeof(va_list) = 24
19501   // alignment(va_list) = 8
19502
19503   unsigned TotalNumIntRegs = 6;
19504   unsigned TotalNumXMMRegs = 8;
19505   bool UseGPOffset = (ArgMode == 1);
19506   bool UseFPOffset = (ArgMode == 2);
19507   unsigned MaxOffset = TotalNumIntRegs * 8 +
19508                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19509
19510   /* Align ArgSize to a multiple of 8 */
19511   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19512   bool NeedsAlign = (Align > 8);
19513
19514   MachineBasicBlock *thisMBB = MBB;
19515   MachineBasicBlock *overflowMBB;
19516   MachineBasicBlock *offsetMBB;
19517   MachineBasicBlock *endMBB;
19518
19519   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19520   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19521   unsigned OffsetReg = 0;
19522
19523   if (!UseGPOffset && !UseFPOffset) {
19524     // If we only pull from the overflow region, we don't create a branch.
19525     // We don't need to alter control flow.
19526     OffsetDestReg = 0; // unused
19527     OverflowDestReg = DestReg;
19528
19529     offsetMBB = nullptr;
19530     overflowMBB = thisMBB;
19531     endMBB = thisMBB;
19532   } else {
19533     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19534     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19535     // If not, pull from overflow_area. (branch to overflowMBB)
19536     //
19537     //       thisMBB
19538     //         |     .
19539     //         |        .
19540     //     offsetMBB   overflowMBB
19541     //         |        .
19542     //         |     .
19543     //        endMBB
19544
19545     // Registers for the PHI in endMBB
19546     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19547     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19548
19549     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19550     MachineFunction *MF = MBB->getParent();
19551     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19552     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19553     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19554
19555     MachineFunction::iterator MBBIter = MBB;
19556     ++MBBIter;
19557
19558     // Insert the new basic blocks
19559     MF->insert(MBBIter, offsetMBB);
19560     MF->insert(MBBIter, overflowMBB);
19561     MF->insert(MBBIter, endMBB);
19562
19563     // Transfer the remainder of MBB and its successor edges to endMBB.
19564     endMBB->splice(endMBB->begin(), thisMBB,
19565                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19566     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19567
19568     // Make offsetMBB and overflowMBB successors of thisMBB
19569     thisMBB->addSuccessor(offsetMBB);
19570     thisMBB->addSuccessor(overflowMBB);
19571
19572     // endMBB is a successor of both offsetMBB and overflowMBB
19573     offsetMBB->addSuccessor(endMBB);
19574     overflowMBB->addSuccessor(endMBB);
19575
19576     // Load the offset value into a register
19577     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19578     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19579       .addOperand(Base)
19580       .addOperand(Scale)
19581       .addOperand(Index)
19582       .addDisp(Disp, UseFPOffset ? 4 : 0)
19583       .addOperand(Segment)
19584       .setMemRefs(MMOBegin, MMOEnd);
19585
19586     // Check if there is enough room left to pull this argument.
19587     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19588       .addReg(OffsetReg)
19589       .addImm(MaxOffset + 8 - ArgSizeA8);
19590
19591     // Branch to "overflowMBB" if offset >= max
19592     // Fall through to "offsetMBB" otherwise
19593     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19594       .addMBB(overflowMBB);
19595   }
19596
19597   // In offsetMBB, emit code to use the reg_save_area.
19598   if (offsetMBB) {
19599     assert(OffsetReg != 0);
19600
19601     // Read the reg_save_area address.
19602     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19603     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19604       .addOperand(Base)
19605       .addOperand(Scale)
19606       .addOperand(Index)
19607       .addDisp(Disp, 16)
19608       .addOperand(Segment)
19609       .setMemRefs(MMOBegin, MMOEnd);
19610
19611     // Zero-extend the offset
19612     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19613       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19614         .addImm(0)
19615         .addReg(OffsetReg)
19616         .addImm(X86::sub_32bit);
19617
19618     // Add the offset to the reg_save_area to get the final address.
19619     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19620       .addReg(OffsetReg64)
19621       .addReg(RegSaveReg);
19622
19623     // Compute the offset for the next argument
19624     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19625     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19626       .addReg(OffsetReg)
19627       .addImm(UseFPOffset ? 16 : 8);
19628
19629     // Store it back into the va_list.
19630     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19631       .addOperand(Base)
19632       .addOperand(Scale)
19633       .addOperand(Index)
19634       .addDisp(Disp, UseFPOffset ? 4 : 0)
19635       .addOperand(Segment)
19636       .addReg(NextOffsetReg)
19637       .setMemRefs(MMOBegin, MMOEnd);
19638
19639     // Jump to endMBB
19640     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19641       .addMBB(endMBB);
19642   }
19643
19644   //
19645   // Emit code to use overflow area
19646   //
19647
19648   // Load the overflow_area address into a register.
19649   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19650   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19651     .addOperand(Base)
19652     .addOperand(Scale)
19653     .addOperand(Index)
19654     .addDisp(Disp, 8)
19655     .addOperand(Segment)
19656     .setMemRefs(MMOBegin, MMOEnd);
19657
19658   // If we need to align it, do so. Otherwise, just copy the address
19659   // to OverflowDestReg.
19660   if (NeedsAlign) {
19661     // Align the overflow address
19662     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19663     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19664
19665     // aligned_addr = (addr + (align-1)) & ~(align-1)
19666     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19667       .addReg(OverflowAddrReg)
19668       .addImm(Align-1);
19669
19670     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19671       .addReg(TmpReg)
19672       .addImm(~(uint64_t)(Align-1));
19673   } else {
19674     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19675       .addReg(OverflowAddrReg);
19676   }
19677
19678   // Compute the next overflow address after this argument.
19679   // (the overflow address should be kept 8-byte aligned)
19680   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19681   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19682     .addReg(OverflowDestReg)
19683     .addImm(ArgSizeA8);
19684
19685   // Store the new overflow address.
19686   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19687     .addOperand(Base)
19688     .addOperand(Scale)
19689     .addOperand(Index)
19690     .addDisp(Disp, 8)
19691     .addOperand(Segment)
19692     .addReg(NextAddrReg)
19693     .setMemRefs(MMOBegin, MMOEnd);
19694
19695   // If we branched, emit the PHI to the front of endMBB.
19696   if (offsetMBB) {
19697     BuildMI(*endMBB, endMBB->begin(), DL,
19698             TII->get(X86::PHI), DestReg)
19699       .addReg(OffsetDestReg).addMBB(offsetMBB)
19700       .addReg(OverflowDestReg).addMBB(overflowMBB);
19701   }
19702
19703   // Erase the pseudo instruction
19704   MI->eraseFromParent();
19705
19706   return endMBB;
19707 }
19708
19709 MachineBasicBlock *
19710 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19711                                                  MachineInstr *MI,
19712                                                  MachineBasicBlock *MBB) const {
19713   // Emit code to save XMM registers to the stack. The ABI says that the
19714   // number of registers to save is given in %al, so it's theoretically
19715   // possible to do an indirect jump trick to avoid saving all of them,
19716   // however this code takes a simpler approach and just executes all
19717   // of the stores if %al is non-zero. It's less code, and it's probably
19718   // easier on the hardware branch predictor, and stores aren't all that
19719   // expensive anyway.
19720
19721   // Create the new basic blocks. One block contains all the XMM stores,
19722   // and one block is the final destination regardless of whether any
19723   // stores were performed.
19724   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19725   MachineFunction *F = MBB->getParent();
19726   MachineFunction::iterator MBBIter = MBB;
19727   ++MBBIter;
19728   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19729   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19730   F->insert(MBBIter, XMMSaveMBB);
19731   F->insert(MBBIter, EndMBB);
19732
19733   // Transfer the remainder of MBB and its successor edges to EndMBB.
19734   EndMBB->splice(EndMBB->begin(), MBB,
19735                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19736   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19737
19738   // The original block will now fall through to the XMM save block.
19739   MBB->addSuccessor(XMMSaveMBB);
19740   // The XMMSaveMBB will fall through to the end block.
19741   XMMSaveMBB->addSuccessor(EndMBB);
19742
19743   // Now add the instructions.
19744   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19745   DebugLoc DL = MI->getDebugLoc();
19746
19747   unsigned CountReg = MI->getOperand(0).getReg();
19748   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19749   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19750
19751   if (!Subtarget->isTargetWin64()) {
19752     // If %al is 0, branch around the XMM save block.
19753     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19754     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19755     MBB->addSuccessor(EndMBB);
19756   }
19757
19758   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19759   // that was just emitted, but clearly shouldn't be "saved".
19760   assert((MI->getNumOperands() <= 3 ||
19761           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19762           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19763          && "Expected last argument to be EFLAGS");
19764   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19765   // In the XMM save block, save all the XMM argument registers.
19766   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19767     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19768     MachineMemOperand *MMO =
19769       F->getMachineMemOperand(
19770           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19771         MachineMemOperand::MOStore,
19772         /*Size=*/16, /*Align=*/16);
19773     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19774       .addFrameIndex(RegSaveFrameIndex)
19775       .addImm(/*Scale=*/1)
19776       .addReg(/*IndexReg=*/0)
19777       .addImm(/*Disp=*/Offset)
19778       .addReg(/*Segment=*/0)
19779       .addReg(MI->getOperand(i).getReg())
19780       .addMemOperand(MMO);
19781   }
19782
19783   MI->eraseFromParent();   // The pseudo instruction is gone now.
19784
19785   return EndMBB;
19786 }
19787
19788 // The EFLAGS operand of SelectItr might be missing a kill marker
19789 // because there were multiple uses of EFLAGS, and ISel didn't know
19790 // which to mark. Figure out whether SelectItr should have had a
19791 // kill marker, and set it if it should. Returns the correct kill
19792 // marker value.
19793 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19794                                      MachineBasicBlock* BB,
19795                                      const TargetRegisterInfo* TRI) {
19796   // Scan forward through BB for a use/def of EFLAGS.
19797   MachineBasicBlock::iterator miI(std::next(SelectItr));
19798   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19799     const MachineInstr& mi = *miI;
19800     if (mi.readsRegister(X86::EFLAGS))
19801       return false;
19802     if (mi.definesRegister(X86::EFLAGS))
19803       break; // Should have kill-flag - update below.
19804   }
19805
19806   // If we hit the end of the block, check whether EFLAGS is live into a
19807   // successor.
19808   if (miI == BB->end()) {
19809     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19810                                           sEnd = BB->succ_end();
19811          sItr != sEnd; ++sItr) {
19812       MachineBasicBlock* succ = *sItr;
19813       if (succ->isLiveIn(X86::EFLAGS))
19814         return false;
19815     }
19816   }
19817
19818   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19819   // out. SelectMI should have a kill flag on EFLAGS.
19820   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19821   return true;
19822 }
19823
19824 MachineBasicBlock *
19825 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19826                                      MachineBasicBlock *BB) const {
19827   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19828   DebugLoc DL = MI->getDebugLoc();
19829
19830   // To "insert" a SELECT_CC instruction, we actually have to insert the
19831   // diamond control-flow pattern.  The incoming instruction knows the
19832   // destination vreg to set, the condition code register to branch on, the
19833   // true/false values to select between, and a branch opcode to use.
19834   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19835   MachineFunction::iterator It = BB;
19836   ++It;
19837
19838   //  thisMBB:
19839   //  ...
19840   //   TrueVal = ...
19841   //   cmpTY ccX, r1, r2
19842   //   bCC copy1MBB
19843   //   fallthrough --> copy0MBB
19844   MachineBasicBlock *thisMBB = BB;
19845   MachineFunction *F = BB->getParent();
19846
19847   // We also lower double CMOVs:
19848   //   (CMOV (CMOV F, T, cc1), T, cc2)
19849   // to two successives branches.  For that, we look for another CMOV as the
19850   // following instruction.
19851   //
19852   // Without this, we would add a PHI between the two jumps, which ends up
19853   // creating a few copies all around. For instance, for
19854   //
19855   //    (sitofp (zext (fcmp une)))
19856   //
19857   // we would generate:
19858   //
19859   //         ucomiss %xmm1, %xmm0
19860   //         movss  <1.0f>, %xmm0
19861   //         movaps  %xmm0, %xmm1
19862   //         jne     .LBB5_2
19863   //         xorps   %xmm1, %xmm1
19864   // .LBB5_2:
19865   //         jp      .LBB5_4
19866   //         movaps  %xmm1, %xmm0
19867   // .LBB5_4:
19868   //         retq
19869   //
19870   // because this custom-inserter would have generated:
19871   //
19872   //   A
19873   //   | \
19874   //   |  B
19875   //   | /
19876   //   C
19877   //   | \
19878   //   |  D
19879   //   | /
19880   //   E
19881   //
19882   // A: X = ...; Y = ...
19883   // B: empty
19884   // C: Z = PHI [X, A], [Y, B]
19885   // D: empty
19886   // E: PHI [X, C], [Z, D]
19887   //
19888   // If we lower both CMOVs in a single step, we can instead generate:
19889   //
19890   //   A
19891   //   | \
19892   //   |  C
19893   //   | /|
19894   //   |/ |
19895   //   |  |
19896   //   |  D
19897   //   | /
19898   //   E
19899   //
19900   // A: X = ...; Y = ...
19901   // D: empty
19902   // E: PHI [X, A], [X, C], [Y, D]
19903   //
19904   // Which, in our sitofp/fcmp example, gives us something like:
19905   //
19906   //         ucomiss %xmm1, %xmm0
19907   //         movss  <1.0f>, %xmm0
19908   //         jne     .LBB5_4
19909   //         jp      .LBB5_4
19910   //         xorps   %xmm0, %xmm0
19911   // .LBB5_4:
19912   //         retq
19913   //
19914   MachineInstr *NextCMOV = nullptr;
19915   MachineBasicBlock::iterator NextMIIt =
19916       std::next(MachineBasicBlock::iterator(MI));
19917   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19918       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19919       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19920     NextCMOV = &*NextMIIt;
19921
19922   MachineBasicBlock *jcc1MBB = nullptr;
19923
19924   // If we have a double CMOV, we lower it to two successive branches to
19925   // the same block.  EFLAGS is used by both, so mark it as live in the second.
19926   if (NextCMOV) {
19927     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19928     F->insert(It, jcc1MBB);
19929     jcc1MBB->addLiveIn(X86::EFLAGS);
19930   }
19931
19932   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19933   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19934   F->insert(It, copy0MBB);
19935   F->insert(It, sinkMBB);
19936
19937   // If the EFLAGS register isn't dead in the terminator, then claim that it's
19938   // live into the sink and copy blocks.
19939   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19940
19941   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19942   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19943       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19944     copy0MBB->addLiveIn(X86::EFLAGS);
19945     sinkMBB->addLiveIn(X86::EFLAGS);
19946   }
19947
19948   // Transfer the remainder of BB and its successor edges to sinkMBB.
19949   sinkMBB->splice(sinkMBB->begin(), BB,
19950                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
19951   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19952
19953   // Add the true and fallthrough blocks as its successors.
19954   if (NextCMOV) {
19955     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19956     BB->addSuccessor(jcc1MBB);
19957
19958     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19959     // jump to the sinkMBB.
19960     jcc1MBB->addSuccessor(copy0MBB);
19961     jcc1MBB->addSuccessor(sinkMBB);
19962   } else {
19963     BB->addSuccessor(copy0MBB);
19964   }
19965
19966   // The true block target of the first (or only) branch is always sinkMBB.
19967   BB->addSuccessor(sinkMBB);
19968
19969   // Create the conditional branch instruction.
19970   unsigned Opc =
19971     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19972   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19973
19974   if (NextCMOV) {
19975     unsigned Opc2 = X86::GetCondBranchFromCond(
19976         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19977     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19978   }
19979
19980   //  copy0MBB:
19981   //   %FalseValue = ...
19982   //   # fallthrough to sinkMBB
19983   copy0MBB->addSuccessor(sinkMBB);
19984
19985   //  sinkMBB:
19986   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19987   //  ...
19988   MachineInstrBuilder MIB =
19989       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19990               MI->getOperand(0).getReg())
19991           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19992           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19993
19994   // If we have a double CMOV, the second Jcc provides the same incoming
19995   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19996   if (NextCMOV) {
19997     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19998     // Copy the PHI result to the register defined by the second CMOV.
19999     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20000             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
20001         .addReg(MI->getOperand(0).getReg());
20002     NextCMOV->eraseFromParent();
20003   }
20004
20005   MI->eraseFromParent();   // The pseudo instruction is gone now.
20006   return sinkMBB;
20007 }
20008
20009 MachineBasicBlock *
20010 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20011                                         MachineBasicBlock *BB) const {
20012   MachineFunction *MF = BB->getParent();
20013   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20014   DebugLoc DL = MI->getDebugLoc();
20015   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20016
20017   assert(MF->shouldSplitStack());
20018
20019   const bool Is64Bit = Subtarget->is64Bit();
20020   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20021
20022   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20023   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20024
20025   // BB:
20026   //  ... [Till the alloca]
20027   // If stacklet is not large enough, jump to mallocMBB
20028   //
20029   // bumpMBB:
20030   //  Allocate by subtracting from RSP
20031   //  Jump to continueMBB
20032   //
20033   // mallocMBB:
20034   //  Allocate by call to runtime
20035   //
20036   // continueMBB:
20037   //  ...
20038   //  [rest of original BB]
20039   //
20040
20041   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20042   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20043   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20044
20045   MachineRegisterInfo &MRI = MF->getRegInfo();
20046   const TargetRegisterClass *AddrRegClass =
20047       getRegClassFor(getPointerTy(MF->getDataLayout()));
20048
20049   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20050     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20051     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20052     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20053     sizeVReg = MI->getOperand(1).getReg(),
20054     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20055
20056   MachineFunction::iterator MBBIter = BB;
20057   ++MBBIter;
20058
20059   MF->insert(MBBIter, bumpMBB);
20060   MF->insert(MBBIter, mallocMBB);
20061   MF->insert(MBBIter, continueMBB);
20062
20063   continueMBB->splice(continueMBB->begin(), BB,
20064                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20065   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20066
20067   // Add code to the main basic block to check if the stack limit has been hit,
20068   // and if so, jump to mallocMBB otherwise to bumpMBB.
20069   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20070   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20071     .addReg(tmpSPVReg).addReg(sizeVReg);
20072   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20073     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20074     .addReg(SPLimitVReg);
20075   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20076
20077   // bumpMBB simply decreases the stack pointer, since we know the current
20078   // stacklet has enough space.
20079   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20080     .addReg(SPLimitVReg);
20081   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20082     .addReg(SPLimitVReg);
20083   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20084
20085   // Calls into a routine in libgcc to allocate more space from the heap.
20086   const uint32_t *RegMask =
20087       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20088   if (IsLP64) {
20089     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20090       .addReg(sizeVReg);
20091     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20092       .addExternalSymbol("__morestack_allocate_stack_space")
20093       .addRegMask(RegMask)
20094       .addReg(X86::RDI, RegState::Implicit)
20095       .addReg(X86::RAX, RegState::ImplicitDefine);
20096   } else if (Is64Bit) {
20097     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20098       .addReg(sizeVReg);
20099     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20100       .addExternalSymbol("__morestack_allocate_stack_space")
20101       .addRegMask(RegMask)
20102       .addReg(X86::EDI, RegState::Implicit)
20103       .addReg(X86::EAX, RegState::ImplicitDefine);
20104   } else {
20105     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20106       .addImm(12);
20107     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20108     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20109       .addExternalSymbol("__morestack_allocate_stack_space")
20110       .addRegMask(RegMask)
20111       .addReg(X86::EAX, RegState::ImplicitDefine);
20112   }
20113
20114   if (!Is64Bit)
20115     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20116       .addImm(16);
20117
20118   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20119     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20120   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20121
20122   // Set up the CFG correctly.
20123   BB->addSuccessor(bumpMBB);
20124   BB->addSuccessor(mallocMBB);
20125   mallocMBB->addSuccessor(continueMBB);
20126   bumpMBB->addSuccessor(continueMBB);
20127
20128   // Take care of the PHI nodes.
20129   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20130           MI->getOperand(0).getReg())
20131     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20132     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20133
20134   // Delete the original pseudo instruction.
20135   MI->eraseFromParent();
20136
20137   // And we're done.
20138   return continueMBB;
20139 }
20140
20141 MachineBasicBlock *
20142 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20143                                         MachineBasicBlock *BB) const {
20144   DebugLoc DL = MI->getDebugLoc();
20145
20146   assert(!Subtarget->isTargetMachO());
20147
20148   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20149                                                     DL);
20150
20151   MI->eraseFromParent();   // The pseudo instruction is gone now.
20152   return BB;
20153 }
20154
20155 MachineBasicBlock *
20156 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20157                                       MachineBasicBlock *BB) const {
20158   // This is pretty easy.  We're taking the value that we received from
20159   // our load from the relocation, sticking it in either RDI (x86-64)
20160   // or EAX and doing an indirect call.  The return value will then
20161   // be in the normal return register.
20162   MachineFunction *F = BB->getParent();
20163   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20164   DebugLoc DL = MI->getDebugLoc();
20165
20166   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20167   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20168
20169   // Get a register mask for the lowered call.
20170   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20171   // proper register mask.
20172   const uint32_t *RegMask =
20173       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20174   if (Subtarget->is64Bit()) {
20175     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20176                                       TII->get(X86::MOV64rm), X86::RDI)
20177     .addReg(X86::RIP)
20178     .addImm(0).addReg(0)
20179     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20180                       MI->getOperand(3).getTargetFlags())
20181     .addReg(0);
20182     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20183     addDirectMem(MIB, X86::RDI);
20184     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20185   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20186     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20187                                       TII->get(X86::MOV32rm), X86::EAX)
20188     .addReg(0)
20189     .addImm(0).addReg(0)
20190     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20191                       MI->getOperand(3).getTargetFlags())
20192     .addReg(0);
20193     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20194     addDirectMem(MIB, X86::EAX);
20195     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20196   } else {
20197     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20198                                       TII->get(X86::MOV32rm), X86::EAX)
20199     .addReg(TII->getGlobalBaseReg(F))
20200     .addImm(0).addReg(0)
20201     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20202                       MI->getOperand(3).getTargetFlags())
20203     .addReg(0);
20204     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20205     addDirectMem(MIB, X86::EAX);
20206     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20207   }
20208
20209   MI->eraseFromParent(); // The pseudo instruction is gone now.
20210   return BB;
20211 }
20212
20213 MachineBasicBlock *
20214 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20215                                     MachineBasicBlock *MBB) const {
20216   DebugLoc DL = MI->getDebugLoc();
20217   MachineFunction *MF = MBB->getParent();
20218   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20219   MachineRegisterInfo &MRI = MF->getRegInfo();
20220
20221   const BasicBlock *BB = MBB->getBasicBlock();
20222   MachineFunction::iterator I = MBB;
20223   ++I;
20224
20225   // Memory Reference
20226   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20227   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20228
20229   unsigned DstReg;
20230   unsigned MemOpndSlot = 0;
20231
20232   unsigned CurOp = 0;
20233
20234   DstReg = MI->getOperand(CurOp++).getReg();
20235   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20236   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20237   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20238   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20239
20240   MemOpndSlot = CurOp;
20241
20242   MVT PVT = getPointerTy(MF->getDataLayout());
20243   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20244          "Invalid Pointer Size!");
20245
20246   // For v = setjmp(buf), we generate
20247   //
20248   // thisMBB:
20249   //  buf[LabelOffset] = restoreMBB
20250   //  SjLjSetup restoreMBB
20251   //
20252   // mainMBB:
20253   //  v_main = 0
20254   //
20255   // sinkMBB:
20256   //  v = phi(main, restore)
20257   //
20258   // restoreMBB:
20259   //  if base pointer being used, load it from frame
20260   //  v_restore = 1
20261
20262   MachineBasicBlock *thisMBB = MBB;
20263   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20264   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20265   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20266   MF->insert(I, mainMBB);
20267   MF->insert(I, sinkMBB);
20268   MF->push_back(restoreMBB);
20269
20270   MachineInstrBuilder MIB;
20271
20272   // Transfer the remainder of BB and its successor edges to sinkMBB.
20273   sinkMBB->splice(sinkMBB->begin(), MBB,
20274                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20275   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20276
20277   // thisMBB:
20278   unsigned PtrStoreOpc = 0;
20279   unsigned LabelReg = 0;
20280   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20281   Reloc::Model RM = MF->getTarget().getRelocationModel();
20282   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20283                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20284
20285   // Prepare IP either in reg or imm.
20286   if (!UseImmLabel) {
20287     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20288     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20289     LabelReg = MRI.createVirtualRegister(PtrRC);
20290     if (Subtarget->is64Bit()) {
20291       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20292               .addReg(X86::RIP)
20293               .addImm(0)
20294               .addReg(0)
20295               .addMBB(restoreMBB)
20296               .addReg(0);
20297     } else {
20298       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20299       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20300               .addReg(XII->getGlobalBaseReg(MF))
20301               .addImm(0)
20302               .addReg(0)
20303               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20304               .addReg(0);
20305     }
20306   } else
20307     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20308   // Store IP
20309   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20310   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20311     if (i == X86::AddrDisp)
20312       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20313     else
20314       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20315   }
20316   if (!UseImmLabel)
20317     MIB.addReg(LabelReg);
20318   else
20319     MIB.addMBB(restoreMBB);
20320   MIB.setMemRefs(MMOBegin, MMOEnd);
20321   // Setup
20322   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20323           .addMBB(restoreMBB);
20324
20325   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20326   MIB.addRegMask(RegInfo->getNoPreservedMask());
20327   thisMBB->addSuccessor(mainMBB);
20328   thisMBB->addSuccessor(restoreMBB);
20329
20330   // mainMBB:
20331   //  EAX = 0
20332   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20333   mainMBB->addSuccessor(sinkMBB);
20334
20335   // sinkMBB:
20336   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20337           TII->get(X86::PHI), DstReg)
20338     .addReg(mainDstReg).addMBB(mainMBB)
20339     .addReg(restoreDstReg).addMBB(restoreMBB);
20340
20341   // restoreMBB:
20342   if (RegInfo->hasBasePointer(*MF)) {
20343     const bool Uses64BitFramePtr =
20344         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20345     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20346     X86FI->setRestoreBasePointer(MF);
20347     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20348     unsigned BasePtr = RegInfo->getBaseRegister();
20349     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20350     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20351                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20352       .setMIFlag(MachineInstr::FrameSetup);
20353   }
20354   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20355   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20356   restoreMBB->addSuccessor(sinkMBB);
20357
20358   MI->eraseFromParent();
20359   return sinkMBB;
20360 }
20361
20362 MachineBasicBlock *
20363 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20364                                      MachineBasicBlock *MBB) const {
20365   DebugLoc DL = MI->getDebugLoc();
20366   MachineFunction *MF = MBB->getParent();
20367   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20368   MachineRegisterInfo &MRI = MF->getRegInfo();
20369
20370   // Memory Reference
20371   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20372   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20373
20374   MVT PVT = getPointerTy(MF->getDataLayout());
20375   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20376          "Invalid Pointer Size!");
20377
20378   const TargetRegisterClass *RC =
20379     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20380   unsigned Tmp = MRI.createVirtualRegister(RC);
20381   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20382   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20383   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20384   unsigned SP = RegInfo->getStackRegister();
20385
20386   MachineInstrBuilder MIB;
20387
20388   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20389   const int64_t SPOffset = 2 * PVT.getStoreSize();
20390
20391   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20392   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20393
20394   // Reload FP
20395   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20396   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20397     MIB.addOperand(MI->getOperand(i));
20398   MIB.setMemRefs(MMOBegin, MMOEnd);
20399   // Reload IP
20400   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20401   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20402     if (i == X86::AddrDisp)
20403       MIB.addDisp(MI->getOperand(i), LabelOffset);
20404     else
20405       MIB.addOperand(MI->getOperand(i));
20406   }
20407   MIB.setMemRefs(MMOBegin, MMOEnd);
20408   // Reload SP
20409   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20410   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20411     if (i == X86::AddrDisp)
20412       MIB.addDisp(MI->getOperand(i), SPOffset);
20413     else
20414       MIB.addOperand(MI->getOperand(i));
20415   }
20416   MIB.setMemRefs(MMOBegin, MMOEnd);
20417   // Jump
20418   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20419
20420   MI->eraseFromParent();
20421   return MBB;
20422 }
20423
20424 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20425 // accumulator loops. Writing back to the accumulator allows the coalescer
20426 // to remove extra copies in the loop.
20427 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20428 MachineBasicBlock *
20429 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20430                                  MachineBasicBlock *MBB) const {
20431   MachineOperand &AddendOp = MI->getOperand(3);
20432
20433   // Bail out early if the addend isn't a register - we can't switch these.
20434   if (!AddendOp.isReg())
20435     return MBB;
20436
20437   MachineFunction &MF = *MBB->getParent();
20438   MachineRegisterInfo &MRI = MF.getRegInfo();
20439
20440   // Check whether the addend is defined by a PHI:
20441   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20442   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20443   if (!AddendDef.isPHI())
20444     return MBB;
20445
20446   // Look for the following pattern:
20447   // loop:
20448   //   %addend = phi [%entry, 0], [%loop, %result]
20449   //   ...
20450   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20451
20452   // Replace with:
20453   //   loop:
20454   //   %addend = phi [%entry, 0], [%loop, %result]
20455   //   ...
20456   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20457
20458   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20459     assert(AddendDef.getOperand(i).isReg());
20460     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20461     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20462     if (&PHISrcInst == MI) {
20463       // Found a matching instruction.
20464       unsigned NewFMAOpc = 0;
20465       switch (MI->getOpcode()) {
20466         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20467         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20468         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20469         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20470         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20471         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20472         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20473         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20474         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20475         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20476         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20477         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20478         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20479         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20480         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20481         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20482         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20483         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20484         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20485         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20486
20487         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20488         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20489         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20490         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20491         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20492         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20493         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20494         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20495         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20496         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20497         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20498         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20499         default: llvm_unreachable("Unrecognized FMA variant.");
20500       }
20501
20502       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20503       MachineInstrBuilder MIB =
20504         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20505         .addOperand(MI->getOperand(0))
20506         .addOperand(MI->getOperand(3))
20507         .addOperand(MI->getOperand(2))
20508         .addOperand(MI->getOperand(1));
20509       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20510       MI->eraseFromParent();
20511     }
20512   }
20513
20514   return MBB;
20515 }
20516
20517 MachineBasicBlock *
20518 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20519                                                MachineBasicBlock *BB) const {
20520   switch (MI->getOpcode()) {
20521   default: llvm_unreachable("Unexpected instr type to insert");
20522   case X86::TAILJMPd64:
20523   case X86::TAILJMPr64:
20524   case X86::TAILJMPm64:
20525   case X86::TAILJMPd64_REX:
20526   case X86::TAILJMPr64_REX:
20527   case X86::TAILJMPm64_REX:
20528     llvm_unreachable("TAILJMP64 would not be touched here.");
20529   case X86::TCRETURNdi64:
20530   case X86::TCRETURNri64:
20531   case X86::TCRETURNmi64:
20532     return BB;
20533   case X86::WIN_ALLOCA:
20534     return EmitLoweredWinAlloca(MI, BB);
20535   case X86::SEG_ALLOCA_32:
20536   case X86::SEG_ALLOCA_64:
20537     return EmitLoweredSegAlloca(MI, BB);
20538   case X86::TLSCall_32:
20539   case X86::TLSCall_64:
20540     return EmitLoweredTLSCall(MI, BB);
20541   case X86::CMOV_GR8:
20542   case X86::CMOV_FR32:
20543   case X86::CMOV_FR64:
20544   case X86::CMOV_V4F32:
20545   case X86::CMOV_V2F64:
20546   case X86::CMOV_V2I64:
20547   case X86::CMOV_V8F32:
20548   case X86::CMOV_V4F64:
20549   case X86::CMOV_V4I64:
20550   case X86::CMOV_V16F32:
20551   case X86::CMOV_V8F64:
20552   case X86::CMOV_V8I64:
20553   case X86::CMOV_GR16:
20554   case X86::CMOV_GR32:
20555   case X86::CMOV_RFP32:
20556   case X86::CMOV_RFP64:
20557   case X86::CMOV_RFP80:
20558   case X86::CMOV_V8I1:
20559   case X86::CMOV_V16I1:
20560   case X86::CMOV_V32I1:
20561   case X86::CMOV_V64I1:
20562     return EmitLoweredSelect(MI, BB);
20563
20564   case X86::FP32_TO_INT16_IN_MEM:
20565   case X86::FP32_TO_INT32_IN_MEM:
20566   case X86::FP32_TO_INT64_IN_MEM:
20567   case X86::FP64_TO_INT16_IN_MEM:
20568   case X86::FP64_TO_INT32_IN_MEM:
20569   case X86::FP64_TO_INT64_IN_MEM:
20570   case X86::FP80_TO_INT16_IN_MEM:
20571   case X86::FP80_TO_INT32_IN_MEM:
20572   case X86::FP80_TO_INT64_IN_MEM: {
20573     MachineFunction *F = BB->getParent();
20574     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20575     DebugLoc DL = MI->getDebugLoc();
20576
20577     // Change the floating point control register to use "round towards zero"
20578     // mode when truncating to an integer value.
20579     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20580     addFrameReference(BuildMI(*BB, MI, DL,
20581                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20582
20583     // Load the old value of the high byte of the control word...
20584     unsigned OldCW =
20585       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20586     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20587                       CWFrameIdx);
20588
20589     // Set the high part to be round to zero...
20590     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20591       .addImm(0xC7F);
20592
20593     // Reload the modified control word now...
20594     addFrameReference(BuildMI(*BB, MI, DL,
20595                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20596
20597     // Restore the memory image of control word to original value
20598     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20599       .addReg(OldCW);
20600
20601     // Get the X86 opcode to use.
20602     unsigned Opc;
20603     switch (MI->getOpcode()) {
20604     default: llvm_unreachable("illegal opcode!");
20605     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20606     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20607     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20608     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20609     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20610     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20611     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20612     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20613     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20614     }
20615
20616     X86AddressMode AM;
20617     MachineOperand &Op = MI->getOperand(0);
20618     if (Op.isReg()) {
20619       AM.BaseType = X86AddressMode::RegBase;
20620       AM.Base.Reg = Op.getReg();
20621     } else {
20622       AM.BaseType = X86AddressMode::FrameIndexBase;
20623       AM.Base.FrameIndex = Op.getIndex();
20624     }
20625     Op = MI->getOperand(1);
20626     if (Op.isImm())
20627       AM.Scale = Op.getImm();
20628     Op = MI->getOperand(2);
20629     if (Op.isImm())
20630       AM.IndexReg = Op.getImm();
20631     Op = MI->getOperand(3);
20632     if (Op.isGlobal()) {
20633       AM.GV = Op.getGlobal();
20634     } else {
20635       AM.Disp = Op.getImm();
20636     }
20637     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20638                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20639
20640     // Reload the original control word now.
20641     addFrameReference(BuildMI(*BB, MI, DL,
20642                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20643
20644     MI->eraseFromParent();   // The pseudo instruction is gone now.
20645     return BB;
20646   }
20647     // String/text processing lowering.
20648   case X86::PCMPISTRM128REG:
20649   case X86::VPCMPISTRM128REG:
20650   case X86::PCMPISTRM128MEM:
20651   case X86::VPCMPISTRM128MEM:
20652   case X86::PCMPESTRM128REG:
20653   case X86::VPCMPESTRM128REG:
20654   case X86::PCMPESTRM128MEM:
20655   case X86::VPCMPESTRM128MEM:
20656     assert(Subtarget->hasSSE42() &&
20657            "Target must have SSE4.2 or AVX features enabled");
20658     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20659
20660   // String/text processing lowering.
20661   case X86::PCMPISTRIREG:
20662   case X86::VPCMPISTRIREG:
20663   case X86::PCMPISTRIMEM:
20664   case X86::VPCMPISTRIMEM:
20665   case X86::PCMPESTRIREG:
20666   case X86::VPCMPESTRIREG:
20667   case X86::PCMPESTRIMEM:
20668   case X86::VPCMPESTRIMEM:
20669     assert(Subtarget->hasSSE42() &&
20670            "Target must have SSE4.2 or AVX features enabled");
20671     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20672
20673   // Thread synchronization.
20674   case X86::MONITOR:
20675     return EmitMonitor(MI, BB, Subtarget);
20676
20677   // xbegin
20678   case X86::XBEGIN:
20679     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20680
20681   case X86::VASTART_SAVE_XMM_REGS:
20682     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20683
20684   case X86::VAARG_64:
20685     return EmitVAARG64WithCustomInserter(MI, BB);
20686
20687   case X86::EH_SjLj_SetJmp32:
20688   case X86::EH_SjLj_SetJmp64:
20689     return emitEHSjLjSetJmp(MI, BB);
20690
20691   case X86::EH_SjLj_LongJmp32:
20692   case X86::EH_SjLj_LongJmp64:
20693     return emitEHSjLjLongJmp(MI, BB);
20694
20695   case TargetOpcode::STATEPOINT:
20696     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20697     // this point in the process.  We diverge later.
20698     return emitPatchPoint(MI, BB);
20699
20700   case TargetOpcode::STACKMAP:
20701   case TargetOpcode::PATCHPOINT:
20702     return emitPatchPoint(MI, BB);
20703
20704   case X86::VFMADDPDr213r:
20705   case X86::VFMADDPSr213r:
20706   case X86::VFMADDSDr213r:
20707   case X86::VFMADDSSr213r:
20708   case X86::VFMSUBPDr213r:
20709   case X86::VFMSUBPSr213r:
20710   case X86::VFMSUBSDr213r:
20711   case X86::VFMSUBSSr213r:
20712   case X86::VFNMADDPDr213r:
20713   case X86::VFNMADDPSr213r:
20714   case X86::VFNMADDSDr213r:
20715   case X86::VFNMADDSSr213r:
20716   case X86::VFNMSUBPDr213r:
20717   case X86::VFNMSUBPSr213r:
20718   case X86::VFNMSUBSDr213r:
20719   case X86::VFNMSUBSSr213r:
20720   case X86::VFMADDSUBPDr213r:
20721   case X86::VFMADDSUBPSr213r:
20722   case X86::VFMSUBADDPDr213r:
20723   case X86::VFMSUBADDPSr213r:
20724   case X86::VFMADDPDr213rY:
20725   case X86::VFMADDPSr213rY:
20726   case X86::VFMSUBPDr213rY:
20727   case X86::VFMSUBPSr213rY:
20728   case X86::VFNMADDPDr213rY:
20729   case X86::VFNMADDPSr213rY:
20730   case X86::VFNMSUBPDr213rY:
20731   case X86::VFNMSUBPSr213rY:
20732   case X86::VFMADDSUBPDr213rY:
20733   case X86::VFMADDSUBPSr213rY:
20734   case X86::VFMSUBADDPDr213rY:
20735   case X86::VFMSUBADDPSr213rY:
20736     return emitFMA3Instr(MI, BB);
20737   }
20738 }
20739
20740 //===----------------------------------------------------------------------===//
20741 //                           X86 Optimization Hooks
20742 //===----------------------------------------------------------------------===//
20743
20744 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20745                                                       APInt &KnownZero,
20746                                                       APInt &KnownOne,
20747                                                       const SelectionDAG &DAG,
20748                                                       unsigned Depth) const {
20749   unsigned BitWidth = KnownZero.getBitWidth();
20750   unsigned Opc = Op.getOpcode();
20751   assert((Opc >= ISD::BUILTIN_OP_END ||
20752           Opc == ISD::INTRINSIC_WO_CHAIN ||
20753           Opc == ISD::INTRINSIC_W_CHAIN ||
20754           Opc == ISD::INTRINSIC_VOID) &&
20755          "Should use MaskedValueIsZero if you don't know whether Op"
20756          " is a target node!");
20757
20758   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20759   switch (Opc) {
20760   default: break;
20761   case X86ISD::ADD:
20762   case X86ISD::SUB:
20763   case X86ISD::ADC:
20764   case X86ISD::SBB:
20765   case X86ISD::SMUL:
20766   case X86ISD::UMUL:
20767   case X86ISD::INC:
20768   case X86ISD::DEC:
20769   case X86ISD::OR:
20770   case X86ISD::XOR:
20771   case X86ISD::AND:
20772     // These nodes' second result is a boolean.
20773     if (Op.getResNo() == 0)
20774       break;
20775     // Fallthrough
20776   case X86ISD::SETCC:
20777     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20778     break;
20779   case ISD::INTRINSIC_WO_CHAIN: {
20780     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20781     unsigned NumLoBits = 0;
20782     switch (IntId) {
20783     default: break;
20784     case Intrinsic::x86_sse_movmsk_ps:
20785     case Intrinsic::x86_avx_movmsk_ps_256:
20786     case Intrinsic::x86_sse2_movmsk_pd:
20787     case Intrinsic::x86_avx_movmsk_pd_256:
20788     case Intrinsic::x86_mmx_pmovmskb:
20789     case Intrinsic::x86_sse2_pmovmskb_128:
20790     case Intrinsic::x86_avx2_pmovmskb: {
20791       // High bits of movmskp{s|d}, pmovmskb are known zero.
20792       switch (IntId) {
20793         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20794         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20795         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20796         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20797         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20798         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20799         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20800         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20801       }
20802       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20803       break;
20804     }
20805     }
20806     break;
20807   }
20808   }
20809 }
20810
20811 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20812   SDValue Op,
20813   const SelectionDAG &,
20814   unsigned Depth) const {
20815   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20816   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20817     return Op.getValueType().getScalarType().getSizeInBits();
20818
20819   // Fallback case.
20820   return 1;
20821 }
20822
20823 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20824 /// node is a GlobalAddress + offset.
20825 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20826                                        const GlobalValue* &GA,
20827                                        int64_t &Offset) const {
20828   if (N->getOpcode() == X86ISD::Wrapper) {
20829     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20830       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20831       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20832       return true;
20833     }
20834   }
20835   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20836 }
20837
20838 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20839 /// same as extracting the high 128-bit part of 256-bit vector and then
20840 /// inserting the result into the low part of a new 256-bit vector
20841 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20842   EVT VT = SVOp->getValueType(0);
20843   unsigned NumElems = VT.getVectorNumElements();
20844
20845   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20846   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20847     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20848         SVOp->getMaskElt(j) >= 0)
20849       return false;
20850
20851   return true;
20852 }
20853
20854 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20855 /// same as extracting the low 128-bit part of 256-bit vector and then
20856 /// inserting the result into the high part of a new 256-bit vector
20857 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20858   EVT VT = SVOp->getValueType(0);
20859   unsigned NumElems = VT.getVectorNumElements();
20860
20861   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20862   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20863     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20864         SVOp->getMaskElt(j) >= 0)
20865       return false;
20866
20867   return true;
20868 }
20869
20870 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20871 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20872                                         TargetLowering::DAGCombinerInfo &DCI,
20873                                         const X86Subtarget* Subtarget) {
20874   SDLoc dl(N);
20875   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20876   SDValue V1 = SVOp->getOperand(0);
20877   SDValue V2 = SVOp->getOperand(1);
20878   EVT VT = SVOp->getValueType(0);
20879   unsigned NumElems = VT.getVectorNumElements();
20880
20881   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20882       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20883     //
20884     //                   0,0,0,...
20885     //                      |
20886     //    V      UNDEF    BUILD_VECTOR    UNDEF
20887     //     \      /           \           /
20888     //  CONCAT_VECTOR         CONCAT_VECTOR
20889     //         \                  /
20890     //          \                /
20891     //          RESULT: V + zero extended
20892     //
20893     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20894         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20895         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20896       return SDValue();
20897
20898     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20899       return SDValue();
20900
20901     // To match the shuffle mask, the first half of the mask should
20902     // be exactly the first vector, and all the rest a splat with the
20903     // first element of the second one.
20904     for (unsigned i = 0; i != NumElems/2; ++i)
20905       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20906           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20907         return SDValue();
20908
20909     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20910     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20911       if (Ld->hasNUsesOfValue(1, 0)) {
20912         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20913         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20914         SDValue ResNode =
20915           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20916                                   Ld->getMemoryVT(),
20917                                   Ld->getPointerInfo(),
20918                                   Ld->getAlignment(),
20919                                   false/*isVolatile*/, true/*ReadMem*/,
20920                                   false/*WriteMem*/);
20921
20922         // Make sure the newly-created LOAD is in the same position as Ld in
20923         // terms of dependency. We create a TokenFactor for Ld and ResNode,
20924         // and update uses of Ld's output chain to use the TokenFactor.
20925         if (Ld->hasAnyUseOfValue(1)) {
20926           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20927                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20928           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20929           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20930                                  SDValue(ResNode.getNode(), 1));
20931         }
20932
20933         return DAG.getBitcast(VT, ResNode);
20934       }
20935     }
20936
20937     // Emit a zeroed vector and insert the desired subvector on its
20938     // first half.
20939     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20940     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20941     return DCI.CombineTo(N, InsV);
20942   }
20943
20944   //===--------------------------------------------------------------------===//
20945   // Combine some shuffles into subvector extracts and inserts:
20946   //
20947
20948   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20949   if (isShuffleHigh128VectorInsertLow(SVOp)) {
20950     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20951     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20952     return DCI.CombineTo(N, InsV);
20953   }
20954
20955   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20956   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20957     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20958     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20959     return DCI.CombineTo(N, InsV);
20960   }
20961
20962   return SDValue();
20963 }
20964
20965 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20966 /// possible.
20967 ///
20968 /// This is the leaf of the recursive combinine below. When we have found some
20969 /// chain of single-use x86 shuffle instructions and accumulated the combined
20970 /// shuffle mask represented by them, this will try to pattern match that mask
20971 /// into either a single instruction if there is a special purpose instruction
20972 /// for this operation, or into a PSHUFB instruction which is a fully general
20973 /// instruction but should only be used to replace chains over a certain depth.
20974 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20975                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20976                                    TargetLowering::DAGCombinerInfo &DCI,
20977                                    const X86Subtarget *Subtarget) {
20978   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20979
20980   // Find the operand that enters the chain. Note that multiple uses are OK
20981   // here, we're not going to remove the operand we find.
20982   SDValue Input = Op.getOperand(0);
20983   while (Input.getOpcode() == ISD::BITCAST)
20984     Input = Input.getOperand(0);
20985
20986   MVT VT = Input.getSimpleValueType();
20987   MVT RootVT = Root.getSimpleValueType();
20988   SDLoc DL(Root);
20989
20990   // Just remove no-op shuffle masks.
20991   if (Mask.size() == 1) {
20992     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
20993                   /*AddTo*/ true);
20994     return true;
20995   }
20996
20997   // Use the float domain if the operand type is a floating point type.
20998   bool FloatDomain = VT.isFloatingPoint();
20999
21000   // For floating point shuffles, we don't have free copies in the shuffle
21001   // instructions or the ability to load as part of the instruction, so
21002   // canonicalize their shuffles to UNPCK or MOV variants.
21003   //
21004   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21005   // vectors because it can have a load folded into it that UNPCK cannot. This
21006   // doesn't preclude something switching to the shorter encoding post-RA.
21007   //
21008   // FIXME: Should teach these routines about AVX vector widths.
21009   if (FloatDomain && VT.getSizeInBits() == 128) {
21010     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21011       bool Lo = Mask.equals({0, 0});
21012       unsigned Shuffle;
21013       MVT ShuffleVT;
21014       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21015       // is no slower than UNPCKLPD but has the option to fold the input operand
21016       // into even an unaligned memory load.
21017       if (Lo && Subtarget->hasSSE3()) {
21018         Shuffle = X86ISD::MOVDDUP;
21019         ShuffleVT = MVT::v2f64;
21020       } else {
21021         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21022         // than the UNPCK variants.
21023         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21024         ShuffleVT = MVT::v4f32;
21025       }
21026       if (Depth == 1 && Root->getOpcode() == Shuffle)
21027         return false; // Nothing to do!
21028       Op = DAG.getBitcast(ShuffleVT, Input);
21029       DCI.AddToWorklist(Op.getNode());
21030       if (Shuffle == X86ISD::MOVDDUP)
21031         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21032       else
21033         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21034       DCI.AddToWorklist(Op.getNode());
21035       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21036                     /*AddTo*/ true);
21037       return true;
21038     }
21039     if (Subtarget->hasSSE3() &&
21040         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21041       bool Lo = Mask.equals({0, 0, 2, 2});
21042       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21043       MVT ShuffleVT = MVT::v4f32;
21044       if (Depth == 1 && Root->getOpcode() == Shuffle)
21045         return false; // Nothing to do!
21046       Op = DAG.getBitcast(ShuffleVT, Input);
21047       DCI.AddToWorklist(Op.getNode());
21048       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21049       DCI.AddToWorklist(Op.getNode());
21050       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21051                     /*AddTo*/ true);
21052       return true;
21053     }
21054     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21055       bool Lo = Mask.equals({0, 0, 1, 1});
21056       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21057       MVT ShuffleVT = MVT::v4f32;
21058       if (Depth == 1 && Root->getOpcode() == Shuffle)
21059         return false; // Nothing to do!
21060       Op = DAG.getBitcast(ShuffleVT, Input);
21061       DCI.AddToWorklist(Op.getNode());
21062       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21063       DCI.AddToWorklist(Op.getNode());
21064       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21065                     /*AddTo*/ true);
21066       return true;
21067     }
21068   }
21069
21070   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21071   // variants as none of these have single-instruction variants that are
21072   // superior to the UNPCK formulation.
21073   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21074       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21075        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21076        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21077        Mask.equals(
21078            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21079     bool Lo = Mask[0] == 0;
21080     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21081     if (Depth == 1 && Root->getOpcode() == Shuffle)
21082       return false; // Nothing to do!
21083     MVT ShuffleVT;
21084     switch (Mask.size()) {
21085     case 8:
21086       ShuffleVT = MVT::v8i16;
21087       break;
21088     case 16:
21089       ShuffleVT = MVT::v16i8;
21090       break;
21091     default:
21092       llvm_unreachable("Impossible mask size!");
21093     };
21094     Op = DAG.getBitcast(ShuffleVT, Input);
21095     DCI.AddToWorklist(Op.getNode());
21096     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21097     DCI.AddToWorklist(Op.getNode());
21098     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21099                   /*AddTo*/ true);
21100     return true;
21101   }
21102
21103   // Don't try to re-form single instruction chains under any circumstances now
21104   // that we've done encoding canonicalization for them.
21105   if (Depth < 2)
21106     return false;
21107
21108   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21109   // can replace them with a single PSHUFB instruction profitably. Intel's
21110   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21111   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21112   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21113     SmallVector<SDValue, 16> PSHUFBMask;
21114     int NumBytes = VT.getSizeInBits() / 8;
21115     int Ratio = NumBytes / Mask.size();
21116     for (int i = 0; i < NumBytes; ++i) {
21117       if (Mask[i / Ratio] == SM_SentinelUndef) {
21118         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21119         continue;
21120       }
21121       int M = Mask[i / Ratio] != SM_SentinelZero
21122                   ? Ratio * Mask[i / Ratio] + i % Ratio
21123                   : 255;
21124       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21125     }
21126     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21127     Op = DAG.getBitcast(ByteVT, Input);
21128     DCI.AddToWorklist(Op.getNode());
21129     SDValue PSHUFBMaskOp =
21130         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21131     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21132     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21133     DCI.AddToWorklist(Op.getNode());
21134     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21135                   /*AddTo*/ true);
21136     return true;
21137   }
21138
21139   // Failed to find any combines.
21140   return false;
21141 }
21142
21143 /// \brief Fully generic combining of x86 shuffle instructions.
21144 ///
21145 /// This should be the last combine run over the x86 shuffle instructions. Once
21146 /// they have been fully optimized, this will recursively consider all chains
21147 /// of single-use shuffle instructions, build a generic model of the cumulative
21148 /// shuffle operation, and check for simpler instructions which implement this
21149 /// operation. We use this primarily for two purposes:
21150 ///
21151 /// 1) Collapse generic shuffles to specialized single instructions when
21152 ///    equivalent. In most cases, this is just an encoding size win, but
21153 ///    sometimes we will collapse multiple generic shuffles into a single
21154 ///    special-purpose shuffle.
21155 /// 2) Look for sequences of shuffle instructions with 3 or more total
21156 ///    instructions, and replace them with the slightly more expensive SSSE3
21157 ///    PSHUFB instruction if available. We do this as the last combining step
21158 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21159 ///    a suitable short sequence of other instructions. The PHUFB will either
21160 ///    use a register or have to read from memory and so is slightly (but only
21161 ///    slightly) more expensive than the other shuffle instructions.
21162 ///
21163 /// Because this is inherently a quadratic operation (for each shuffle in
21164 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21165 /// This should never be an issue in practice as the shuffle lowering doesn't
21166 /// produce sequences of more than 8 instructions.
21167 ///
21168 /// FIXME: We will currently miss some cases where the redundant shuffling
21169 /// would simplify under the threshold for PSHUFB formation because of
21170 /// combine-ordering. To fix this, we should do the redundant instruction
21171 /// combining in this recursive walk.
21172 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21173                                           ArrayRef<int> RootMask,
21174                                           int Depth, bool HasPSHUFB,
21175                                           SelectionDAG &DAG,
21176                                           TargetLowering::DAGCombinerInfo &DCI,
21177                                           const X86Subtarget *Subtarget) {
21178   // Bound the depth of our recursive combine because this is ultimately
21179   // quadratic in nature.
21180   if (Depth > 8)
21181     return false;
21182
21183   // Directly rip through bitcasts to find the underlying operand.
21184   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21185     Op = Op.getOperand(0);
21186
21187   MVT VT = Op.getSimpleValueType();
21188   if (!VT.isVector())
21189     return false; // Bail if we hit a non-vector.
21190
21191   assert(Root.getSimpleValueType().isVector() &&
21192          "Shuffles operate on vector types!");
21193   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21194          "Can only combine shuffles of the same vector register size.");
21195
21196   if (!isTargetShuffle(Op.getOpcode()))
21197     return false;
21198   SmallVector<int, 16> OpMask;
21199   bool IsUnary;
21200   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21201   // We only can combine unary shuffles which we can decode the mask for.
21202   if (!HaveMask || !IsUnary)
21203     return false;
21204
21205   assert(VT.getVectorNumElements() == OpMask.size() &&
21206          "Different mask size from vector size!");
21207   assert(((RootMask.size() > OpMask.size() &&
21208            RootMask.size() % OpMask.size() == 0) ||
21209           (OpMask.size() > RootMask.size() &&
21210            OpMask.size() % RootMask.size() == 0) ||
21211           OpMask.size() == RootMask.size()) &&
21212          "The smaller number of elements must divide the larger.");
21213   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21214   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21215   assert(((RootRatio == 1 && OpRatio == 1) ||
21216           (RootRatio == 1) != (OpRatio == 1)) &&
21217          "Must not have a ratio for both incoming and op masks!");
21218
21219   SmallVector<int, 16> Mask;
21220   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21221
21222   // Merge this shuffle operation's mask into our accumulated mask. Note that
21223   // this shuffle's mask will be the first applied to the input, followed by the
21224   // root mask to get us all the way to the root value arrangement. The reason
21225   // for this order is that we are recursing up the operation chain.
21226   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21227     int RootIdx = i / RootRatio;
21228     if (RootMask[RootIdx] < 0) {
21229       // This is a zero or undef lane, we're done.
21230       Mask.push_back(RootMask[RootIdx]);
21231       continue;
21232     }
21233
21234     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21235     int OpIdx = RootMaskedIdx / OpRatio;
21236     if (OpMask[OpIdx] < 0) {
21237       // The incoming lanes are zero or undef, it doesn't matter which ones we
21238       // are using.
21239       Mask.push_back(OpMask[OpIdx]);
21240       continue;
21241     }
21242
21243     // Ok, we have non-zero lanes, map them through.
21244     Mask.push_back(OpMask[OpIdx] * OpRatio +
21245                    RootMaskedIdx % OpRatio);
21246   }
21247
21248   // See if we can recurse into the operand to combine more things.
21249   switch (Op.getOpcode()) {
21250     case X86ISD::PSHUFB:
21251       HasPSHUFB = true;
21252     case X86ISD::PSHUFD:
21253     case X86ISD::PSHUFHW:
21254     case X86ISD::PSHUFLW:
21255       if (Op.getOperand(0).hasOneUse() &&
21256           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21257                                         HasPSHUFB, DAG, DCI, Subtarget))
21258         return true;
21259       break;
21260
21261     case X86ISD::UNPCKL:
21262     case X86ISD::UNPCKH:
21263       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21264       // We can't check for single use, we have to check that this shuffle is the only user.
21265       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21266           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21267                                         HasPSHUFB, DAG, DCI, Subtarget))
21268           return true;
21269       break;
21270   }
21271
21272   // Minor canonicalization of the accumulated shuffle mask to make it easier
21273   // to match below. All this does is detect masks with squential pairs of
21274   // elements, and shrink them to the half-width mask. It does this in a loop
21275   // so it will reduce the size of the mask to the minimal width mask which
21276   // performs an equivalent shuffle.
21277   SmallVector<int, 16> WidenedMask;
21278   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21279     Mask = std::move(WidenedMask);
21280     WidenedMask.clear();
21281   }
21282
21283   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21284                                 Subtarget);
21285 }
21286
21287 /// \brief Get the PSHUF-style mask from PSHUF node.
21288 ///
21289 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21290 /// PSHUF-style masks that can be reused with such instructions.
21291 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21292   MVT VT = N.getSimpleValueType();
21293   SmallVector<int, 4> Mask;
21294   bool IsUnary;
21295   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21296   (void)HaveMask;
21297   assert(HaveMask);
21298
21299   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21300   // matter. Check that the upper masks are repeats and remove them.
21301   if (VT.getSizeInBits() > 128) {
21302     int LaneElts = 128 / VT.getScalarSizeInBits();
21303 #ifndef NDEBUG
21304     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21305       for (int j = 0; j < LaneElts; ++j)
21306         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21307                "Mask doesn't repeat in high 128-bit lanes!");
21308 #endif
21309     Mask.resize(LaneElts);
21310   }
21311
21312   switch (N.getOpcode()) {
21313   case X86ISD::PSHUFD:
21314     return Mask;
21315   case X86ISD::PSHUFLW:
21316     Mask.resize(4);
21317     return Mask;
21318   case X86ISD::PSHUFHW:
21319     Mask.erase(Mask.begin(), Mask.begin() + 4);
21320     for (int &M : Mask)
21321       M -= 4;
21322     return Mask;
21323   default:
21324     llvm_unreachable("No valid shuffle instruction found!");
21325   }
21326 }
21327
21328 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21329 ///
21330 /// We walk up the chain and look for a combinable shuffle, skipping over
21331 /// shuffles that we could hoist this shuffle's transformation past without
21332 /// altering anything.
21333 static SDValue
21334 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21335                              SelectionDAG &DAG,
21336                              TargetLowering::DAGCombinerInfo &DCI) {
21337   assert(N.getOpcode() == X86ISD::PSHUFD &&
21338          "Called with something other than an x86 128-bit half shuffle!");
21339   SDLoc DL(N);
21340
21341   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21342   // of the shuffles in the chain so that we can form a fresh chain to replace
21343   // this one.
21344   SmallVector<SDValue, 8> Chain;
21345   SDValue V = N.getOperand(0);
21346   for (; V.hasOneUse(); V = V.getOperand(0)) {
21347     switch (V.getOpcode()) {
21348     default:
21349       return SDValue(); // Nothing combined!
21350
21351     case ISD::BITCAST:
21352       // Skip bitcasts as we always know the type for the target specific
21353       // instructions.
21354       continue;
21355
21356     case X86ISD::PSHUFD:
21357       // Found another dword shuffle.
21358       break;
21359
21360     case X86ISD::PSHUFLW:
21361       // Check that the low words (being shuffled) are the identity in the
21362       // dword shuffle, and the high words are self-contained.
21363       if (Mask[0] != 0 || Mask[1] != 1 ||
21364           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21365         return SDValue();
21366
21367       Chain.push_back(V);
21368       continue;
21369
21370     case X86ISD::PSHUFHW:
21371       // Check that the high words (being shuffled) are the identity in the
21372       // dword shuffle, and the low words are self-contained.
21373       if (Mask[2] != 2 || Mask[3] != 3 ||
21374           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21375         return SDValue();
21376
21377       Chain.push_back(V);
21378       continue;
21379
21380     case X86ISD::UNPCKL:
21381     case X86ISD::UNPCKH:
21382       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21383       // shuffle into a preceding word shuffle.
21384       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21385           V.getSimpleValueType().getScalarType() != MVT::i16)
21386         return SDValue();
21387
21388       // Search for a half-shuffle which we can combine with.
21389       unsigned CombineOp =
21390           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21391       if (V.getOperand(0) != V.getOperand(1) ||
21392           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21393         return SDValue();
21394       Chain.push_back(V);
21395       V = V.getOperand(0);
21396       do {
21397         switch (V.getOpcode()) {
21398         default:
21399           return SDValue(); // Nothing to combine.
21400
21401         case X86ISD::PSHUFLW:
21402         case X86ISD::PSHUFHW:
21403           if (V.getOpcode() == CombineOp)
21404             break;
21405
21406           Chain.push_back(V);
21407
21408           // Fallthrough!
21409         case ISD::BITCAST:
21410           V = V.getOperand(0);
21411           continue;
21412         }
21413         break;
21414       } while (V.hasOneUse());
21415       break;
21416     }
21417     // Break out of the loop if we break out of the switch.
21418     break;
21419   }
21420
21421   if (!V.hasOneUse())
21422     // We fell out of the loop without finding a viable combining instruction.
21423     return SDValue();
21424
21425   // Merge this node's mask and our incoming mask.
21426   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21427   for (int &M : Mask)
21428     M = VMask[M];
21429   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21430                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21431
21432   // Rebuild the chain around this new shuffle.
21433   while (!Chain.empty()) {
21434     SDValue W = Chain.pop_back_val();
21435
21436     if (V.getValueType() != W.getOperand(0).getValueType())
21437       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21438
21439     switch (W.getOpcode()) {
21440     default:
21441       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21442
21443     case X86ISD::UNPCKL:
21444     case X86ISD::UNPCKH:
21445       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21446       break;
21447
21448     case X86ISD::PSHUFD:
21449     case X86ISD::PSHUFLW:
21450     case X86ISD::PSHUFHW:
21451       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21452       break;
21453     }
21454   }
21455   if (V.getValueType() != N.getValueType())
21456     V = DAG.getBitcast(N.getValueType(), V);
21457
21458   // Return the new chain to replace N.
21459   return V;
21460 }
21461
21462 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21463 ///
21464 /// We walk up the chain, skipping shuffles of the other half and looking
21465 /// through shuffles which switch halves trying to find a shuffle of the same
21466 /// pair of dwords.
21467 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21468                                         SelectionDAG &DAG,
21469                                         TargetLowering::DAGCombinerInfo &DCI) {
21470   assert(
21471       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21472       "Called with something other than an x86 128-bit half shuffle!");
21473   SDLoc DL(N);
21474   unsigned CombineOpcode = N.getOpcode();
21475
21476   // Walk up a single-use chain looking for a combinable shuffle.
21477   SDValue V = N.getOperand(0);
21478   for (; V.hasOneUse(); V = V.getOperand(0)) {
21479     switch (V.getOpcode()) {
21480     default:
21481       return false; // Nothing combined!
21482
21483     case ISD::BITCAST:
21484       // Skip bitcasts as we always know the type for the target specific
21485       // instructions.
21486       continue;
21487
21488     case X86ISD::PSHUFLW:
21489     case X86ISD::PSHUFHW:
21490       if (V.getOpcode() == CombineOpcode)
21491         break;
21492
21493       // Other-half shuffles are no-ops.
21494       continue;
21495     }
21496     // Break out of the loop if we break out of the switch.
21497     break;
21498   }
21499
21500   if (!V.hasOneUse())
21501     // We fell out of the loop without finding a viable combining instruction.
21502     return false;
21503
21504   // Combine away the bottom node as its shuffle will be accumulated into
21505   // a preceding shuffle.
21506   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21507
21508   // Record the old value.
21509   SDValue Old = V;
21510
21511   // Merge this node's mask and our incoming mask (adjusted to account for all
21512   // the pshufd instructions encountered).
21513   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21514   for (int &M : Mask)
21515     M = VMask[M];
21516   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21517                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21518
21519   // Check that the shuffles didn't cancel each other out. If not, we need to
21520   // combine to the new one.
21521   if (Old != V)
21522     // Replace the combinable shuffle with the combined one, updating all users
21523     // so that we re-evaluate the chain here.
21524     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21525
21526   return true;
21527 }
21528
21529 /// \brief Try to combine x86 target specific shuffles.
21530 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21531                                            TargetLowering::DAGCombinerInfo &DCI,
21532                                            const X86Subtarget *Subtarget) {
21533   SDLoc DL(N);
21534   MVT VT = N.getSimpleValueType();
21535   SmallVector<int, 4> Mask;
21536
21537   switch (N.getOpcode()) {
21538   case X86ISD::PSHUFD:
21539   case X86ISD::PSHUFLW:
21540   case X86ISD::PSHUFHW:
21541     Mask = getPSHUFShuffleMask(N);
21542     assert(Mask.size() == 4);
21543     break;
21544   default:
21545     return SDValue();
21546   }
21547
21548   // Nuke no-op shuffles that show up after combining.
21549   if (isNoopShuffleMask(Mask))
21550     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21551
21552   // Look for simplifications involving one or two shuffle instructions.
21553   SDValue V = N.getOperand(0);
21554   switch (N.getOpcode()) {
21555   default:
21556     break;
21557   case X86ISD::PSHUFLW:
21558   case X86ISD::PSHUFHW:
21559     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21560
21561     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21562       return SDValue(); // We combined away this shuffle, so we're done.
21563
21564     // See if this reduces to a PSHUFD which is no more expensive and can
21565     // combine with more operations. Note that it has to at least flip the
21566     // dwords as otherwise it would have been removed as a no-op.
21567     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21568       int DMask[] = {0, 1, 2, 3};
21569       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21570       DMask[DOffset + 0] = DOffset + 1;
21571       DMask[DOffset + 1] = DOffset + 0;
21572       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21573       V = DAG.getBitcast(DVT, V);
21574       DCI.AddToWorklist(V.getNode());
21575       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21576                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21577       DCI.AddToWorklist(V.getNode());
21578       return DAG.getBitcast(VT, V);
21579     }
21580
21581     // Look for shuffle patterns which can be implemented as a single unpack.
21582     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21583     // only works when we have a PSHUFD followed by two half-shuffles.
21584     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21585         (V.getOpcode() == X86ISD::PSHUFLW ||
21586          V.getOpcode() == X86ISD::PSHUFHW) &&
21587         V.getOpcode() != N.getOpcode() &&
21588         V.hasOneUse()) {
21589       SDValue D = V.getOperand(0);
21590       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21591         D = D.getOperand(0);
21592       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21593         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21594         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21595         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21596         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21597         int WordMask[8];
21598         for (int i = 0; i < 4; ++i) {
21599           WordMask[i + NOffset] = Mask[i] + NOffset;
21600           WordMask[i + VOffset] = VMask[i] + VOffset;
21601         }
21602         // Map the word mask through the DWord mask.
21603         int MappedMask[8];
21604         for (int i = 0; i < 8; ++i)
21605           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21606         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21607             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21608           // We can replace all three shuffles with an unpack.
21609           V = DAG.getBitcast(VT, D.getOperand(0));
21610           DCI.AddToWorklist(V.getNode());
21611           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21612                                                 : X86ISD::UNPCKH,
21613                              DL, VT, V, V);
21614         }
21615       }
21616     }
21617
21618     break;
21619
21620   case X86ISD::PSHUFD:
21621     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21622       return NewN;
21623
21624     break;
21625   }
21626
21627   return SDValue();
21628 }
21629
21630 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21631 ///
21632 /// We combine this directly on the abstract vector shuffle nodes so it is
21633 /// easier to generically match. We also insert dummy vector shuffle nodes for
21634 /// the operands which explicitly discard the lanes which are unused by this
21635 /// operation to try to flow through the rest of the combiner the fact that
21636 /// they're unused.
21637 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21638   SDLoc DL(N);
21639   EVT VT = N->getValueType(0);
21640
21641   // We only handle target-independent shuffles.
21642   // FIXME: It would be easy and harmless to use the target shuffle mask
21643   // extraction tool to support more.
21644   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21645     return SDValue();
21646
21647   auto *SVN = cast<ShuffleVectorSDNode>(N);
21648   ArrayRef<int> Mask = SVN->getMask();
21649   SDValue V1 = N->getOperand(0);
21650   SDValue V2 = N->getOperand(1);
21651
21652   // We require the first shuffle operand to be the SUB node, and the second to
21653   // be the ADD node.
21654   // FIXME: We should support the commuted patterns.
21655   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21656     return SDValue();
21657
21658   // If there are other uses of these operations we can't fold them.
21659   if (!V1->hasOneUse() || !V2->hasOneUse())
21660     return SDValue();
21661
21662   // Ensure that both operations have the same operands. Note that we can
21663   // commute the FADD operands.
21664   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21665   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21666       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21667     return SDValue();
21668
21669   // We're looking for blends between FADD and FSUB nodes. We insist on these
21670   // nodes being lined up in a specific expected pattern.
21671   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21672         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21673         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21674     return SDValue();
21675
21676   // Only specific types are legal at this point, assert so we notice if and
21677   // when these change.
21678   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21679           VT == MVT::v4f64) &&
21680          "Unknown vector type encountered!");
21681
21682   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21683 }
21684
21685 /// PerformShuffleCombine - Performs several different shuffle combines.
21686 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21687                                      TargetLowering::DAGCombinerInfo &DCI,
21688                                      const X86Subtarget *Subtarget) {
21689   SDLoc dl(N);
21690   SDValue N0 = N->getOperand(0);
21691   SDValue N1 = N->getOperand(1);
21692   EVT VT = N->getValueType(0);
21693
21694   // Don't create instructions with illegal types after legalize types has run.
21695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21696   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21697     return SDValue();
21698
21699   // If we have legalized the vector types, look for blends of FADD and FSUB
21700   // nodes that we can fuse into an ADDSUB node.
21701   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21702     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21703       return AddSub;
21704
21705   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21706   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21707       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21708     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21709
21710   // During Type Legalization, when promoting illegal vector types,
21711   // the backend might introduce new shuffle dag nodes and bitcasts.
21712   //
21713   // This code performs the following transformation:
21714   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21715   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21716   //
21717   // We do this only if both the bitcast and the BINOP dag nodes have
21718   // one use. Also, perform this transformation only if the new binary
21719   // operation is legal. This is to avoid introducing dag nodes that
21720   // potentially need to be further expanded (or custom lowered) into a
21721   // less optimal sequence of dag nodes.
21722   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21723       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21724       N0.getOpcode() == ISD::BITCAST) {
21725     SDValue BC0 = N0.getOperand(0);
21726     EVT SVT = BC0.getValueType();
21727     unsigned Opcode = BC0.getOpcode();
21728     unsigned NumElts = VT.getVectorNumElements();
21729
21730     if (BC0.hasOneUse() && SVT.isVector() &&
21731         SVT.getVectorNumElements() * 2 == NumElts &&
21732         TLI.isOperationLegal(Opcode, VT)) {
21733       bool CanFold = false;
21734       switch (Opcode) {
21735       default : break;
21736       case ISD::ADD :
21737       case ISD::FADD :
21738       case ISD::SUB :
21739       case ISD::FSUB :
21740       case ISD::MUL :
21741       case ISD::FMUL :
21742         CanFold = true;
21743       }
21744
21745       unsigned SVTNumElts = SVT.getVectorNumElements();
21746       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21747       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21748         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21749       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21750         CanFold = SVOp->getMaskElt(i) < 0;
21751
21752       if (CanFold) {
21753         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21754         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21755         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21756         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21757       }
21758     }
21759   }
21760
21761   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21762   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21763   // consecutive, non-overlapping, and in the right order.
21764   SmallVector<SDValue, 16> Elts;
21765   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21766     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21767
21768   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21769     return LD;
21770
21771   if (isTargetShuffle(N->getOpcode())) {
21772     SDValue Shuffle =
21773         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21774     if (Shuffle.getNode())
21775       return Shuffle;
21776
21777     // Try recursively combining arbitrary sequences of x86 shuffle
21778     // instructions into higher-order shuffles. We do this after combining
21779     // specific PSHUF instruction sequences into their minimal form so that we
21780     // can evaluate how many specialized shuffle instructions are involved in
21781     // a particular chain.
21782     SmallVector<int, 1> NonceMask; // Just a placeholder.
21783     NonceMask.push_back(0);
21784     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21785                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21786                                       DCI, Subtarget))
21787       return SDValue(); // This routine will use CombineTo to replace N.
21788   }
21789
21790   return SDValue();
21791 }
21792
21793 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21794 /// specific shuffle of a load can be folded into a single element load.
21795 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21796 /// shuffles have been custom lowered so we need to handle those here.
21797 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21798                                          TargetLowering::DAGCombinerInfo &DCI) {
21799   if (DCI.isBeforeLegalizeOps())
21800     return SDValue();
21801
21802   SDValue InVec = N->getOperand(0);
21803   SDValue EltNo = N->getOperand(1);
21804
21805   if (!isa<ConstantSDNode>(EltNo))
21806     return SDValue();
21807
21808   EVT OriginalVT = InVec.getValueType();
21809
21810   if (InVec.getOpcode() == ISD::BITCAST) {
21811     // Don't duplicate a load with other uses.
21812     if (!InVec.hasOneUse())
21813       return SDValue();
21814     EVT BCVT = InVec.getOperand(0).getValueType();
21815     if (!BCVT.isVector() ||
21816         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21817       return SDValue();
21818     InVec = InVec.getOperand(0);
21819   }
21820
21821   EVT CurrentVT = InVec.getValueType();
21822
21823   if (!isTargetShuffle(InVec.getOpcode()))
21824     return SDValue();
21825
21826   // Don't duplicate a load with other uses.
21827   if (!InVec.hasOneUse())
21828     return SDValue();
21829
21830   SmallVector<int, 16> ShuffleMask;
21831   bool UnaryShuffle;
21832   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21833                             ShuffleMask, UnaryShuffle))
21834     return SDValue();
21835
21836   // Select the input vector, guarding against out of range extract vector.
21837   unsigned NumElems = CurrentVT.getVectorNumElements();
21838   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21839   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21840   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21841                                          : InVec.getOperand(1);
21842
21843   // If inputs to shuffle are the same for both ops, then allow 2 uses
21844   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21845                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21846
21847   if (LdNode.getOpcode() == ISD::BITCAST) {
21848     // Don't duplicate a load with other uses.
21849     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21850       return SDValue();
21851
21852     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21853     LdNode = LdNode.getOperand(0);
21854   }
21855
21856   if (!ISD::isNormalLoad(LdNode.getNode()))
21857     return SDValue();
21858
21859   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21860
21861   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21862     return SDValue();
21863
21864   EVT EltVT = N->getValueType(0);
21865   // If there's a bitcast before the shuffle, check if the load type and
21866   // alignment is valid.
21867   unsigned Align = LN0->getAlignment();
21868   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21869   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
21870       EltVT.getTypeForEVT(*DAG.getContext()));
21871
21872   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21873     return SDValue();
21874
21875   // All checks match so transform back to vector_shuffle so that DAG combiner
21876   // can finish the job
21877   SDLoc dl(N);
21878
21879   // Create shuffle node taking into account the case that its a unary shuffle
21880   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21881                                    : InVec.getOperand(1);
21882   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21883                                  InVec.getOperand(0), Shuffle,
21884                                  &ShuffleMask[0]);
21885   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21886   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21887                      EltNo);
21888 }
21889
21890 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21891 /// special and don't usually play with other vector types, it's better to
21892 /// handle them early to be sure we emit efficient code by avoiding
21893 /// store-load conversions.
21894 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21895   if (N->getValueType(0) != MVT::x86mmx ||
21896       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21897       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21898     return SDValue();
21899
21900   SDValue V = N->getOperand(0);
21901   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21902   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21903     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21904                        N->getValueType(0), V.getOperand(0));
21905
21906   return SDValue();
21907 }
21908
21909 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21910 /// generation and convert it from being a bunch of shuffles and extracts
21911 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21912 /// storing the value and loading scalars back, while for x64 we should
21913 /// use 64-bit extracts and shifts.
21914 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21915                                          TargetLowering::DAGCombinerInfo &DCI) {
21916   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
21917     return NewOp;
21918
21919   SDValue InputVector = N->getOperand(0);
21920   SDLoc dl(InputVector);
21921   // Detect mmx to i32 conversion through a v2i32 elt extract.
21922   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21923       N->getValueType(0) == MVT::i32 &&
21924       InputVector.getValueType() == MVT::v2i32) {
21925
21926     // The bitcast source is a direct mmx result.
21927     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21928     if (MMXSrc.getValueType() == MVT::x86mmx)
21929       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21930                          N->getValueType(0),
21931                          InputVector.getNode()->getOperand(0));
21932
21933     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21934     SDValue MMXSrcOp = MMXSrc.getOperand(0);
21935     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21936         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21937         MMXSrcOp.getOpcode() == ISD::BITCAST &&
21938         MMXSrcOp.getValueType() == MVT::v1i64 &&
21939         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21940       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21941                          N->getValueType(0),
21942                          MMXSrcOp.getOperand(0));
21943   }
21944
21945   EVT VT = N->getValueType(0);
21946
21947   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21948       InputVector.getOpcode() == ISD::BITCAST &&
21949       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21950     uint64_t ExtractedElt =
21951           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21952     uint64_t InputValue =
21953           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21954     uint64_t Res = (InputValue >> ExtractedElt) & 1;
21955     return DAG.getConstant(Res, dl, MVT::i1);
21956   }
21957   // Only operate on vectors of 4 elements, where the alternative shuffling
21958   // gets to be more expensive.
21959   if (InputVector.getValueType() != MVT::v4i32)
21960     return SDValue();
21961
21962   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21963   // single use which is a sign-extend or zero-extend, and all elements are
21964   // used.
21965   SmallVector<SDNode *, 4> Uses;
21966   unsigned ExtractedElements = 0;
21967   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21968        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21969     if (UI.getUse().getResNo() != InputVector.getResNo())
21970       return SDValue();
21971
21972     SDNode *Extract = *UI;
21973     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21974       return SDValue();
21975
21976     if (Extract->getValueType(0) != MVT::i32)
21977       return SDValue();
21978     if (!Extract->hasOneUse())
21979       return SDValue();
21980     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21981         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21982       return SDValue();
21983     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21984       return SDValue();
21985
21986     // Record which element was extracted.
21987     ExtractedElements |=
21988       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21989
21990     Uses.push_back(Extract);
21991   }
21992
21993   // If not all the elements were used, this may not be worthwhile.
21994   if (ExtractedElements != 15)
21995     return SDValue();
21996
21997   // Ok, we've now decided to do the transformation.
21998   // If 64-bit shifts are legal, use the extract-shift sequence,
21999   // otherwise bounce the vector off the cache.
22000   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22001   SDValue Vals[4];
22002
22003   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22004     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22005     auto &DL = DAG.getDataLayout();
22006     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22007     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22008       DAG.getConstant(0, dl, VecIdxTy));
22009     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22010       DAG.getConstant(1, dl, VecIdxTy));
22011
22012     SDValue ShAmt = DAG.getConstant(
22013         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22014     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22015     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22016       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22017     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22018     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22019       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22020   } else {
22021     // Store the value to a temporary stack slot.
22022     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22023     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22024       MachinePointerInfo(), false, false, 0);
22025
22026     EVT ElementType = InputVector.getValueType().getVectorElementType();
22027     unsigned EltSize = ElementType.getSizeInBits() / 8;
22028
22029     // Replace each use (extract) with a load of the appropriate element.
22030     for (unsigned i = 0; i < 4; ++i) {
22031       uint64_t Offset = EltSize * i;
22032       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22033       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22034
22035       SDValue ScalarAddr =
22036           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22037
22038       // Load the scalar.
22039       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22040                             ScalarAddr, MachinePointerInfo(),
22041                             false, false, false, 0);
22042
22043     }
22044   }
22045
22046   // Replace the extracts
22047   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22048     UE = Uses.end(); UI != UE; ++UI) {
22049     SDNode *Extract = *UI;
22050
22051     SDValue Idx = Extract->getOperand(1);
22052     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22053     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22054   }
22055
22056   // The replacement was made in place; don't return anything.
22057   return SDValue();
22058 }
22059
22060 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22061 static std::pair<unsigned, bool>
22062 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22063                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22064   if (!VT.isVector())
22065     return std::make_pair(0, false);
22066
22067   bool NeedSplit = false;
22068   switch (VT.getSimpleVT().SimpleTy) {
22069   default: return std::make_pair(0, false);
22070   case MVT::v4i64:
22071   case MVT::v2i64:
22072     if (!Subtarget->hasVLX())
22073       return std::make_pair(0, false);
22074     break;
22075   case MVT::v64i8:
22076   case MVT::v32i16:
22077     if (!Subtarget->hasBWI())
22078       return std::make_pair(0, false);
22079     break;
22080   case MVT::v16i32:
22081   case MVT::v8i64:
22082     if (!Subtarget->hasAVX512())
22083       return std::make_pair(0, false);
22084     break;
22085   case MVT::v32i8:
22086   case MVT::v16i16:
22087   case MVT::v8i32:
22088     if (!Subtarget->hasAVX2())
22089       NeedSplit = true;
22090     if (!Subtarget->hasAVX())
22091       return std::make_pair(0, false);
22092     break;
22093   case MVT::v16i8:
22094   case MVT::v8i16:
22095   case MVT::v4i32:
22096     if (!Subtarget->hasSSE2())
22097       return std::make_pair(0, false);
22098   }
22099
22100   // SSE2 has only a small subset of the operations.
22101   bool hasUnsigned = Subtarget->hasSSE41() ||
22102                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22103   bool hasSigned = Subtarget->hasSSE41() ||
22104                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22105
22106   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22107
22108   unsigned Opc = 0;
22109   // Check for x CC y ? x : y.
22110   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22111       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22112     switch (CC) {
22113     default: break;
22114     case ISD::SETULT:
22115     case ISD::SETULE:
22116       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22117     case ISD::SETUGT:
22118     case ISD::SETUGE:
22119       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22120     case ISD::SETLT:
22121     case ISD::SETLE:
22122       Opc = hasSigned ? ISD::SMIN : 0; break;
22123     case ISD::SETGT:
22124     case ISD::SETGE:
22125       Opc = hasSigned ? ISD::SMAX : 0; break;
22126     }
22127   // Check for x CC y ? y : x -- a min/max with reversed arms.
22128   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22129              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22130     switch (CC) {
22131     default: break;
22132     case ISD::SETULT:
22133     case ISD::SETULE:
22134       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22135     case ISD::SETUGT:
22136     case ISD::SETUGE:
22137       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22138     case ISD::SETLT:
22139     case ISD::SETLE:
22140       Opc = hasSigned ? ISD::SMAX : 0; break;
22141     case ISD::SETGT:
22142     case ISD::SETGE:
22143       Opc = hasSigned ? ISD::SMIN : 0; break;
22144     }
22145   }
22146
22147   return std::make_pair(Opc, NeedSplit);
22148 }
22149
22150 static SDValue
22151 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22152                                       const X86Subtarget *Subtarget) {
22153   SDLoc dl(N);
22154   SDValue Cond = N->getOperand(0);
22155   SDValue LHS = N->getOperand(1);
22156   SDValue RHS = N->getOperand(2);
22157
22158   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22159     SDValue CondSrc = Cond->getOperand(0);
22160     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22161       Cond = CondSrc->getOperand(0);
22162   }
22163
22164   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22165     return SDValue();
22166
22167   // A vselect where all conditions and data are constants can be optimized into
22168   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22169   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22170       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22171     return SDValue();
22172
22173   unsigned MaskValue = 0;
22174   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22175     return SDValue();
22176
22177   MVT VT = N->getSimpleValueType(0);
22178   unsigned NumElems = VT.getVectorNumElements();
22179   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22180   for (unsigned i = 0; i < NumElems; ++i) {
22181     // Be sure we emit undef where we can.
22182     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22183       ShuffleMask[i] = -1;
22184     else
22185       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22186   }
22187
22188   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22189   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22190     return SDValue();
22191   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22192 }
22193
22194 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22195 /// nodes.
22196 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22197                                     TargetLowering::DAGCombinerInfo &DCI,
22198                                     const X86Subtarget *Subtarget) {
22199   SDLoc DL(N);
22200   SDValue Cond = N->getOperand(0);
22201   // Get the LHS/RHS of the select.
22202   SDValue LHS = N->getOperand(1);
22203   SDValue RHS = N->getOperand(2);
22204   EVT VT = LHS.getValueType();
22205   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22206
22207   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22208   // instructions match the semantics of the common C idiom x<y?x:y but not
22209   // x<=y?x:y, because of how they handle negative zero (which can be
22210   // ignored in unsafe-math mode).
22211   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22212   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22213       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22214       (Subtarget->hasSSE2() ||
22215        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22216     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22217
22218     unsigned Opcode = 0;
22219     // Check for x CC y ? x : y.
22220     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22221         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22222       switch (CC) {
22223       default: break;
22224       case ISD::SETULT:
22225         // Converting this to a min would handle NaNs incorrectly, and swapping
22226         // the operands would cause it to handle comparisons between positive
22227         // and negative zero incorrectly.
22228         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22229           if (!DAG.getTarget().Options.UnsafeFPMath &&
22230               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22231             break;
22232           std::swap(LHS, RHS);
22233         }
22234         Opcode = X86ISD::FMIN;
22235         break;
22236       case ISD::SETOLE:
22237         // Converting this to a min would handle comparisons between positive
22238         // and negative zero incorrectly.
22239         if (!DAG.getTarget().Options.UnsafeFPMath &&
22240             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22241           break;
22242         Opcode = X86ISD::FMIN;
22243         break;
22244       case ISD::SETULE:
22245         // Converting this to a min would handle both negative zeros and NaNs
22246         // incorrectly, but we can swap the operands to fix both.
22247         std::swap(LHS, RHS);
22248       case ISD::SETOLT:
22249       case ISD::SETLT:
22250       case ISD::SETLE:
22251         Opcode = X86ISD::FMIN;
22252         break;
22253
22254       case ISD::SETOGE:
22255         // Converting this to a max would handle comparisons between positive
22256         // and negative zero incorrectly.
22257         if (!DAG.getTarget().Options.UnsafeFPMath &&
22258             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22259           break;
22260         Opcode = X86ISD::FMAX;
22261         break;
22262       case ISD::SETUGT:
22263         // Converting this to a max would handle NaNs incorrectly, and swapping
22264         // the operands would cause it to handle comparisons between positive
22265         // and negative zero incorrectly.
22266         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22267           if (!DAG.getTarget().Options.UnsafeFPMath &&
22268               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22269             break;
22270           std::swap(LHS, RHS);
22271         }
22272         Opcode = X86ISD::FMAX;
22273         break;
22274       case ISD::SETUGE:
22275         // Converting this to a max would handle both negative zeros and NaNs
22276         // incorrectly, but we can swap the operands to fix both.
22277         std::swap(LHS, RHS);
22278       case ISD::SETOGT:
22279       case ISD::SETGT:
22280       case ISD::SETGE:
22281         Opcode = X86ISD::FMAX;
22282         break;
22283       }
22284     // Check for x CC y ? y : x -- a min/max with reversed arms.
22285     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22286                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22287       switch (CC) {
22288       default: break;
22289       case ISD::SETOGE:
22290         // Converting this to a min would handle comparisons between positive
22291         // and negative zero incorrectly, and swapping the operands would
22292         // cause it to handle NaNs incorrectly.
22293         if (!DAG.getTarget().Options.UnsafeFPMath &&
22294             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22295           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22296             break;
22297           std::swap(LHS, RHS);
22298         }
22299         Opcode = X86ISD::FMIN;
22300         break;
22301       case ISD::SETUGT:
22302         // Converting this to a min would handle NaNs incorrectly.
22303         if (!DAG.getTarget().Options.UnsafeFPMath &&
22304             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22305           break;
22306         Opcode = X86ISD::FMIN;
22307         break;
22308       case ISD::SETUGE:
22309         // Converting this to a min would handle both negative zeros and NaNs
22310         // incorrectly, but we can swap the operands to fix both.
22311         std::swap(LHS, RHS);
22312       case ISD::SETOGT:
22313       case ISD::SETGT:
22314       case ISD::SETGE:
22315         Opcode = X86ISD::FMIN;
22316         break;
22317
22318       case ISD::SETULT:
22319         // Converting this to a max would handle NaNs incorrectly.
22320         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22321           break;
22322         Opcode = X86ISD::FMAX;
22323         break;
22324       case ISD::SETOLE:
22325         // Converting this to a max would handle comparisons between positive
22326         // and negative zero incorrectly, and swapping the operands would
22327         // cause it to handle NaNs incorrectly.
22328         if (!DAG.getTarget().Options.UnsafeFPMath &&
22329             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22330           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22331             break;
22332           std::swap(LHS, RHS);
22333         }
22334         Opcode = X86ISD::FMAX;
22335         break;
22336       case ISD::SETULE:
22337         // Converting this to a max would handle both negative zeros and NaNs
22338         // incorrectly, but we can swap the operands to fix both.
22339         std::swap(LHS, RHS);
22340       case ISD::SETOLT:
22341       case ISD::SETLT:
22342       case ISD::SETLE:
22343         Opcode = X86ISD::FMAX;
22344         break;
22345       }
22346     }
22347
22348     if (Opcode)
22349       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22350   }
22351
22352   EVT CondVT = Cond.getValueType();
22353   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22354       CondVT.getVectorElementType() == MVT::i1) {
22355     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22356     // lowering on KNL. In this case we convert it to
22357     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22358     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22359     // Since SKX these selects have a proper lowering.
22360     EVT OpVT = LHS.getValueType();
22361     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22362         (OpVT.getVectorElementType() == MVT::i8 ||
22363          OpVT.getVectorElementType() == MVT::i16) &&
22364         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22365       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22366       DCI.AddToWorklist(Cond.getNode());
22367       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22368     }
22369   }
22370   // If this is a select between two integer constants, try to do some
22371   // optimizations.
22372   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22373     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22374       // Don't do this for crazy integer types.
22375       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22376         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22377         // so that TrueC (the true value) is larger than FalseC.
22378         bool NeedsCondInvert = false;
22379
22380         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22381             // Efficiently invertible.
22382             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22383              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22384               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22385           NeedsCondInvert = true;
22386           std::swap(TrueC, FalseC);
22387         }
22388
22389         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22390         if (FalseC->getAPIntValue() == 0 &&
22391             TrueC->getAPIntValue().isPowerOf2()) {
22392           if (NeedsCondInvert) // Invert the condition if needed.
22393             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22394                                DAG.getConstant(1, DL, Cond.getValueType()));
22395
22396           // Zero extend the condition if needed.
22397           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22398
22399           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22400           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22401                              DAG.getConstant(ShAmt, DL, MVT::i8));
22402         }
22403
22404         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22405         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22406           if (NeedsCondInvert) // Invert the condition if needed.
22407             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22408                                DAG.getConstant(1, DL, Cond.getValueType()));
22409
22410           // Zero extend the condition if needed.
22411           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22412                              FalseC->getValueType(0), Cond);
22413           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22414                              SDValue(FalseC, 0));
22415         }
22416
22417         // Optimize cases that will turn into an LEA instruction.  This requires
22418         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22419         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22420           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22421           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22422
22423           bool isFastMultiplier = false;
22424           if (Diff < 10) {
22425             switch ((unsigned char)Diff) {
22426               default: break;
22427               case 1:  // result = add base, cond
22428               case 2:  // result = lea base(    , cond*2)
22429               case 3:  // result = lea base(cond, cond*2)
22430               case 4:  // result = lea base(    , cond*4)
22431               case 5:  // result = lea base(cond, cond*4)
22432               case 8:  // result = lea base(    , cond*8)
22433               case 9:  // result = lea base(cond, cond*8)
22434                 isFastMultiplier = true;
22435                 break;
22436             }
22437           }
22438
22439           if (isFastMultiplier) {
22440             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22441             if (NeedsCondInvert) // Invert the condition if needed.
22442               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22443                                  DAG.getConstant(1, DL, Cond.getValueType()));
22444
22445             // Zero extend the condition if needed.
22446             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22447                                Cond);
22448             // Scale the condition by the difference.
22449             if (Diff != 1)
22450               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22451                                  DAG.getConstant(Diff, DL,
22452                                                  Cond.getValueType()));
22453
22454             // Add the base if non-zero.
22455             if (FalseC->getAPIntValue() != 0)
22456               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22457                                  SDValue(FalseC, 0));
22458             return Cond;
22459           }
22460         }
22461       }
22462   }
22463
22464   // Canonicalize max and min:
22465   // (x > y) ? x : y -> (x >= y) ? x : y
22466   // (x < y) ? x : y -> (x <= y) ? x : y
22467   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22468   // the need for an extra compare
22469   // against zero. e.g.
22470   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22471   // subl   %esi, %edi
22472   // testl  %edi, %edi
22473   // movl   $0, %eax
22474   // cmovgl %edi, %eax
22475   // =>
22476   // xorl   %eax, %eax
22477   // subl   %esi, $edi
22478   // cmovsl %eax, %edi
22479   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22480       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22481       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22482     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22483     switch (CC) {
22484     default: break;
22485     case ISD::SETLT:
22486     case ISD::SETGT: {
22487       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22488       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22489                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22490       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22491     }
22492     }
22493   }
22494
22495   // Early exit check
22496   if (!TLI.isTypeLegal(VT))
22497     return SDValue();
22498
22499   // Match VSELECTs into subs with unsigned saturation.
22500   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22501       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22502       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22503        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22504     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22505
22506     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22507     // left side invert the predicate to simplify logic below.
22508     SDValue Other;
22509     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22510       Other = RHS;
22511       CC = ISD::getSetCCInverse(CC, true);
22512     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22513       Other = LHS;
22514     }
22515
22516     if (Other.getNode() && Other->getNumOperands() == 2 &&
22517         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22518       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22519       SDValue CondRHS = Cond->getOperand(1);
22520
22521       // Look for a general sub with unsigned saturation first.
22522       // x >= y ? x-y : 0 --> subus x, y
22523       // x >  y ? x-y : 0 --> subus x, y
22524       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22525           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22526         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22527
22528       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22529         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22530           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22531             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22532               // If the RHS is a constant we have to reverse the const
22533               // canonicalization.
22534               // x > C-1 ? x+-C : 0 --> subus x, C
22535               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22536                   CondRHSConst->getAPIntValue() ==
22537                       (-OpRHSConst->getAPIntValue() - 1))
22538                 return DAG.getNode(
22539                     X86ISD::SUBUS, DL, VT, OpLHS,
22540                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22541
22542           // Another special case: If C was a sign bit, the sub has been
22543           // canonicalized into a xor.
22544           // FIXME: Would it be better to use computeKnownBits to determine
22545           //        whether it's safe to decanonicalize the xor?
22546           // x s< 0 ? x^C : 0 --> subus x, C
22547           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22548               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22549               OpRHSConst->getAPIntValue().isSignBit())
22550             // Note that we have to rebuild the RHS constant here to ensure we
22551             // don't rely on particular values of undef lanes.
22552             return DAG.getNode(
22553                 X86ISD::SUBUS, DL, VT, OpLHS,
22554                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22555         }
22556     }
22557   }
22558
22559   // Try to match a min/max vector operation.
22560   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22561     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22562     unsigned Opc = ret.first;
22563     bool NeedSplit = ret.second;
22564
22565     if (Opc && NeedSplit) {
22566       unsigned NumElems = VT.getVectorNumElements();
22567       // Extract the LHS vectors
22568       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22569       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22570
22571       // Extract the RHS vectors
22572       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22573       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22574
22575       // Create min/max for each subvector
22576       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22577       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22578
22579       // Merge the result
22580       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22581     } else if (Opc)
22582       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22583   }
22584
22585   // Simplify vector selection if condition value type matches vselect
22586   // operand type
22587   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22588     assert(Cond.getValueType().isVector() &&
22589            "vector select expects a vector selector!");
22590
22591     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22592     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22593
22594     // Try invert the condition if true value is not all 1s and false value
22595     // is not all 0s.
22596     if (!TValIsAllOnes && !FValIsAllZeros &&
22597         // Check if the selector will be produced by CMPP*/PCMP*
22598         Cond.getOpcode() == ISD::SETCC &&
22599         // Check if SETCC has already been promoted
22600         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22601             CondVT) {
22602       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22603       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22604
22605       if (TValIsAllZeros || FValIsAllOnes) {
22606         SDValue CC = Cond.getOperand(2);
22607         ISD::CondCode NewCC =
22608           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22609                                Cond.getOperand(0).getValueType().isInteger());
22610         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22611         std::swap(LHS, RHS);
22612         TValIsAllOnes = FValIsAllOnes;
22613         FValIsAllZeros = TValIsAllZeros;
22614       }
22615     }
22616
22617     if (TValIsAllOnes || FValIsAllZeros) {
22618       SDValue Ret;
22619
22620       if (TValIsAllOnes && FValIsAllZeros)
22621         Ret = Cond;
22622       else if (TValIsAllOnes)
22623         Ret =
22624             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22625       else if (FValIsAllZeros)
22626         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22627                           DAG.getBitcast(CondVT, LHS));
22628
22629       return DAG.getBitcast(VT, Ret);
22630     }
22631   }
22632
22633   // We should generate an X86ISD::BLENDI from a vselect if its argument
22634   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22635   // constants. This specific pattern gets generated when we split a
22636   // selector for a 512 bit vector in a machine without AVX512 (but with
22637   // 256-bit vectors), during legalization:
22638   //
22639   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22640   //
22641   // Iff we find this pattern and the build_vectors are built from
22642   // constants, we translate the vselect into a shuffle_vector that we
22643   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22644   if ((N->getOpcode() == ISD::VSELECT ||
22645        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22646       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22647     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22648     if (Shuffle.getNode())
22649       return Shuffle;
22650   }
22651
22652   // If this is a *dynamic* select (non-constant condition) and we can match
22653   // this node with one of the variable blend instructions, restructure the
22654   // condition so that the blends can use the high bit of each element and use
22655   // SimplifyDemandedBits to simplify the condition operand.
22656   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22657       !DCI.isBeforeLegalize() &&
22658       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22659     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22660
22661     // Don't optimize vector selects that map to mask-registers.
22662     if (BitWidth == 1)
22663       return SDValue();
22664
22665     // We can only handle the cases where VSELECT is directly legal on the
22666     // subtarget. We custom lower VSELECT nodes with constant conditions and
22667     // this makes it hard to see whether a dynamic VSELECT will correctly
22668     // lower, so we both check the operation's status and explicitly handle the
22669     // cases where a *dynamic* blend will fail even though a constant-condition
22670     // blend could be custom lowered.
22671     // FIXME: We should find a better way to handle this class of problems.
22672     // Potentially, we should combine constant-condition vselect nodes
22673     // pre-legalization into shuffles and not mark as many types as custom
22674     // lowered.
22675     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22676       return SDValue();
22677     // FIXME: We don't support i16-element blends currently. We could and
22678     // should support them by making *all* the bits in the condition be set
22679     // rather than just the high bit and using an i8-element blend.
22680     if (VT.getScalarType() == MVT::i16)
22681       return SDValue();
22682     // Dynamic blending was only available from SSE4.1 onward.
22683     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22684       return SDValue();
22685     // Byte blends are only available in AVX2
22686     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22687         !Subtarget->hasAVX2())
22688       return SDValue();
22689
22690     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22691     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22692
22693     APInt KnownZero, KnownOne;
22694     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22695                                           DCI.isBeforeLegalizeOps());
22696     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22697         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22698                                  TLO)) {
22699       // If we changed the computation somewhere in the DAG, this change
22700       // will affect all users of Cond.
22701       // Make sure it is fine and update all the nodes so that we do not
22702       // use the generic VSELECT anymore. Otherwise, we may perform
22703       // wrong optimizations as we messed up with the actual expectation
22704       // for the vector boolean values.
22705       if (Cond != TLO.Old) {
22706         // Check all uses of that condition operand to check whether it will be
22707         // consumed by non-BLEND instructions, which may depend on all bits are
22708         // set properly.
22709         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22710              I != E; ++I)
22711           if (I->getOpcode() != ISD::VSELECT)
22712             // TODO: Add other opcodes eventually lowered into BLEND.
22713             return SDValue();
22714
22715         // Update all the users of the condition, before committing the change,
22716         // so that the VSELECT optimizations that expect the correct vector
22717         // boolean value will not be triggered.
22718         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22719              I != E; ++I)
22720           DAG.ReplaceAllUsesOfValueWith(
22721               SDValue(*I, 0),
22722               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22723                           Cond, I->getOperand(1), I->getOperand(2)));
22724         DCI.CommitTargetLoweringOpt(TLO);
22725         return SDValue();
22726       }
22727       // At this point, only Cond is changed. Change the condition
22728       // just for N to keep the opportunity to optimize all other
22729       // users their own way.
22730       DAG.ReplaceAllUsesOfValueWith(
22731           SDValue(N, 0),
22732           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22733                       TLO.New, N->getOperand(1), N->getOperand(2)));
22734       return SDValue();
22735     }
22736   }
22737
22738   return SDValue();
22739 }
22740
22741 // Check whether a boolean test is testing a boolean value generated by
22742 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22743 // code.
22744 //
22745 // Simplify the following patterns:
22746 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22747 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22748 // to (Op EFLAGS Cond)
22749 //
22750 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22751 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22752 // to (Op EFLAGS !Cond)
22753 //
22754 // where Op could be BRCOND or CMOV.
22755 //
22756 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22757   // Quit if not CMP and SUB with its value result used.
22758   if (Cmp.getOpcode() != X86ISD::CMP &&
22759       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22760       return SDValue();
22761
22762   // Quit if not used as a boolean value.
22763   if (CC != X86::COND_E && CC != X86::COND_NE)
22764     return SDValue();
22765
22766   // Check CMP operands. One of them should be 0 or 1 and the other should be
22767   // an SetCC or extended from it.
22768   SDValue Op1 = Cmp.getOperand(0);
22769   SDValue Op2 = Cmp.getOperand(1);
22770
22771   SDValue SetCC;
22772   const ConstantSDNode* C = nullptr;
22773   bool needOppositeCond = (CC == X86::COND_E);
22774   bool checkAgainstTrue = false; // Is it a comparison against 1?
22775
22776   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22777     SetCC = Op2;
22778   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22779     SetCC = Op1;
22780   else // Quit if all operands are not constants.
22781     return SDValue();
22782
22783   if (C->getZExtValue() == 1) {
22784     needOppositeCond = !needOppositeCond;
22785     checkAgainstTrue = true;
22786   } else if (C->getZExtValue() != 0)
22787     // Quit if the constant is neither 0 or 1.
22788     return SDValue();
22789
22790   bool truncatedToBoolWithAnd = false;
22791   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22792   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22793          SetCC.getOpcode() == ISD::TRUNCATE ||
22794          SetCC.getOpcode() == ISD::AND) {
22795     if (SetCC.getOpcode() == ISD::AND) {
22796       int OpIdx = -1;
22797       ConstantSDNode *CS;
22798       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22799           CS->getZExtValue() == 1)
22800         OpIdx = 1;
22801       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22802           CS->getZExtValue() == 1)
22803         OpIdx = 0;
22804       if (OpIdx == -1)
22805         break;
22806       SetCC = SetCC.getOperand(OpIdx);
22807       truncatedToBoolWithAnd = true;
22808     } else
22809       SetCC = SetCC.getOperand(0);
22810   }
22811
22812   switch (SetCC.getOpcode()) {
22813   case X86ISD::SETCC_CARRY:
22814     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22815     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22816     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22817     // truncated to i1 using 'and'.
22818     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22819       break;
22820     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22821            "Invalid use of SETCC_CARRY!");
22822     // FALL THROUGH
22823   case X86ISD::SETCC:
22824     // Set the condition code or opposite one if necessary.
22825     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22826     if (needOppositeCond)
22827       CC = X86::GetOppositeBranchCondition(CC);
22828     return SetCC.getOperand(1);
22829   case X86ISD::CMOV: {
22830     // Check whether false/true value has canonical one, i.e. 0 or 1.
22831     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22832     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22833     // Quit if true value is not a constant.
22834     if (!TVal)
22835       return SDValue();
22836     // Quit if false value is not a constant.
22837     if (!FVal) {
22838       SDValue Op = SetCC.getOperand(0);
22839       // Skip 'zext' or 'trunc' node.
22840       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22841           Op.getOpcode() == ISD::TRUNCATE)
22842         Op = Op.getOperand(0);
22843       // A special case for rdrand/rdseed, where 0 is set if false cond is
22844       // found.
22845       if ((Op.getOpcode() != X86ISD::RDRAND &&
22846            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22847         return SDValue();
22848     }
22849     // Quit if false value is not the constant 0 or 1.
22850     bool FValIsFalse = true;
22851     if (FVal && FVal->getZExtValue() != 0) {
22852       if (FVal->getZExtValue() != 1)
22853         return SDValue();
22854       // If FVal is 1, opposite cond is needed.
22855       needOppositeCond = !needOppositeCond;
22856       FValIsFalse = false;
22857     }
22858     // Quit if TVal is not the constant opposite of FVal.
22859     if (FValIsFalse && TVal->getZExtValue() != 1)
22860       return SDValue();
22861     if (!FValIsFalse && TVal->getZExtValue() != 0)
22862       return SDValue();
22863     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22864     if (needOppositeCond)
22865       CC = X86::GetOppositeBranchCondition(CC);
22866     return SetCC.getOperand(3);
22867   }
22868   }
22869
22870   return SDValue();
22871 }
22872
22873 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22874 /// Match:
22875 ///   (X86or (X86setcc) (X86setcc))
22876 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22877 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22878                                            X86::CondCode &CC1, SDValue &Flags,
22879                                            bool &isAnd) {
22880   if (Cond->getOpcode() == X86ISD::CMP) {
22881     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22882     if (!CondOp1C || !CondOp1C->isNullValue())
22883       return false;
22884
22885     Cond = Cond->getOperand(0);
22886   }
22887
22888   isAnd = false;
22889
22890   SDValue SetCC0, SetCC1;
22891   switch (Cond->getOpcode()) {
22892   default: return false;
22893   case ISD::AND:
22894   case X86ISD::AND:
22895     isAnd = true;
22896     // fallthru
22897   case ISD::OR:
22898   case X86ISD::OR:
22899     SetCC0 = Cond->getOperand(0);
22900     SetCC1 = Cond->getOperand(1);
22901     break;
22902   };
22903
22904   // Make sure we have SETCC nodes, using the same flags value.
22905   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22906       SetCC1.getOpcode() != X86ISD::SETCC ||
22907       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22908     return false;
22909
22910   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22911   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22912   Flags = SetCC0->getOperand(1);
22913   return true;
22914 }
22915
22916 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22917 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22918                                   TargetLowering::DAGCombinerInfo &DCI,
22919                                   const X86Subtarget *Subtarget) {
22920   SDLoc DL(N);
22921
22922   // If the flag operand isn't dead, don't touch this CMOV.
22923   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22924     return SDValue();
22925
22926   SDValue FalseOp = N->getOperand(0);
22927   SDValue TrueOp = N->getOperand(1);
22928   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22929   SDValue Cond = N->getOperand(3);
22930
22931   if (CC == X86::COND_E || CC == X86::COND_NE) {
22932     switch (Cond.getOpcode()) {
22933     default: break;
22934     case X86ISD::BSR:
22935     case X86ISD::BSF:
22936       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22937       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22938         return (CC == X86::COND_E) ? FalseOp : TrueOp;
22939     }
22940   }
22941
22942   SDValue Flags;
22943
22944   Flags = checkBoolTestSetCCCombine(Cond, CC);
22945   if (Flags.getNode() &&
22946       // Extra check as FCMOV only supports a subset of X86 cond.
22947       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22948     SDValue Ops[] = { FalseOp, TrueOp,
22949                       DAG.getConstant(CC, DL, MVT::i8), Flags };
22950     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22951   }
22952
22953   // If this is a select between two integer constants, try to do some
22954   // optimizations.  Note that the operands are ordered the opposite of SELECT
22955   // operands.
22956   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22957     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22958       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22959       // larger than FalseC (the false value).
22960       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22961         CC = X86::GetOppositeBranchCondition(CC);
22962         std::swap(TrueC, FalseC);
22963         std::swap(TrueOp, FalseOp);
22964       }
22965
22966       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22967       // This is efficient for any integer data type (including i8/i16) and
22968       // shift amount.
22969       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22970         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22971                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22972
22973         // Zero extend the condition if needed.
22974         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22975
22976         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22977         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22978                            DAG.getConstant(ShAmt, DL, MVT::i8));
22979         if (N->getNumValues() == 2)  // Dead flag value?
22980           return DCI.CombineTo(N, Cond, SDValue());
22981         return Cond;
22982       }
22983
22984       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22985       // for any integer data type, including i8/i16.
22986       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22987         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22988                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22989
22990         // Zero extend the condition if needed.
22991         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22992                            FalseC->getValueType(0), Cond);
22993         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22994                            SDValue(FalseC, 0));
22995
22996         if (N->getNumValues() == 2)  // Dead flag value?
22997           return DCI.CombineTo(N, Cond, SDValue());
22998         return Cond;
22999       }
23000
23001       // Optimize cases that will turn into an LEA instruction.  This requires
23002       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23003       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23004         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23005         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23006
23007         bool isFastMultiplier = false;
23008         if (Diff < 10) {
23009           switch ((unsigned char)Diff) {
23010           default: break;
23011           case 1:  // result = add base, cond
23012           case 2:  // result = lea base(    , cond*2)
23013           case 3:  // result = lea base(cond, cond*2)
23014           case 4:  // result = lea base(    , cond*4)
23015           case 5:  // result = lea base(cond, cond*4)
23016           case 8:  // result = lea base(    , cond*8)
23017           case 9:  // result = lea base(cond, cond*8)
23018             isFastMultiplier = true;
23019             break;
23020           }
23021         }
23022
23023         if (isFastMultiplier) {
23024           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23025           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23026                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23027           // Zero extend the condition if needed.
23028           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23029                              Cond);
23030           // Scale the condition by the difference.
23031           if (Diff != 1)
23032             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23033                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23034
23035           // Add the base if non-zero.
23036           if (FalseC->getAPIntValue() != 0)
23037             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23038                                SDValue(FalseC, 0));
23039           if (N->getNumValues() == 2)  // Dead flag value?
23040             return DCI.CombineTo(N, Cond, SDValue());
23041           return Cond;
23042         }
23043       }
23044     }
23045   }
23046
23047   // Handle these cases:
23048   //   (select (x != c), e, c) -> select (x != c), e, x),
23049   //   (select (x == c), c, e) -> select (x == c), x, e)
23050   // where the c is an integer constant, and the "select" is the combination
23051   // of CMOV and CMP.
23052   //
23053   // The rationale for this change is that the conditional-move from a constant
23054   // needs two instructions, however, conditional-move from a register needs
23055   // only one instruction.
23056   //
23057   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23058   //  some instruction-combining opportunities. This opt needs to be
23059   //  postponed as late as possible.
23060   //
23061   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23062     // the DCI.xxxx conditions are provided to postpone the optimization as
23063     // late as possible.
23064
23065     ConstantSDNode *CmpAgainst = nullptr;
23066     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23067         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23068         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23069
23070       if (CC == X86::COND_NE &&
23071           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23072         CC = X86::GetOppositeBranchCondition(CC);
23073         std::swap(TrueOp, FalseOp);
23074       }
23075
23076       if (CC == X86::COND_E &&
23077           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23078         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23079                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23080         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23081       }
23082     }
23083   }
23084
23085   // Fold and/or of setcc's to double CMOV:
23086   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23087   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23088   //
23089   // This combine lets us generate:
23090   //   cmovcc1 (jcc1 if we don't have CMOV)
23091   //   cmovcc2 (same)
23092   // instead of:
23093   //   setcc1
23094   //   setcc2
23095   //   and/or
23096   //   cmovne (jne if we don't have CMOV)
23097   // When we can't use the CMOV instruction, it might increase branch
23098   // mispredicts.
23099   // When we can use CMOV, or when there is no mispredict, this improves
23100   // throughput and reduces register pressure.
23101   //
23102   if (CC == X86::COND_NE) {
23103     SDValue Flags;
23104     X86::CondCode CC0, CC1;
23105     bool isAndSetCC;
23106     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23107       if (isAndSetCC) {
23108         std::swap(FalseOp, TrueOp);
23109         CC0 = X86::GetOppositeBranchCondition(CC0);
23110         CC1 = X86::GetOppositeBranchCondition(CC1);
23111       }
23112
23113       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23114         Flags};
23115       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23116       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23117       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23118       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23119       return CMOV;
23120     }
23121   }
23122
23123   return SDValue();
23124 }
23125
23126 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23127                                                 const X86Subtarget *Subtarget) {
23128   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23129   switch (IntNo) {
23130   default: return SDValue();
23131   // SSE/AVX/AVX2 blend intrinsics.
23132   case Intrinsic::x86_avx2_pblendvb:
23133     // Don't try to simplify this intrinsic if we don't have AVX2.
23134     if (!Subtarget->hasAVX2())
23135       return SDValue();
23136     // FALL-THROUGH
23137   case Intrinsic::x86_avx_blendv_pd_256:
23138   case Intrinsic::x86_avx_blendv_ps_256:
23139     // Don't try to simplify this intrinsic if we don't have AVX.
23140     if (!Subtarget->hasAVX())
23141       return SDValue();
23142     // FALL-THROUGH
23143   case Intrinsic::x86_sse41_blendvps:
23144   case Intrinsic::x86_sse41_blendvpd:
23145   case Intrinsic::x86_sse41_pblendvb: {
23146     SDValue Op0 = N->getOperand(1);
23147     SDValue Op1 = N->getOperand(2);
23148     SDValue Mask = N->getOperand(3);
23149
23150     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23151     if (!Subtarget->hasSSE41())
23152       return SDValue();
23153
23154     // fold (blend A, A, Mask) -> A
23155     if (Op0 == Op1)
23156       return Op0;
23157     // fold (blend A, B, allZeros) -> A
23158     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23159       return Op0;
23160     // fold (blend A, B, allOnes) -> B
23161     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23162       return Op1;
23163
23164     // Simplify the case where the mask is a constant i32 value.
23165     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23166       if (C->isNullValue())
23167         return Op0;
23168       if (C->isAllOnesValue())
23169         return Op1;
23170     }
23171
23172     return SDValue();
23173   }
23174
23175   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23176   case Intrinsic::x86_sse2_psrai_w:
23177   case Intrinsic::x86_sse2_psrai_d:
23178   case Intrinsic::x86_avx2_psrai_w:
23179   case Intrinsic::x86_avx2_psrai_d:
23180   case Intrinsic::x86_sse2_psra_w:
23181   case Intrinsic::x86_sse2_psra_d:
23182   case Intrinsic::x86_avx2_psra_w:
23183   case Intrinsic::x86_avx2_psra_d: {
23184     SDValue Op0 = N->getOperand(1);
23185     SDValue Op1 = N->getOperand(2);
23186     EVT VT = Op0.getValueType();
23187     assert(VT.isVector() && "Expected a vector type!");
23188
23189     if (isa<BuildVectorSDNode>(Op1))
23190       Op1 = Op1.getOperand(0);
23191
23192     if (!isa<ConstantSDNode>(Op1))
23193       return SDValue();
23194
23195     EVT SVT = VT.getVectorElementType();
23196     unsigned SVTBits = SVT.getSizeInBits();
23197
23198     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23199     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23200     uint64_t ShAmt = C.getZExtValue();
23201
23202     // Don't try to convert this shift into a ISD::SRA if the shift
23203     // count is bigger than or equal to the element size.
23204     if (ShAmt >= SVTBits)
23205       return SDValue();
23206
23207     // Trivial case: if the shift count is zero, then fold this
23208     // into the first operand.
23209     if (ShAmt == 0)
23210       return Op0;
23211
23212     // Replace this packed shift intrinsic with a target independent
23213     // shift dag node.
23214     SDLoc DL(N);
23215     SDValue Splat = DAG.getConstant(C, DL, VT);
23216     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23217   }
23218   }
23219 }
23220
23221 /// PerformMulCombine - Optimize a single multiply with constant into two
23222 /// in order to implement it with two cheaper instructions, e.g.
23223 /// LEA + SHL, LEA + LEA.
23224 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23225                                  TargetLowering::DAGCombinerInfo &DCI) {
23226   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23227     return SDValue();
23228
23229   EVT VT = N->getValueType(0);
23230   if (VT != MVT::i64 && VT != MVT::i32)
23231     return SDValue();
23232
23233   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23234   if (!C)
23235     return SDValue();
23236   uint64_t MulAmt = C->getZExtValue();
23237   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23238     return SDValue();
23239
23240   uint64_t MulAmt1 = 0;
23241   uint64_t MulAmt2 = 0;
23242   if ((MulAmt % 9) == 0) {
23243     MulAmt1 = 9;
23244     MulAmt2 = MulAmt / 9;
23245   } else if ((MulAmt % 5) == 0) {
23246     MulAmt1 = 5;
23247     MulAmt2 = MulAmt / 5;
23248   } else if ((MulAmt % 3) == 0) {
23249     MulAmt1 = 3;
23250     MulAmt2 = MulAmt / 3;
23251   }
23252   if (MulAmt2 &&
23253       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23254     SDLoc DL(N);
23255
23256     if (isPowerOf2_64(MulAmt2) &&
23257         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23258       // If second multiplifer is pow2, issue it first. We want the multiply by
23259       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23260       // is an add.
23261       std::swap(MulAmt1, MulAmt2);
23262
23263     SDValue NewMul;
23264     if (isPowerOf2_64(MulAmt1))
23265       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23266                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23267     else
23268       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23269                            DAG.getConstant(MulAmt1, DL, VT));
23270
23271     if (isPowerOf2_64(MulAmt2))
23272       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23273                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23274     else
23275       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23276                            DAG.getConstant(MulAmt2, DL, VT));
23277
23278     // Do not add new nodes to DAG combiner worklist.
23279     DCI.CombineTo(N, NewMul, false);
23280   }
23281   return SDValue();
23282 }
23283
23284 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23285   SDValue N0 = N->getOperand(0);
23286   SDValue N1 = N->getOperand(1);
23287   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23288   EVT VT = N0.getValueType();
23289
23290   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23291   // since the result of setcc_c is all zero's or all ones.
23292   if (VT.isInteger() && !VT.isVector() &&
23293       N1C && N0.getOpcode() == ISD::AND &&
23294       N0.getOperand(1).getOpcode() == ISD::Constant) {
23295     SDValue N00 = N0.getOperand(0);
23296     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23297         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23298           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23299          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23300       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23301       APInt ShAmt = N1C->getAPIntValue();
23302       Mask = Mask.shl(ShAmt);
23303       if (Mask != 0) {
23304         SDLoc DL(N);
23305         return DAG.getNode(ISD::AND, DL, VT,
23306                            N00, DAG.getConstant(Mask, DL, VT));
23307       }
23308     }
23309   }
23310
23311   // Hardware support for vector shifts is sparse which makes us scalarize the
23312   // vector operations in many cases. Also, on sandybridge ADD is faster than
23313   // shl.
23314   // (shl V, 1) -> add V,V
23315   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23316     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23317       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23318       // We shift all of the values by one. In many cases we do not have
23319       // hardware support for this operation. This is better expressed as an ADD
23320       // of two values.
23321       if (N1SplatC->getAPIntValue() == 1)
23322         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23323     }
23324
23325   return SDValue();
23326 }
23327
23328 /// \brief Returns a vector of 0s if the node in input is a vector logical
23329 /// shift by a constant amount which is known to be bigger than or equal
23330 /// to the vector element size in bits.
23331 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23332                                       const X86Subtarget *Subtarget) {
23333   EVT VT = N->getValueType(0);
23334
23335   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23336       (!Subtarget->hasInt256() ||
23337        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23338     return SDValue();
23339
23340   SDValue Amt = N->getOperand(1);
23341   SDLoc DL(N);
23342   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23343     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23344       APInt ShiftAmt = AmtSplat->getAPIntValue();
23345       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23346
23347       // SSE2/AVX2 logical shifts always return a vector of 0s
23348       // if the shift amount is bigger than or equal to
23349       // the element size. The constant shift amount will be
23350       // encoded as a 8-bit immediate.
23351       if (ShiftAmt.trunc(8).uge(MaxAmount))
23352         return getZeroVector(VT, Subtarget, DAG, DL);
23353     }
23354
23355   return SDValue();
23356 }
23357
23358 /// PerformShiftCombine - Combine shifts.
23359 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23360                                    TargetLowering::DAGCombinerInfo &DCI,
23361                                    const X86Subtarget *Subtarget) {
23362   if (N->getOpcode() == ISD::SHL)
23363     if (SDValue V = PerformSHLCombine(N, DAG))
23364       return V;
23365
23366   // Try to fold this logical shift into a zero vector.
23367   if (N->getOpcode() != ISD::SRA)
23368     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23369       return V;
23370
23371   return SDValue();
23372 }
23373
23374 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23375 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23376 // and friends.  Likewise for OR -> CMPNEQSS.
23377 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23378                             TargetLowering::DAGCombinerInfo &DCI,
23379                             const X86Subtarget *Subtarget) {
23380   unsigned opcode;
23381
23382   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23383   // we're requiring SSE2 for both.
23384   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23385     SDValue N0 = N->getOperand(0);
23386     SDValue N1 = N->getOperand(1);
23387     SDValue CMP0 = N0->getOperand(1);
23388     SDValue CMP1 = N1->getOperand(1);
23389     SDLoc DL(N);
23390
23391     // The SETCCs should both refer to the same CMP.
23392     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23393       return SDValue();
23394
23395     SDValue CMP00 = CMP0->getOperand(0);
23396     SDValue CMP01 = CMP0->getOperand(1);
23397     EVT     VT    = CMP00.getValueType();
23398
23399     if (VT == MVT::f32 || VT == MVT::f64) {
23400       bool ExpectingFlags = false;
23401       // Check for any users that want flags:
23402       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23403            !ExpectingFlags && UI != UE; ++UI)
23404         switch (UI->getOpcode()) {
23405         default:
23406         case ISD::BR_CC:
23407         case ISD::BRCOND:
23408         case ISD::SELECT:
23409           ExpectingFlags = true;
23410           break;
23411         case ISD::CopyToReg:
23412         case ISD::SIGN_EXTEND:
23413         case ISD::ZERO_EXTEND:
23414         case ISD::ANY_EXTEND:
23415           break;
23416         }
23417
23418       if (!ExpectingFlags) {
23419         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23420         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23421
23422         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23423           X86::CondCode tmp = cc0;
23424           cc0 = cc1;
23425           cc1 = tmp;
23426         }
23427
23428         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23429             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23430           // FIXME: need symbolic constants for these magic numbers.
23431           // See X86ATTInstPrinter.cpp:printSSECC().
23432           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23433           if (Subtarget->hasAVX512()) {
23434             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23435                                          CMP01,
23436                                          DAG.getConstant(x86cc, DL, MVT::i8));
23437             if (N->getValueType(0) != MVT::i1)
23438               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23439                                  FSetCC);
23440             return FSetCC;
23441           }
23442           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23443                                               CMP00.getValueType(), CMP00, CMP01,
23444                                               DAG.getConstant(x86cc, DL,
23445                                                               MVT::i8));
23446
23447           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23448           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23449
23450           if (is64BitFP && !Subtarget->is64Bit()) {
23451             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23452             // 64-bit integer, since that's not a legal type. Since
23453             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23454             // bits, but can do this little dance to extract the lowest 32 bits
23455             // and work with those going forward.
23456             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23457                                            OnesOrZeroesF);
23458             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23459             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23460                                         Vector32, DAG.getIntPtrConstant(0, DL));
23461             IntVT = MVT::i32;
23462           }
23463
23464           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23465           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23466                                       DAG.getConstant(1, DL, IntVT));
23467           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23468                                               ANDed);
23469           return OneBitOfTruth;
23470         }
23471       }
23472     }
23473   }
23474   return SDValue();
23475 }
23476
23477 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23478 /// so it can be folded inside ANDNP.
23479 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23480   EVT VT = N->getValueType(0);
23481
23482   // Match direct AllOnes for 128 and 256-bit vectors
23483   if (ISD::isBuildVectorAllOnes(N))
23484     return true;
23485
23486   // Look through a bit convert.
23487   if (N->getOpcode() == ISD::BITCAST)
23488     N = N->getOperand(0).getNode();
23489
23490   // Sometimes the operand may come from a insert_subvector building a 256-bit
23491   // allones vector
23492   if (VT.is256BitVector() &&
23493       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23494     SDValue V1 = N->getOperand(0);
23495     SDValue V2 = N->getOperand(1);
23496
23497     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23498         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23499         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23500         ISD::isBuildVectorAllOnes(V2.getNode()))
23501       return true;
23502   }
23503
23504   return false;
23505 }
23506
23507 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23508 // register. In most cases we actually compare or select YMM-sized registers
23509 // and mixing the two types creates horrible code. This method optimizes
23510 // some of the transition sequences.
23511 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23512                                  TargetLowering::DAGCombinerInfo &DCI,
23513                                  const X86Subtarget *Subtarget) {
23514   EVT VT = N->getValueType(0);
23515   if (!VT.is256BitVector())
23516     return SDValue();
23517
23518   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23519           N->getOpcode() == ISD::ZERO_EXTEND ||
23520           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23521
23522   SDValue Narrow = N->getOperand(0);
23523   EVT NarrowVT = Narrow->getValueType(0);
23524   if (!NarrowVT.is128BitVector())
23525     return SDValue();
23526
23527   if (Narrow->getOpcode() != ISD::XOR &&
23528       Narrow->getOpcode() != ISD::AND &&
23529       Narrow->getOpcode() != ISD::OR)
23530     return SDValue();
23531
23532   SDValue N0  = Narrow->getOperand(0);
23533   SDValue N1  = Narrow->getOperand(1);
23534   SDLoc DL(Narrow);
23535
23536   // The Left side has to be a trunc.
23537   if (N0.getOpcode() != ISD::TRUNCATE)
23538     return SDValue();
23539
23540   // The type of the truncated inputs.
23541   EVT WideVT = N0->getOperand(0)->getValueType(0);
23542   if (WideVT != VT)
23543     return SDValue();
23544
23545   // The right side has to be a 'trunc' or a constant vector.
23546   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23547   ConstantSDNode *RHSConstSplat = nullptr;
23548   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23549     RHSConstSplat = RHSBV->getConstantSplatNode();
23550   if (!RHSTrunc && !RHSConstSplat)
23551     return SDValue();
23552
23553   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23554
23555   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23556     return SDValue();
23557
23558   // Set N0 and N1 to hold the inputs to the new wide operation.
23559   N0 = N0->getOperand(0);
23560   if (RHSConstSplat) {
23561     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23562                      SDValue(RHSConstSplat, 0));
23563     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23564     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23565   } else if (RHSTrunc) {
23566     N1 = N1->getOperand(0);
23567   }
23568
23569   // Generate the wide operation.
23570   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23571   unsigned Opcode = N->getOpcode();
23572   switch (Opcode) {
23573   case ISD::ANY_EXTEND:
23574     return Op;
23575   case ISD::ZERO_EXTEND: {
23576     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23577     APInt Mask = APInt::getAllOnesValue(InBits);
23578     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23579     return DAG.getNode(ISD::AND, DL, VT,
23580                        Op, DAG.getConstant(Mask, DL, VT));
23581   }
23582   case ISD::SIGN_EXTEND:
23583     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23584                        Op, DAG.getValueType(NarrowVT));
23585   default:
23586     llvm_unreachable("Unexpected opcode");
23587   }
23588 }
23589
23590 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23591                                  TargetLowering::DAGCombinerInfo &DCI,
23592                                  const X86Subtarget *Subtarget) {
23593   SDValue N0 = N->getOperand(0);
23594   SDValue N1 = N->getOperand(1);
23595   SDLoc DL(N);
23596
23597   // A vector zext_in_reg may be represented as a shuffle,
23598   // feeding into a bitcast (this represents anyext) feeding into
23599   // an and with a mask.
23600   // We'd like to try to combine that into a shuffle with zero
23601   // plus a bitcast, removing the and.
23602   if (N0.getOpcode() != ISD::BITCAST ||
23603       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23604     return SDValue();
23605
23606   // The other side of the AND should be a splat of 2^C, where C
23607   // is the number of bits in the source type.
23608   if (N1.getOpcode() == ISD::BITCAST)
23609     N1 = N1.getOperand(0);
23610   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23611     return SDValue();
23612   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23613
23614   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23615   EVT SrcType = Shuffle->getValueType(0);
23616
23617   // We expect a single-source shuffle
23618   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23619     return SDValue();
23620
23621   unsigned SrcSize = SrcType.getScalarSizeInBits();
23622
23623   APInt SplatValue, SplatUndef;
23624   unsigned SplatBitSize;
23625   bool HasAnyUndefs;
23626   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23627                                 SplatBitSize, HasAnyUndefs))
23628     return SDValue();
23629
23630   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23631   // Make sure the splat matches the mask we expect
23632   if (SplatBitSize > ResSize ||
23633       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23634     return SDValue();
23635
23636   // Make sure the input and output size make sense
23637   if (SrcSize >= ResSize || ResSize % SrcSize)
23638     return SDValue();
23639
23640   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23641   // The number of u's between each two values depends on the ratio between
23642   // the source and dest type.
23643   unsigned ZextRatio = ResSize / SrcSize;
23644   bool IsZext = true;
23645   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23646     if (i % ZextRatio) {
23647       if (Shuffle->getMaskElt(i) > 0) {
23648         // Expected undef
23649         IsZext = false;
23650         break;
23651       }
23652     } else {
23653       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23654         // Expected element number
23655         IsZext = false;
23656         break;
23657       }
23658     }
23659   }
23660
23661   if (!IsZext)
23662     return SDValue();
23663
23664   // Ok, perform the transformation - replace the shuffle with
23665   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23666   // (instead of undef) where the k elements come from the zero vector.
23667   SmallVector<int, 8> Mask;
23668   unsigned NumElems = SrcType.getVectorNumElements();
23669   for (unsigned i = 0; i < NumElems; ++i)
23670     if (i % ZextRatio)
23671       Mask.push_back(NumElems);
23672     else
23673       Mask.push_back(i / ZextRatio);
23674
23675   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23676     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23677   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23678 }
23679
23680 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23681                                  TargetLowering::DAGCombinerInfo &DCI,
23682                                  const X86Subtarget *Subtarget) {
23683   if (DCI.isBeforeLegalizeOps())
23684     return SDValue();
23685
23686   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23687     return Zext;
23688
23689   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23690     return R;
23691
23692   EVT VT = N->getValueType(0);
23693   SDValue N0 = N->getOperand(0);
23694   SDValue N1 = N->getOperand(1);
23695   SDLoc DL(N);
23696
23697   // Create BEXTR instructions
23698   // BEXTR is ((X >> imm) & (2**size-1))
23699   if (VT == MVT::i32 || VT == MVT::i64) {
23700     // Check for BEXTR.
23701     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23702         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23703       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23704       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23705       if (MaskNode && ShiftNode) {
23706         uint64_t Mask = MaskNode->getZExtValue();
23707         uint64_t Shift = ShiftNode->getZExtValue();
23708         if (isMask_64(Mask)) {
23709           uint64_t MaskSize = countPopulation(Mask);
23710           if (Shift + MaskSize <= VT.getSizeInBits())
23711             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23712                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23713                                                VT));
23714         }
23715       }
23716     } // BEXTR
23717
23718     return SDValue();
23719   }
23720
23721   // Want to form ANDNP nodes:
23722   // 1) In the hopes of then easily combining them with OR and AND nodes
23723   //    to form PBLEND/PSIGN.
23724   // 2) To match ANDN packed intrinsics
23725   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23726     return SDValue();
23727
23728   // Check LHS for vnot
23729   if (N0.getOpcode() == ISD::XOR &&
23730       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23731       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23732     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23733
23734   // Check RHS for vnot
23735   if (N1.getOpcode() == ISD::XOR &&
23736       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23737       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23738     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23739
23740   return SDValue();
23741 }
23742
23743 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23744                                 TargetLowering::DAGCombinerInfo &DCI,
23745                                 const X86Subtarget *Subtarget) {
23746   if (DCI.isBeforeLegalizeOps())
23747     return SDValue();
23748
23749   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23750     return R;
23751
23752   SDValue N0 = N->getOperand(0);
23753   SDValue N1 = N->getOperand(1);
23754   EVT VT = N->getValueType(0);
23755
23756   // look for psign/blend
23757   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23758     if (!Subtarget->hasSSSE3() ||
23759         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23760       return SDValue();
23761
23762     // Canonicalize pandn to RHS
23763     if (N0.getOpcode() == X86ISD::ANDNP)
23764       std::swap(N0, N1);
23765     // or (and (m, y), (pandn m, x))
23766     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23767       SDValue Mask = N1.getOperand(0);
23768       SDValue X    = N1.getOperand(1);
23769       SDValue Y;
23770       if (N0.getOperand(0) == Mask)
23771         Y = N0.getOperand(1);
23772       if (N0.getOperand(1) == Mask)
23773         Y = N0.getOperand(0);
23774
23775       // Check to see if the mask appeared in both the AND and ANDNP and
23776       if (!Y.getNode())
23777         return SDValue();
23778
23779       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23780       // Look through mask bitcast.
23781       if (Mask.getOpcode() == ISD::BITCAST)
23782         Mask = Mask.getOperand(0);
23783       if (X.getOpcode() == ISD::BITCAST)
23784         X = X.getOperand(0);
23785       if (Y.getOpcode() == ISD::BITCAST)
23786         Y = Y.getOperand(0);
23787
23788       EVT MaskVT = Mask.getValueType();
23789
23790       // Validate that the Mask operand is a vector sra node.
23791       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23792       // there is no psrai.b
23793       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23794       unsigned SraAmt = ~0;
23795       if (Mask.getOpcode() == ISD::SRA) {
23796         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23797           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23798             SraAmt = AmtConst->getZExtValue();
23799       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23800         SDValue SraC = Mask.getOperand(1);
23801         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23802       }
23803       if ((SraAmt + 1) != EltBits)
23804         return SDValue();
23805
23806       SDLoc DL(N);
23807
23808       // Now we know we at least have a plendvb with the mask val.  See if
23809       // we can form a psignb/w/d.
23810       // psign = x.type == y.type == mask.type && y = sub(0, x);
23811       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23812           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23813           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23814         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23815                "Unsupported VT for PSIGN");
23816         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23817         return DAG.getBitcast(VT, Mask);
23818       }
23819       // PBLENDVB only available on SSE 4.1
23820       if (!Subtarget->hasSSE41())
23821         return SDValue();
23822
23823       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23824
23825       X = DAG.getBitcast(BlendVT, X);
23826       Y = DAG.getBitcast(BlendVT, Y);
23827       Mask = DAG.getBitcast(BlendVT, Mask);
23828       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23829       return DAG.getBitcast(VT, Mask);
23830     }
23831   }
23832
23833   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23834     return SDValue();
23835
23836   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23837   MachineFunction &MF = DAG.getMachineFunction();
23838   bool OptForSize =
23839       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23840
23841   // SHLD/SHRD instructions have lower register pressure, but on some
23842   // platforms they have higher latency than the equivalent
23843   // series of shifts/or that would otherwise be generated.
23844   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23845   // have higher latencies and we are not optimizing for size.
23846   if (!OptForSize && Subtarget->isSHLDSlow())
23847     return SDValue();
23848
23849   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23850     std::swap(N0, N1);
23851   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23852     return SDValue();
23853   if (!N0.hasOneUse() || !N1.hasOneUse())
23854     return SDValue();
23855
23856   SDValue ShAmt0 = N0.getOperand(1);
23857   if (ShAmt0.getValueType() != MVT::i8)
23858     return SDValue();
23859   SDValue ShAmt1 = N1.getOperand(1);
23860   if (ShAmt1.getValueType() != MVT::i8)
23861     return SDValue();
23862   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23863     ShAmt0 = ShAmt0.getOperand(0);
23864   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23865     ShAmt1 = ShAmt1.getOperand(0);
23866
23867   SDLoc DL(N);
23868   unsigned Opc = X86ISD::SHLD;
23869   SDValue Op0 = N0.getOperand(0);
23870   SDValue Op1 = N1.getOperand(0);
23871   if (ShAmt0.getOpcode() == ISD::SUB) {
23872     Opc = X86ISD::SHRD;
23873     std::swap(Op0, Op1);
23874     std::swap(ShAmt0, ShAmt1);
23875   }
23876
23877   unsigned Bits = VT.getSizeInBits();
23878   if (ShAmt1.getOpcode() == ISD::SUB) {
23879     SDValue Sum = ShAmt1.getOperand(0);
23880     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23881       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23882       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23883         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23884       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23885         return DAG.getNode(Opc, DL, VT,
23886                            Op0, Op1,
23887                            DAG.getNode(ISD::TRUNCATE, DL,
23888                                        MVT::i8, ShAmt0));
23889     }
23890   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23891     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23892     if (ShAmt0C &&
23893         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23894       return DAG.getNode(Opc, DL, VT,
23895                          N0.getOperand(0), N1.getOperand(0),
23896                          DAG.getNode(ISD::TRUNCATE, DL,
23897                                        MVT::i8, ShAmt0));
23898   }
23899
23900   return SDValue();
23901 }
23902
23903 // Generate NEG and CMOV for integer abs.
23904 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23905   EVT VT = N->getValueType(0);
23906
23907   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23908   // 8-bit integer abs to NEG and CMOV.
23909   if (VT.isInteger() && VT.getSizeInBits() == 8)
23910     return SDValue();
23911
23912   SDValue N0 = N->getOperand(0);
23913   SDValue N1 = N->getOperand(1);
23914   SDLoc DL(N);
23915
23916   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23917   // and change it to SUB and CMOV.
23918   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23919       N0.getOpcode() == ISD::ADD &&
23920       N0.getOperand(1) == N1 &&
23921       N1.getOpcode() == ISD::SRA &&
23922       N1.getOperand(0) == N0.getOperand(0))
23923     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23924       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23925         // Generate SUB & CMOV.
23926         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23927                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
23928
23929         SDValue Ops[] = { N0.getOperand(0), Neg,
23930                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23931                           SDValue(Neg.getNode(), 1) };
23932         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23933       }
23934   return SDValue();
23935 }
23936
23937 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23938 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23939                                  TargetLowering::DAGCombinerInfo &DCI,
23940                                  const X86Subtarget *Subtarget) {
23941   if (DCI.isBeforeLegalizeOps())
23942     return SDValue();
23943
23944   if (Subtarget->hasCMov())
23945     if (SDValue RV = performIntegerAbsCombine(N, DAG))
23946       return RV;
23947
23948   return SDValue();
23949 }
23950
23951 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23952 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23953                                   TargetLowering::DAGCombinerInfo &DCI,
23954                                   const X86Subtarget *Subtarget) {
23955   LoadSDNode *Ld = cast<LoadSDNode>(N);
23956   EVT RegVT = Ld->getValueType(0);
23957   EVT MemVT = Ld->getMemoryVT();
23958   SDLoc dl(Ld);
23959   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23960
23961   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23962   // into two 16-byte operations.
23963   ISD::LoadExtType Ext = Ld->getExtensionType();
23964   unsigned Alignment = Ld->getAlignment();
23965   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23966   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23967       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23968     unsigned NumElems = RegVT.getVectorNumElements();
23969     if (NumElems < 2)
23970       return SDValue();
23971
23972     SDValue Ptr = Ld->getBasePtr();
23973     SDValue Increment =
23974         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
23975
23976     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23977                                   NumElems/2);
23978     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23979                                 Ld->getPointerInfo(), Ld->isVolatile(),
23980                                 Ld->isNonTemporal(), Ld->isInvariant(),
23981                                 Alignment);
23982     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23983     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23984                                 Ld->getPointerInfo(), Ld->isVolatile(),
23985                                 Ld->isNonTemporal(), Ld->isInvariant(),
23986                                 std::min(16U, Alignment));
23987     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23988                              Load1.getValue(1),
23989                              Load2.getValue(1));
23990
23991     SDValue NewVec = DAG.getUNDEF(RegVT);
23992     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23993     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23994     return DCI.CombineTo(N, NewVec, TF, true);
23995   }
23996
23997   return SDValue();
23998 }
23999
24000 /// PerformMLOADCombine - Resolve extending loads
24001 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24002                                    TargetLowering::DAGCombinerInfo &DCI,
24003                                    const X86Subtarget *Subtarget) {
24004   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24005   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24006     return SDValue();
24007
24008   EVT VT = Mld->getValueType(0);
24009   unsigned NumElems = VT.getVectorNumElements();
24010   EVT LdVT = Mld->getMemoryVT();
24011   SDLoc dl(Mld);
24012
24013   assert(LdVT != VT && "Cannot extend to the same type");
24014   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24015   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24016   // From, To sizes and ElemCount must be pow of two
24017   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24018     "Unexpected size for extending masked load");
24019
24020   unsigned SizeRatio  = ToSz / FromSz;
24021   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24022
24023   // Create a type on which we perform the shuffle
24024   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24025           LdVT.getScalarType(), NumElems*SizeRatio);
24026   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24027
24028   // Convert Src0 value
24029   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24030   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24031     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24032     for (unsigned i = 0; i != NumElems; ++i)
24033       ShuffleVec[i] = i * SizeRatio;
24034
24035     // Can't shuffle using an illegal type.
24036     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24037             && "WideVecVT should be legal");
24038     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24039                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24040   }
24041   // Prepare the new mask
24042   SDValue NewMask;
24043   SDValue Mask = Mld->getMask();
24044   if (Mask.getValueType() == VT) {
24045     // Mask and original value have the same type
24046     NewMask = DAG.getBitcast(WideVecVT, Mask);
24047     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24048     for (unsigned i = 0; i != NumElems; ++i)
24049       ShuffleVec[i] = i * SizeRatio;
24050     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24051       ShuffleVec[i] = NumElems*SizeRatio;
24052     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24053                                    DAG.getConstant(0, dl, WideVecVT),
24054                                    &ShuffleVec[0]);
24055   }
24056   else {
24057     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24058     unsigned WidenNumElts = NumElems*SizeRatio;
24059     unsigned MaskNumElts = VT.getVectorNumElements();
24060     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24061                                      WidenNumElts);
24062
24063     unsigned NumConcat = WidenNumElts / MaskNumElts;
24064     SmallVector<SDValue, 16> Ops(NumConcat);
24065     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24066     Ops[0] = Mask;
24067     for (unsigned i = 1; i != NumConcat; ++i)
24068       Ops[i] = ZeroVal;
24069
24070     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24071   }
24072
24073   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24074                                      Mld->getBasePtr(), NewMask, WideSrc0,
24075                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24076                                      ISD::NON_EXTLOAD);
24077   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24078   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24079
24080 }
24081 /// PerformMSTORECombine - Resolve truncating stores
24082 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24083                                     const X86Subtarget *Subtarget) {
24084   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24085   if (!Mst->isTruncatingStore())
24086     return SDValue();
24087
24088   EVT VT = Mst->getValue().getValueType();
24089   unsigned NumElems = VT.getVectorNumElements();
24090   EVT StVT = Mst->getMemoryVT();
24091   SDLoc dl(Mst);
24092
24093   assert(StVT != VT && "Cannot truncate to the same type");
24094   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24095   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24096
24097   // From, To sizes and ElemCount must be pow of two
24098   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24099     "Unexpected size for truncating masked store");
24100   // We are going to use the original vector elt for storing.
24101   // Accumulated smaller vector elements must be a multiple of the store size.
24102   assert (((NumElems * FromSz) % ToSz) == 0 &&
24103           "Unexpected ratio for truncating masked store");
24104
24105   unsigned SizeRatio  = FromSz / ToSz;
24106   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24107
24108   // Create a type on which we perform the shuffle
24109   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24110           StVT.getScalarType(), NumElems*SizeRatio);
24111
24112   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24113
24114   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24115   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24116   for (unsigned i = 0; i != NumElems; ++i)
24117     ShuffleVec[i] = i * SizeRatio;
24118
24119   // Can't shuffle using an illegal type.
24120   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24121           && "WideVecVT should be legal");
24122
24123   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24124                                         DAG.getUNDEF(WideVecVT),
24125                                         &ShuffleVec[0]);
24126
24127   SDValue NewMask;
24128   SDValue Mask = Mst->getMask();
24129   if (Mask.getValueType() == VT) {
24130     // Mask and original value have the same type
24131     NewMask = DAG.getBitcast(WideVecVT, Mask);
24132     for (unsigned i = 0; i != NumElems; ++i)
24133       ShuffleVec[i] = i * SizeRatio;
24134     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24135       ShuffleVec[i] = NumElems*SizeRatio;
24136     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24137                                    DAG.getConstant(0, dl, WideVecVT),
24138                                    &ShuffleVec[0]);
24139   }
24140   else {
24141     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24142     unsigned WidenNumElts = NumElems*SizeRatio;
24143     unsigned MaskNumElts = VT.getVectorNumElements();
24144     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24145                                      WidenNumElts);
24146
24147     unsigned NumConcat = WidenNumElts / MaskNumElts;
24148     SmallVector<SDValue, 16> Ops(NumConcat);
24149     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24150     Ops[0] = Mask;
24151     for (unsigned i = 1; i != NumConcat; ++i)
24152       Ops[i] = ZeroVal;
24153
24154     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24155   }
24156
24157   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24158                             NewMask, StVT, Mst->getMemOperand(), false);
24159 }
24160 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24161 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24162                                    const X86Subtarget *Subtarget) {
24163   StoreSDNode *St = cast<StoreSDNode>(N);
24164   EVT VT = St->getValue().getValueType();
24165   EVT StVT = St->getMemoryVT();
24166   SDLoc dl(St);
24167   SDValue StoredVal = St->getOperand(1);
24168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24169
24170   // If we are saving a concatenation of two XMM registers and 32-byte stores
24171   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24172   unsigned Alignment = St->getAlignment();
24173   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24174   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24175       StVT == VT && !IsAligned) {
24176     unsigned NumElems = VT.getVectorNumElements();
24177     if (NumElems < 2)
24178       return SDValue();
24179
24180     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24181     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24182
24183     SDValue Stride =
24184         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24185     SDValue Ptr0 = St->getBasePtr();
24186     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24187
24188     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24189                                 St->getPointerInfo(), St->isVolatile(),
24190                                 St->isNonTemporal(), Alignment);
24191     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24192                                 St->getPointerInfo(), St->isVolatile(),
24193                                 St->isNonTemporal(),
24194                                 std::min(16U, Alignment));
24195     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24196   }
24197
24198   // Optimize trunc store (of multiple scalars) to shuffle and store.
24199   // First, pack all of the elements in one place. Next, store to memory
24200   // in fewer chunks.
24201   if (St->isTruncatingStore() && VT.isVector()) {
24202     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24203     unsigned NumElems = VT.getVectorNumElements();
24204     assert(StVT != VT && "Cannot truncate to the same type");
24205     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24206     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24207
24208     // From, To sizes and ElemCount must be pow of two
24209     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24210     // We are going to use the original vector elt for storing.
24211     // Accumulated smaller vector elements must be a multiple of the store size.
24212     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24213
24214     unsigned SizeRatio  = FromSz / ToSz;
24215
24216     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24217
24218     // Create a type on which we perform the shuffle
24219     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24220             StVT.getScalarType(), NumElems*SizeRatio);
24221
24222     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24223
24224     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24225     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24226     for (unsigned i = 0; i != NumElems; ++i)
24227       ShuffleVec[i] = i * SizeRatio;
24228
24229     // Can't shuffle using an illegal type.
24230     if (!TLI.isTypeLegal(WideVecVT))
24231       return SDValue();
24232
24233     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24234                                          DAG.getUNDEF(WideVecVT),
24235                                          &ShuffleVec[0]);
24236     // At this point all of the data is stored at the bottom of the
24237     // register. We now need to save it to mem.
24238
24239     // Find the largest store unit
24240     MVT StoreType = MVT::i8;
24241     for (MVT Tp : MVT::integer_valuetypes()) {
24242       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24243         StoreType = Tp;
24244     }
24245
24246     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24247     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24248         (64 <= NumElems * ToSz))
24249       StoreType = MVT::f64;
24250
24251     // Bitcast the original vector into a vector of store-size units
24252     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24253             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24254     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24255     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24256     SmallVector<SDValue, 8> Chains;
24257     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24258                                         TLI.getPointerTy(DAG.getDataLayout()));
24259     SDValue Ptr = St->getBasePtr();
24260
24261     // Perform one or more big stores into memory.
24262     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24263       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24264                                    StoreType, ShuffWide,
24265                                    DAG.getIntPtrConstant(i, dl));
24266       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24267                                 St->getPointerInfo(), St->isVolatile(),
24268                                 St->isNonTemporal(), St->getAlignment());
24269       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24270       Chains.push_back(Ch);
24271     }
24272
24273     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24274   }
24275
24276   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24277   // the FP state in cases where an emms may be missing.
24278   // A preferable solution to the general problem is to figure out the right
24279   // places to insert EMMS.  This qualifies as a quick hack.
24280
24281   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24282   if (VT.getSizeInBits() != 64)
24283     return SDValue();
24284
24285   const Function *F = DAG.getMachineFunction().getFunction();
24286   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24287   bool F64IsLegal =
24288       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24289   if ((VT.isVector() ||
24290        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24291       isa<LoadSDNode>(St->getValue()) &&
24292       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24293       St->getChain().hasOneUse() && !St->isVolatile()) {
24294     SDNode* LdVal = St->getValue().getNode();
24295     LoadSDNode *Ld = nullptr;
24296     int TokenFactorIndex = -1;
24297     SmallVector<SDValue, 8> Ops;
24298     SDNode* ChainVal = St->getChain().getNode();
24299     // Must be a store of a load.  We currently handle two cases:  the load
24300     // is a direct child, and it's under an intervening TokenFactor.  It is
24301     // possible to dig deeper under nested TokenFactors.
24302     if (ChainVal == LdVal)
24303       Ld = cast<LoadSDNode>(St->getChain());
24304     else if (St->getValue().hasOneUse() &&
24305              ChainVal->getOpcode() == ISD::TokenFactor) {
24306       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24307         if (ChainVal->getOperand(i).getNode() == LdVal) {
24308           TokenFactorIndex = i;
24309           Ld = cast<LoadSDNode>(St->getValue());
24310         } else
24311           Ops.push_back(ChainVal->getOperand(i));
24312       }
24313     }
24314
24315     if (!Ld || !ISD::isNormalLoad(Ld))
24316       return SDValue();
24317
24318     // If this is not the MMX case, i.e. we are just turning i64 load/store
24319     // into f64 load/store, avoid the transformation if there are multiple
24320     // uses of the loaded value.
24321     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24322       return SDValue();
24323
24324     SDLoc LdDL(Ld);
24325     SDLoc StDL(N);
24326     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24327     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24328     // pair instead.
24329     if (Subtarget->is64Bit() || F64IsLegal) {
24330       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24331       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24332                                   Ld->getPointerInfo(), Ld->isVolatile(),
24333                                   Ld->isNonTemporal(), Ld->isInvariant(),
24334                                   Ld->getAlignment());
24335       SDValue NewChain = NewLd.getValue(1);
24336       if (TokenFactorIndex != -1) {
24337         Ops.push_back(NewChain);
24338         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24339       }
24340       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24341                           St->getPointerInfo(),
24342                           St->isVolatile(), St->isNonTemporal(),
24343                           St->getAlignment());
24344     }
24345
24346     // Otherwise, lower to two pairs of 32-bit loads / stores.
24347     SDValue LoAddr = Ld->getBasePtr();
24348     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24349                                  DAG.getConstant(4, LdDL, MVT::i32));
24350
24351     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24352                                Ld->getPointerInfo(),
24353                                Ld->isVolatile(), Ld->isNonTemporal(),
24354                                Ld->isInvariant(), Ld->getAlignment());
24355     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24356                                Ld->getPointerInfo().getWithOffset(4),
24357                                Ld->isVolatile(), Ld->isNonTemporal(),
24358                                Ld->isInvariant(),
24359                                MinAlign(Ld->getAlignment(), 4));
24360
24361     SDValue NewChain = LoLd.getValue(1);
24362     if (TokenFactorIndex != -1) {
24363       Ops.push_back(LoLd);
24364       Ops.push_back(HiLd);
24365       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24366     }
24367
24368     LoAddr = St->getBasePtr();
24369     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24370                          DAG.getConstant(4, StDL, MVT::i32));
24371
24372     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24373                                 St->getPointerInfo(),
24374                                 St->isVolatile(), St->isNonTemporal(),
24375                                 St->getAlignment());
24376     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24377                                 St->getPointerInfo().getWithOffset(4),
24378                                 St->isVolatile(),
24379                                 St->isNonTemporal(),
24380                                 MinAlign(St->getAlignment(), 4));
24381     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24382   }
24383
24384   // This is similar to the above case, but here we handle a scalar 64-bit
24385   // integer store that is extracted from a vector on a 32-bit target.
24386   // If we have SSE2, then we can treat it like a floating-point double
24387   // to get past legalization. The execution dependencies fixup pass will
24388   // choose the optimal machine instruction for the store if this really is
24389   // an integer or v2f32 rather than an f64.
24390   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24391       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24392     SDValue OldExtract = St->getOperand(1);
24393     SDValue ExtOp0 = OldExtract.getOperand(0);
24394     unsigned VecSize = ExtOp0.getValueSizeInBits();
24395     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24396     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24397     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24398                                      BitCast, OldExtract.getOperand(1));
24399     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24400                         St->getPointerInfo(), St->isVolatile(),
24401                         St->isNonTemporal(), St->getAlignment());
24402   }
24403
24404   return SDValue();
24405 }
24406
24407 /// Return 'true' if this vector operation is "horizontal"
24408 /// and return the operands for the horizontal operation in LHS and RHS.  A
24409 /// horizontal operation performs the binary operation on successive elements
24410 /// of its first operand, then on successive elements of its second operand,
24411 /// returning the resulting values in a vector.  For example, if
24412 ///   A = < float a0, float a1, float a2, float a3 >
24413 /// and
24414 ///   B = < float b0, float b1, float b2, float b3 >
24415 /// then the result of doing a horizontal operation on A and B is
24416 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24417 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24418 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24419 /// set to A, RHS to B, and the routine returns 'true'.
24420 /// Note that the binary operation should have the property that if one of the
24421 /// operands is UNDEF then the result is UNDEF.
24422 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24423   // Look for the following pattern: if
24424   //   A = < float a0, float a1, float a2, float a3 >
24425   //   B = < float b0, float b1, float b2, float b3 >
24426   // and
24427   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24428   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24429   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24430   // which is A horizontal-op B.
24431
24432   // At least one of the operands should be a vector shuffle.
24433   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24434       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24435     return false;
24436
24437   MVT VT = LHS.getSimpleValueType();
24438
24439   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24440          "Unsupported vector type for horizontal add/sub");
24441
24442   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24443   // operate independently on 128-bit lanes.
24444   unsigned NumElts = VT.getVectorNumElements();
24445   unsigned NumLanes = VT.getSizeInBits()/128;
24446   unsigned NumLaneElts = NumElts / NumLanes;
24447   assert((NumLaneElts % 2 == 0) &&
24448          "Vector type should have an even number of elements in each lane");
24449   unsigned HalfLaneElts = NumLaneElts/2;
24450
24451   // View LHS in the form
24452   //   LHS = VECTOR_SHUFFLE A, B, LMask
24453   // If LHS is not a shuffle then pretend it is the shuffle
24454   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24455   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24456   // type VT.
24457   SDValue A, B;
24458   SmallVector<int, 16> LMask(NumElts);
24459   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24460     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24461       A = LHS.getOperand(0);
24462     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24463       B = LHS.getOperand(1);
24464     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24465     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24466   } else {
24467     if (LHS.getOpcode() != ISD::UNDEF)
24468       A = LHS;
24469     for (unsigned i = 0; i != NumElts; ++i)
24470       LMask[i] = i;
24471   }
24472
24473   // Likewise, view RHS in the form
24474   //   RHS = VECTOR_SHUFFLE C, D, RMask
24475   SDValue C, D;
24476   SmallVector<int, 16> RMask(NumElts);
24477   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24478     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24479       C = RHS.getOperand(0);
24480     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24481       D = RHS.getOperand(1);
24482     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24483     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24484   } else {
24485     if (RHS.getOpcode() != ISD::UNDEF)
24486       C = RHS;
24487     for (unsigned i = 0; i != NumElts; ++i)
24488       RMask[i] = i;
24489   }
24490
24491   // Check that the shuffles are both shuffling the same vectors.
24492   if (!(A == C && B == D) && !(A == D && B == C))
24493     return false;
24494
24495   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24496   if (!A.getNode() && !B.getNode())
24497     return false;
24498
24499   // If A and B occur in reverse order in RHS, then "swap" them (which means
24500   // rewriting the mask).
24501   if (A != C)
24502     ShuffleVectorSDNode::commuteMask(RMask);
24503
24504   // At this point LHS and RHS are equivalent to
24505   //   LHS = VECTOR_SHUFFLE A, B, LMask
24506   //   RHS = VECTOR_SHUFFLE A, B, RMask
24507   // Check that the masks correspond to performing a horizontal operation.
24508   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24509     for (unsigned i = 0; i != NumLaneElts; ++i) {
24510       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24511
24512       // Ignore any UNDEF components.
24513       if (LIdx < 0 || RIdx < 0 ||
24514           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24515           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24516         continue;
24517
24518       // Check that successive elements are being operated on.  If not, this is
24519       // not a horizontal operation.
24520       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24521       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24522       if (!(LIdx == Index && RIdx == Index + 1) &&
24523           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24524         return false;
24525     }
24526   }
24527
24528   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24529   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24530   return true;
24531 }
24532
24533 /// Do target-specific dag combines on floating point adds.
24534 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24535                                   const X86Subtarget *Subtarget) {
24536   EVT VT = N->getValueType(0);
24537   SDValue LHS = N->getOperand(0);
24538   SDValue RHS = N->getOperand(1);
24539
24540   // Try to synthesize horizontal adds from adds of shuffles.
24541   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24542        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24543       isHorizontalBinOp(LHS, RHS, true))
24544     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24545   return SDValue();
24546 }
24547
24548 /// Do target-specific dag combines on floating point subs.
24549 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24550                                   const X86Subtarget *Subtarget) {
24551   EVT VT = N->getValueType(0);
24552   SDValue LHS = N->getOperand(0);
24553   SDValue RHS = N->getOperand(1);
24554
24555   // Try to synthesize horizontal subs from subs of shuffles.
24556   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24557        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24558       isHorizontalBinOp(LHS, RHS, false))
24559     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24560   return SDValue();
24561 }
24562
24563 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24564 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24565   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24566
24567   // F[X]OR(0.0, x) -> x
24568   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24569     if (C->getValueAPF().isPosZero())
24570       return N->getOperand(1);
24571
24572   // F[X]OR(x, 0.0) -> x
24573   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24574     if (C->getValueAPF().isPosZero())
24575       return N->getOperand(0);
24576   return SDValue();
24577 }
24578
24579 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24580 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24581   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24582
24583   // Only perform optimizations if UnsafeMath is used.
24584   if (!DAG.getTarget().Options.UnsafeFPMath)
24585     return SDValue();
24586
24587   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24588   // into FMINC and FMAXC, which are Commutative operations.
24589   unsigned NewOp = 0;
24590   switch (N->getOpcode()) {
24591     default: llvm_unreachable("unknown opcode");
24592     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24593     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24594   }
24595
24596   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24597                      N->getOperand(0), N->getOperand(1));
24598 }
24599
24600 /// Do target-specific dag combines on X86ISD::FAND nodes.
24601 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24602   // FAND(0.0, x) -> 0.0
24603   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24604     if (C->getValueAPF().isPosZero())
24605       return N->getOperand(0);
24606
24607   // FAND(x, 0.0) -> 0.0
24608   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24609     if (C->getValueAPF().isPosZero())
24610       return N->getOperand(1);
24611
24612   return SDValue();
24613 }
24614
24615 /// Do target-specific dag combines on X86ISD::FANDN nodes
24616 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24617   // FANDN(0.0, x) -> x
24618   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24619     if (C->getValueAPF().isPosZero())
24620       return N->getOperand(1);
24621
24622   // FANDN(x, 0.0) -> 0.0
24623   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24624     if (C->getValueAPF().isPosZero())
24625       return N->getOperand(1);
24626
24627   return SDValue();
24628 }
24629
24630 static SDValue PerformBTCombine(SDNode *N,
24631                                 SelectionDAG &DAG,
24632                                 TargetLowering::DAGCombinerInfo &DCI) {
24633   // BT ignores high bits in the bit index operand.
24634   SDValue Op1 = N->getOperand(1);
24635   if (Op1.hasOneUse()) {
24636     unsigned BitWidth = Op1.getValueSizeInBits();
24637     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24638     APInt KnownZero, KnownOne;
24639     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24640                                           !DCI.isBeforeLegalizeOps());
24641     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24642     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24643         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24644       DCI.CommitTargetLoweringOpt(TLO);
24645   }
24646   return SDValue();
24647 }
24648
24649 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24650   SDValue Op = N->getOperand(0);
24651   if (Op.getOpcode() == ISD::BITCAST)
24652     Op = Op.getOperand(0);
24653   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24654   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24655       VT.getVectorElementType().getSizeInBits() ==
24656       OpVT.getVectorElementType().getSizeInBits()) {
24657     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24658   }
24659   return SDValue();
24660 }
24661
24662 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24663                                                const X86Subtarget *Subtarget) {
24664   EVT VT = N->getValueType(0);
24665   if (!VT.isVector())
24666     return SDValue();
24667
24668   SDValue N0 = N->getOperand(0);
24669   SDValue N1 = N->getOperand(1);
24670   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24671   SDLoc dl(N);
24672
24673   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24674   // both SSE and AVX2 since there is no sign-extended shift right
24675   // operation on a vector with 64-bit elements.
24676   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24677   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24678   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24679       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24680     SDValue N00 = N0.getOperand(0);
24681
24682     // EXTLOAD has a better solution on AVX2,
24683     // it may be replaced with X86ISD::VSEXT node.
24684     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24685       if (!ISD::isNormalLoad(N00.getNode()))
24686         return SDValue();
24687
24688     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24689         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24690                                   N00, N1);
24691       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24692     }
24693   }
24694   return SDValue();
24695 }
24696
24697 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24698                                   TargetLowering::DAGCombinerInfo &DCI,
24699                                   const X86Subtarget *Subtarget) {
24700   SDValue N0 = N->getOperand(0);
24701   EVT VT = N->getValueType(0);
24702   EVT SVT = VT.getScalarType();
24703   EVT InVT = N0.getValueType();
24704   EVT InSVT = InVT.getScalarType();
24705   SDLoc DL(N);
24706
24707   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24708   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24709   // This exposes the sext to the sdivrem lowering, so that it directly extends
24710   // from AH (which we otherwise need to do contortions to access).
24711   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24712       InVT == MVT::i8 && VT == MVT::i32) {
24713     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24714     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24715                             N0.getOperand(0), N0.getOperand(1));
24716     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24717     return R.getValue(1);
24718   }
24719
24720   if (!DCI.isBeforeLegalizeOps()) {
24721     if (InVT == MVT::i1) {
24722       SDValue Zero = DAG.getConstant(0, DL, VT);
24723       SDValue AllOnes =
24724         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24725       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24726     }
24727     return SDValue();
24728   }
24729
24730   if (VT.isVector() && Subtarget->hasSSE2()) {
24731     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24732       EVT InVT = N.getValueType();
24733       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24734                                    Size / InVT.getScalarSizeInBits());
24735       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24736                                     DAG.getUNDEF(InVT));
24737       Opnds[0] = N;
24738       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24739     };
24740
24741     // If target-size is less than 128-bits, extend to a type that would extend
24742     // to 128 bits, extend that and extract the original target vector.
24743     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24744         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24745         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24746       unsigned Scale = 128 / VT.getSizeInBits();
24747       EVT ExVT =
24748           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24749       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24750       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24751       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24752                          DAG.getIntPtrConstant(0, DL));
24753     }
24754
24755     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24756     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24757     if (VT.getSizeInBits() == 128 &&
24758         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24759         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24760       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24761       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24762     }
24763
24764     // On pre-AVX2 targets, split into 128-bit nodes of
24765     // ISD::SIGN_EXTEND_VECTOR_INREG.
24766     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24767         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24768         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24769       unsigned NumVecs = VT.getSizeInBits() / 128;
24770       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24771       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24772       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24773
24774       SmallVector<SDValue, 8> Opnds;
24775       for (unsigned i = 0, Offset = 0; i != NumVecs;
24776            ++i, Offset += NumSubElts) {
24777         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24778                                      DAG.getIntPtrConstant(Offset, DL));
24779         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24780         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24781         Opnds.push_back(SrcVec);
24782       }
24783       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24784     }
24785   }
24786
24787   if (!Subtarget->hasFp256())
24788     return SDValue();
24789
24790   if (VT.isVector() && VT.getSizeInBits() == 256)
24791     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24792       return R;
24793
24794   return SDValue();
24795 }
24796
24797 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24798                                  const X86Subtarget* Subtarget) {
24799   SDLoc dl(N);
24800   EVT VT = N->getValueType(0);
24801
24802   // Let legalize expand this if it isn't a legal type yet.
24803   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24804     return SDValue();
24805
24806   EVT ScalarVT = VT.getScalarType();
24807   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24808       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24809        !Subtarget->hasAVX512()))
24810     return SDValue();
24811
24812   SDValue A = N->getOperand(0);
24813   SDValue B = N->getOperand(1);
24814   SDValue C = N->getOperand(2);
24815
24816   bool NegA = (A.getOpcode() == ISD::FNEG);
24817   bool NegB = (B.getOpcode() == ISD::FNEG);
24818   bool NegC = (C.getOpcode() == ISD::FNEG);
24819
24820   // Negative multiplication when NegA xor NegB
24821   bool NegMul = (NegA != NegB);
24822   if (NegA)
24823     A = A.getOperand(0);
24824   if (NegB)
24825     B = B.getOperand(0);
24826   if (NegC)
24827     C = C.getOperand(0);
24828
24829   unsigned Opcode;
24830   if (!NegMul)
24831     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24832   else
24833     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24834
24835   return DAG.getNode(Opcode, dl, VT, A, B, C);
24836 }
24837
24838 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24839                                   TargetLowering::DAGCombinerInfo &DCI,
24840                                   const X86Subtarget *Subtarget) {
24841   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24842   //           (and (i32 x86isd::setcc_carry), 1)
24843   // This eliminates the zext. This transformation is necessary because
24844   // ISD::SETCC is always legalized to i8.
24845   SDLoc dl(N);
24846   SDValue N0 = N->getOperand(0);
24847   EVT VT = N->getValueType(0);
24848
24849   if (N0.getOpcode() == ISD::AND &&
24850       N0.hasOneUse() &&
24851       N0.getOperand(0).hasOneUse()) {
24852     SDValue N00 = N0.getOperand(0);
24853     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24854       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24855       if (!C || C->getZExtValue() != 1)
24856         return SDValue();
24857       return DAG.getNode(ISD::AND, dl, VT,
24858                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24859                                      N00.getOperand(0), N00.getOperand(1)),
24860                          DAG.getConstant(1, dl, VT));
24861     }
24862   }
24863
24864   if (N0.getOpcode() == ISD::TRUNCATE &&
24865       N0.hasOneUse() &&
24866       N0.getOperand(0).hasOneUse()) {
24867     SDValue N00 = N0.getOperand(0);
24868     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24869       return DAG.getNode(ISD::AND, dl, VT,
24870                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24871                                      N00.getOperand(0), N00.getOperand(1)),
24872                          DAG.getConstant(1, dl, VT));
24873     }
24874   }
24875
24876   if (VT.is256BitVector())
24877     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24878       return R;
24879
24880   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24881   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24882   // This exposes the zext to the udivrem lowering, so that it directly extends
24883   // from AH (which we otherwise need to do contortions to access).
24884   if (N0.getOpcode() == ISD::UDIVREM &&
24885       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24886       (VT == MVT::i32 || VT == MVT::i64)) {
24887     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24888     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24889                             N0.getOperand(0), N0.getOperand(1));
24890     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24891     return R.getValue(1);
24892   }
24893
24894   return SDValue();
24895 }
24896
24897 // Optimize x == -y --> x+y == 0
24898 //          x != -y --> x+y != 0
24899 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24900                                       const X86Subtarget* Subtarget) {
24901   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24902   SDValue LHS = N->getOperand(0);
24903   SDValue RHS = N->getOperand(1);
24904   EVT VT = N->getValueType(0);
24905   SDLoc DL(N);
24906
24907   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24908     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24909       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24910         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24911                                    LHS.getOperand(1));
24912         return DAG.getSetCC(DL, N->getValueType(0), addV,
24913                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24914       }
24915   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24916     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24917       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24918         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24919                                    RHS.getOperand(1));
24920         return DAG.getSetCC(DL, N->getValueType(0), addV,
24921                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24922       }
24923
24924   if (VT.getScalarType() == MVT::i1 &&
24925       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24926     bool IsSEXT0 =
24927         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24928         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24929     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24930
24931     if (!IsSEXT0 || !IsVZero1) {
24932       // Swap the operands and update the condition code.
24933       std::swap(LHS, RHS);
24934       CC = ISD::getSetCCSwappedOperands(CC);
24935
24936       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24937                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24938       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24939     }
24940
24941     if (IsSEXT0 && IsVZero1) {
24942       assert(VT == LHS.getOperand(0).getValueType() &&
24943              "Uexpected operand type");
24944       if (CC == ISD::SETGT)
24945         return DAG.getConstant(0, DL, VT);
24946       if (CC == ISD::SETLE)
24947         return DAG.getConstant(1, DL, VT);
24948       if (CC == ISD::SETEQ || CC == ISD::SETGE)
24949         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24950
24951       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24952              "Unexpected condition code!");
24953       return LHS.getOperand(0);
24954     }
24955   }
24956
24957   return SDValue();
24958 }
24959
24960 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24961                                          SelectionDAG &DAG) {
24962   SDLoc dl(Load);
24963   MVT VT = Load->getSimpleValueType(0);
24964   MVT EVT = VT.getVectorElementType();
24965   SDValue Addr = Load->getOperand(1);
24966   SDValue NewAddr = DAG.getNode(
24967       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24968       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24969                       Addr.getSimpleValueType()));
24970
24971   SDValue NewLoad =
24972       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24973                   DAG.getMachineFunction().getMachineMemOperand(
24974                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24975   return NewLoad;
24976 }
24977
24978 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24979                                       const X86Subtarget *Subtarget) {
24980   SDLoc dl(N);
24981   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24982   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24983          "X86insertps is only defined for v4x32");
24984
24985   SDValue Ld = N->getOperand(1);
24986   if (MayFoldLoad(Ld)) {
24987     // Extract the countS bits from the immediate so we can get the proper
24988     // address when narrowing the vector load to a specific element.
24989     // When the second source op is a memory address, insertps doesn't use
24990     // countS and just gets an f32 from that address.
24991     unsigned DestIndex =
24992         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24993
24994     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24995
24996     // Create this as a scalar to vector to match the instruction pattern.
24997     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24998     // countS bits are ignored when loading from memory on insertps, which
24999     // means we don't need to explicitly set them to 0.
25000     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25001                        LoadScalarToVector, N->getOperand(2));
25002   }
25003   return SDValue();
25004 }
25005
25006 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25007   SDValue V0 = N->getOperand(0);
25008   SDValue V1 = N->getOperand(1);
25009   SDLoc DL(N);
25010   EVT VT = N->getValueType(0);
25011
25012   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25013   // operands and changing the mask to 1. This saves us a bunch of
25014   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25015   // x86InstrInfo knows how to commute this back after instruction selection
25016   // if it would help register allocation.
25017
25018   // TODO: If optimizing for size or a processor that doesn't suffer from
25019   // partial register update stalls, this should be transformed into a MOVSD
25020   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25021
25022   if (VT == MVT::v2f64)
25023     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25024       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25025         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25026         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25027       }
25028
25029   return SDValue();
25030 }
25031
25032 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25033 // as "sbb reg,reg", since it can be extended without zext and produces
25034 // an all-ones bit which is more useful than 0/1 in some cases.
25035 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25036                                MVT VT) {
25037   if (VT == MVT::i8)
25038     return DAG.getNode(ISD::AND, DL, VT,
25039                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25040                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25041                                    EFLAGS),
25042                        DAG.getConstant(1, DL, VT));
25043   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25044   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25045                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25046                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25047                                  EFLAGS));
25048 }
25049
25050 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25051 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25052                                    TargetLowering::DAGCombinerInfo &DCI,
25053                                    const X86Subtarget *Subtarget) {
25054   SDLoc DL(N);
25055   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25056   SDValue EFLAGS = N->getOperand(1);
25057
25058   if (CC == X86::COND_A) {
25059     // Try to convert COND_A into COND_B in an attempt to facilitate
25060     // materializing "setb reg".
25061     //
25062     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25063     // cannot take an immediate as its first operand.
25064     //
25065     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25066         EFLAGS.getValueType().isInteger() &&
25067         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25068       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25069                                    EFLAGS.getNode()->getVTList(),
25070                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25071       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25072       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25073     }
25074   }
25075
25076   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25077   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25078   // cases.
25079   if (CC == X86::COND_B)
25080     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25081
25082   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25083     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25084     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25085   }
25086
25087   return SDValue();
25088 }
25089
25090 // Optimize branch condition evaluation.
25091 //
25092 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25093                                     TargetLowering::DAGCombinerInfo &DCI,
25094                                     const X86Subtarget *Subtarget) {
25095   SDLoc DL(N);
25096   SDValue Chain = N->getOperand(0);
25097   SDValue Dest = N->getOperand(1);
25098   SDValue EFLAGS = N->getOperand(3);
25099   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25100
25101   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25102     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25103     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25104                        Flags);
25105   }
25106
25107   return SDValue();
25108 }
25109
25110 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25111                                                          SelectionDAG &DAG) {
25112   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25113   // optimize away operation when it's from a constant.
25114   //
25115   // The general transformation is:
25116   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25117   //       AND(VECTOR_CMP(x,y), constant2)
25118   //    constant2 = UNARYOP(constant)
25119
25120   // Early exit if this isn't a vector operation, the operand of the
25121   // unary operation isn't a bitwise AND, or if the sizes of the operations
25122   // aren't the same.
25123   EVT VT = N->getValueType(0);
25124   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25125       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25126       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25127     return SDValue();
25128
25129   // Now check that the other operand of the AND is a constant. We could
25130   // make the transformation for non-constant splats as well, but it's unclear
25131   // that would be a benefit as it would not eliminate any operations, just
25132   // perform one more step in scalar code before moving to the vector unit.
25133   if (BuildVectorSDNode *BV =
25134           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25135     // Bail out if the vector isn't a constant.
25136     if (!BV->isConstant())
25137       return SDValue();
25138
25139     // Everything checks out. Build up the new and improved node.
25140     SDLoc DL(N);
25141     EVT IntVT = BV->getValueType(0);
25142     // Create a new constant of the appropriate type for the transformed
25143     // DAG.
25144     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25145     // The AND node needs bitcasts to/from an integer vector type around it.
25146     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25147     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25148                                  N->getOperand(0)->getOperand(0), MaskConst);
25149     SDValue Res = DAG.getBitcast(VT, NewAnd);
25150     return Res;
25151   }
25152
25153   return SDValue();
25154 }
25155
25156 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25157                                         const X86Subtarget *Subtarget) {
25158   SDValue Op0 = N->getOperand(0);
25159   EVT VT = N->getValueType(0);
25160   EVT InVT = Op0.getValueType();
25161   EVT InSVT = InVT.getScalarType();
25162   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25163
25164   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25165   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25166   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25167     SDLoc dl(N);
25168     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25169                                  InVT.getVectorNumElements());
25170     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25171
25172     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25173       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25174
25175     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25176   }
25177
25178   return SDValue();
25179 }
25180
25181 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25182                                         const X86Subtarget *Subtarget) {
25183   // First try to optimize away the conversion entirely when it's
25184   // conditionally from a constant. Vectors only.
25185   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25186     return Res;
25187
25188   // Now move on to more general possibilities.
25189   SDValue Op0 = N->getOperand(0);
25190   EVT VT = N->getValueType(0);
25191   EVT InVT = Op0.getValueType();
25192   EVT InSVT = InVT.getScalarType();
25193
25194   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25195   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25196   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25197     SDLoc dl(N);
25198     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25199                                  InVT.getVectorNumElements());
25200     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25201     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25202   }
25203
25204   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25205   // a 32-bit target where SSE doesn't support i64->FP operations.
25206   if (Op0.getOpcode() == ISD::LOAD) {
25207     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25208     EVT LdVT = Ld->getValueType(0);
25209
25210     // This transformation is not supported if the result type is f16
25211     if (VT == MVT::f16)
25212       return SDValue();
25213
25214     if (!Ld->isVolatile() && !VT.isVector() &&
25215         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25216         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25217       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25218           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25219       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25220       return FILDChain;
25221     }
25222   }
25223   return SDValue();
25224 }
25225
25226 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25227 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25228                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25229   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25230   // the result is either zero or one (depending on the input carry bit).
25231   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25232   if (X86::isZeroNode(N->getOperand(0)) &&
25233       X86::isZeroNode(N->getOperand(1)) &&
25234       // We don't have a good way to replace an EFLAGS use, so only do this when
25235       // dead right now.
25236       SDValue(N, 1).use_empty()) {
25237     SDLoc DL(N);
25238     EVT VT = N->getValueType(0);
25239     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25240     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25241                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25242                                            DAG.getConstant(X86::COND_B, DL,
25243                                                            MVT::i8),
25244                                            N->getOperand(2)),
25245                                DAG.getConstant(1, DL, VT));
25246     return DCI.CombineTo(N, Res1, CarryOut);
25247   }
25248
25249   return SDValue();
25250 }
25251
25252 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25253 //      (add Y, (setne X, 0)) -> sbb -1, Y
25254 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25255 //      (sub (setne X, 0), Y) -> adc -1, Y
25256 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25257   SDLoc DL(N);
25258
25259   // Look through ZExts.
25260   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25261   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25262     return SDValue();
25263
25264   SDValue SetCC = Ext.getOperand(0);
25265   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25266     return SDValue();
25267
25268   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25269   if (CC != X86::COND_E && CC != X86::COND_NE)
25270     return SDValue();
25271
25272   SDValue Cmp = SetCC.getOperand(1);
25273   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25274       !X86::isZeroNode(Cmp.getOperand(1)) ||
25275       !Cmp.getOperand(0).getValueType().isInteger())
25276     return SDValue();
25277
25278   SDValue CmpOp0 = Cmp.getOperand(0);
25279   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25280                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25281
25282   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25283   if (CC == X86::COND_NE)
25284     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25285                        DL, OtherVal.getValueType(), OtherVal,
25286                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25287                        NewCmp);
25288   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25289                      DL, OtherVal.getValueType(), OtherVal,
25290                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25291 }
25292
25293 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25294 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25295                                  const X86Subtarget *Subtarget) {
25296   EVT VT = N->getValueType(0);
25297   SDValue Op0 = N->getOperand(0);
25298   SDValue Op1 = N->getOperand(1);
25299
25300   // Try to synthesize horizontal adds from adds of shuffles.
25301   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25302        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25303       isHorizontalBinOp(Op0, Op1, true))
25304     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25305
25306   return OptimizeConditionalInDecrement(N, DAG);
25307 }
25308
25309 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25310                                  const X86Subtarget *Subtarget) {
25311   SDValue Op0 = N->getOperand(0);
25312   SDValue Op1 = N->getOperand(1);
25313
25314   // X86 can't encode an immediate LHS of a sub. See if we can push the
25315   // negation into a preceding instruction.
25316   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25317     // If the RHS of the sub is a XOR with one use and a constant, invert the
25318     // immediate. Then add one to the LHS of the sub so we can turn
25319     // X-Y -> X+~Y+1, saving one register.
25320     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25321         isa<ConstantSDNode>(Op1.getOperand(1))) {
25322       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25323       EVT VT = Op0.getValueType();
25324       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25325                                    Op1.getOperand(0),
25326                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25327       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25328                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25329     }
25330   }
25331
25332   // Try to synthesize horizontal adds from adds of shuffles.
25333   EVT VT = N->getValueType(0);
25334   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25335        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25336       isHorizontalBinOp(Op0, Op1, true))
25337     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25338
25339   return OptimizeConditionalInDecrement(N, DAG);
25340 }
25341
25342 /// performVZEXTCombine - Performs build vector combines
25343 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25344                                    TargetLowering::DAGCombinerInfo &DCI,
25345                                    const X86Subtarget *Subtarget) {
25346   SDLoc DL(N);
25347   MVT VT = N->getSimpleValueType(0);
25348   SDValue Op = N->getOperand(0);
25349   MVT OpVT = Op.getSimpleValueType();
25350   MVT OpEltVT = OpVT.getVectorElementType();
25351   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25352
25353   // (vzext (bitcast (vzext (x)) -> (vzext x)
25354   SDValue V = Op;
25355   while (V.getOpcode() == ISD::BITCAST)
25356     V = V.getOperand(0);
25357
25358   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25359     MVT InnerVT = V.getSimpleValueType();
25360     MVT InnerEltVT = InnerVT.getVectorElementType();
25361
25362     // If the element sizes match exactly, we can just do one larger vzext. This
25363     // is always an exact type match as vzext operates on integer types.
25364     if (OpEltVT == InnerEltVT) {
25365       assert(OpVT == InnerVT && "Types must match for vzext!");
25366       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25367     }
25368
25369     // The only other way we can combine them is if only a single element of the
25370     // inner vzext is used in the input to the outer vzext.
25371     if (InnerEltVT.getSizeInBits() < InputBits)
25372       return SDValue();
25373
25374     // In this case, the inner vzext is completely dead because we're going to
25375     // only look at bits inside of the low element. Just do the outer vzext on
25376     // a bitcast of the input to the inner.
25377     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25378   }
25379
25380   // Check if we can bypass extracting and re-inserting an element of an input
25381   // vector. Essentialy:
25382   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25383   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25384       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25385       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25386     SDValue ExtractedV = V.getOperand(0);
25387     SDValue OrigV = ExtractedV.getOperand(0);
25388     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25389       if (ExtractIdx->getZExtValue() == 0) {
25390         MVT OrigVT = OrigV.getSimpleValueType();
25391         // Extract a subvector if necessary...
25392         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25393           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25394           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25395                                     OrigVT.getVectorNumElements() / Ratio);
25396           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25397                               DAG.getIntPtrConstant(0, DL));
25398         }
25399         Op = DAG.getBitcast(OpVT, OrigV);
25400         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25401       }
25402   }
25403
25404   return SDValue();
25405 }
25406
25407 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25408                                              DAGCombinerInfo &DCI) const {
25409   SelectionDAG &DAG = DCI.DAG;
25410   switch (N->getOpcode()) {
25411   default: break;
25412   case ISD::EXTRACT_VECTOR_ELT:
25413     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25414   case ISD::VSELECT:
25415   case ISD::SELECT:
25416   case X86ISD::SHRUNKBLEND:
25417     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25418   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25419   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25420   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25421   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25422   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25423   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25424   case ISD::SHL:
25425   case ISD::SRA:
25426   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25427   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25428   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25429   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25430   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25431   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25432   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25433   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25434   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25435   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25436   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25437   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25438   case X86ISD::FXOR:
25439   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25440   case X86ISD::FMIN:
25441   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25442   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25443   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25444   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25445   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25446   case ISD::ANY_EXTEND:
25447   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25448   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25449   case ISD::SIGN_EXTEND_INREG:
25450     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25451   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25452   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25453   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25454   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25455   case X86ISD::SHUFP:       // Handle all target specific shuffles
25456   case X86ISD::PALIGNR:
25457   case X86ISD::UNPCKH:
25458   case X86ISD::UNPCKL:
25459   case X86ISD::MOVHLPS:
25460   case X86ISD::MOVLHPS:
25461   case X86ISD::PSHUFB:
25462   case X86ISD::PSHUFD:
25463   case X86ISD::PSHUFHW:
25464   case X86ISD::PSHUFLW:
25465   case X86ISD::MOVSS:
25466   case X86ISD::MOVSD:
25467   case X86ISD::VPERMILPI:
25468   case X86ISD::VPERM2X128:
25469   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25470   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25471   case ISD::INTRINSIC_WO_CHAIN:
25472     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25473   case X86ISD::INSERTPS: {
25474     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25475       return PerformINSERTPSCombine(N, DAG, Subtarget);
25476     break;
25477   }
25478   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25479   }
25480
25481   return SDValue();
25482 }
25483
25484 /// isTypeDesirableForOp - Return true if the target has native support for
25485 /// the specified value type and it is 'desirable' to use the type for the
25486 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25487 /// instruction encodings are longer and some i16 instructions are slow.
25488 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25489   if (!isTypeLegal(VT))
25490     return false;
25491   if (VT != MVT::i16)
25492     return true;
25493
25494   switch (Opc) {
25495   default:
25496     return true;
25497   case ISD::LOAD:
25498   case ISD::SIGN_EXTEND:
25499   case ISD::ZERO_EXTEND:
25500   case ISD::ANY_EXTEND:
25501   case ISD::SHL:
25502   case ISD::SRL:
25503   case ISD::SUB:
25504   case ISD::ADD:
25505   case ISD::MUL:
25506   case ISD::AND:
25507   case ISD::OR:
25508   case ISD::XOR:
25509     return false;
25510   }
25511 }
25512
25513 /// IsDesirableToPromoteOp - This method query the target whether it is
25514 /// beneficial for dag combiner to promote the specified node. If true, it
25515 /// should return the desired promotion type by reference.
25516 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25517   EVT VT = Op.getValueType();
25518   if (VT != MVT::i16)
25519     return false;
25520
25521   bool Promote = false;
25522   bool Commute = false;
25523   switch (Op.getOpcode()) {
25524   default: break;
25525   case ISD::LOAD: {
25526     LoadSDNode *LD = cast<LoadSDNode>(Op);
25527     // If the non-extending load has a single use and it's not live out, then it
25528     // might be folded.
25529     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25530                                                      Op.hasOneUse()*/) {
25531       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25532              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25533         // The only case where we'd want to promote LOAD (rather then it being
25534         // promoted as an operand is when it's only use is liveout.
25535         if (UI->getOpcode() != ISD::CopyToReg)
25536           return false;
25537       }
25538     }
25539     Promote = true;
25540     break;
25541   }
25542   case ISD::SIGN_EXTEND:
25543   case ISD::ZERO_EXTEND:
25544   case ISD::ANY_EXTEND:
25545     Promote = true;
25546     break;
25547   case ISD::SHL:
25548   case ISD::SRL: {
25549     SDValue N0 = Op.getOperand(0);
25550     // Look out for (store (shl (load), x)).
25551     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25552       return false;
25553     Promote = true;
25554     break;
25555   }
25556   case ISD::ADD:
25557   case ISD::MUL:
25558   case ISD::AND:
25559   case ISD::OR:
25560   case ISD::XOR:
25561     Commute = true;
25562     // fallthrough
25563   case ISD::SUB: {
25564     SDValue N0 = Op.getOperand(0);
25565     SDValue N1 = Op.getOperand(1);
25566     if (!Commute && MayFoldLoad(N1))
25567       return false;
25568     // Avoid disabling potential load folding opportunities.
25569     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25570       return false;
25571     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25572       return false;
25573     Promote = true;
25574   }
25575   }
25576
25577   PVT = MVT::i32;
25578   return Promote;
25579 }
25580
25581 //===----------------------------------------------------------------------===//
25582 //                           X86 Inline Assembly Support
25583 //===----------------------------------------------------------------------===//
25584
25585 // Helper to match a string separated by whitespace.
25586 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25587   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25588
25589   for (StringRef Piece : Pieces) {
25590     if (!S.startswith(Piece)) // Check if the piece matches.
25591       return false;
25592
25593     S = S.substr(Piece.size());
25594     StringRef::size_type Pos = S.find_first_not_of(" \t");
25595     if (Pos == 0) // We matched a prefix.
25596       return false;
25597
25598     S = S.substr(Pos);
25599   }
25600
25601   return S.empty();
25602 }
25603
25604 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25605
25606   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25607     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25608         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25609         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25610
25611       if (AsmPieces.size() == 3)
25612         return true;
25613       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25614         return true;
25615     }
25616   }
25617   return false;
25618 }
25619
25620 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25621   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25622
25623   std::string AsmStr = IA->getAsmString();
25624
25625   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25626   if (!Ty || Ty->getBitWidth() % 16 != 0)
25627     return false;
25628
25629   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25630   SmallVector<StringRef, 4> AsmPieces;
25631   SplitString(AsmStr, AsmPieces, ";\n");
25632
25633   switch (AsmPieces.size()) {
25634   default: return false;
25635   case 1:
25636     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25637     // we will turn this bswap into something that will be lowered to logical
25638     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25639     // lower so don't worry about this.
25640     // bswap $0
25641     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25642         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25643         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25644         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25645         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25646         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25647       // No need to check constraints, nothing other than the equivalent of
25648       // "=r,0" would be valid here.
25649       return IntrinsicLowering::LowerToByteSwap(CI);
25650     }
25651
25652     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25653     if (CI->getType()->isIntegerTy(16) &&
25654         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25655         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25656          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25657       AsmPieces.clear();
25658       StringRef ConstraintsStr = IA->getConstraintString();
25659       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25660       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25661       if (clobbersFlagRegisters(AsmPieces))
25662         return IntrinsicLowering::LowerToByteSwap(CI);
25663     }
25664     break;
25665   case 3:
25666     if (CI->getType()->isIntegerTy(32) &&
25667         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25668         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25669         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25670         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25671       AsmPieces.clear();
25672       StringRef ConstraintsStr = IA->getConstraintString();
25673       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25674       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25675       if (clobbersFlagRegisters(AsmPieces))
25676         return IntrinsicLowering::LowerToByteSwap(CI);
25677     }
25678
25679     if (CI->getType()->isIntegerTy(64)) {
25680       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25681       if (Constraints.size() >= 2 &&
25682           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25683           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25684         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25685         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25686             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25687             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25688           return IntrinsicLowering::LowerToByteSwap(CI);
25689       }
25690     }
25691     break;
25692   }
25693   return false;
25694 }
25695
25696 /// getConstraintType - Given a constraint letter, return the type of
25697 /// constraint it is for this target.
25698 X86TargetLowering::ConstraintType
25699 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25700   if (Constraint.size() == 1) {
25701     switch (Constraint[0]) {
25702     case 'R':
25703     case 'q':
25704     case 'Q':
25705     case 'f':
25706     case 't':
25707     case 'u':
25708     case 'y':
25709     case 'x':
25710     case 'Y':
25711     case 'l':
25712       return C_RegisterClass;
25713     case 'a':
25714     case 'b':
25715     case 'c':
25716     case 'd':
25717     case 'S':
25718     case 'D':
25719     case 'A':
25720       return C_Register;
25721     case 'I':
25722     case 'J':
25723     case 'K':
25724     case 'L':
25725     case 'M':
25726     case 'N':
25727     case 'G':
25728     case 'C':
25729     case 'e':
25730     case 'Z':
25731       return C_Other;
25732     default:
25733       break;
25734     }
25735   }
25736   return TargetLowering::getConstraintType(Constraint);
25737 }
25738
25739 /// Examine constraint type and operand type and determine a weight value.
25740 /// This object must already have been set up with the operand type
25741 /// and the current alternative constraint selected.
25742 TargetLowering::ConstraintWeight
25743   X86TargetLowering::getSingleConstraintMatchWeight(
25744     AsmOperandInfo &info, const char *constraint) const {
25745   ConstraintWeight weight = CW_Invalid;
25746   Value *CallOperandVal = info.CallOperandVal;
25747     // If we don't have a value, we can't do a match,
25748     // but allow it at the lowest weight.
25749   if (!CallOperandVal)
25750     return CW_Default;
25751   Type *type = CallOperandVal->getType();
25752   // Look at the constraint type.
25753   switch (*constraint) {
25754   default:
25755     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25756   case 'R':
25757   case 'q':
25758   case 'Q':
25759   case 'a':
25760   case 'b':
25761   case 'c':
25762   case 'd':
25763   case 'S':
25764   case 'D':
25765   case 'A':
25766     if (CallOperandVal->getType()->isIntegerTy())
25767       weight = CW_SpecificReg;
25768     break;
25769   case 'f':
25770   case 't':
25771   case 'u':
25772     if (type->isFloatingPointTy())
25773       weight = CW_SpecificReg;
25774     break;
25775   case 'y':
25776     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25777       weight = CW_SpecificReg;
25778     break;
25779   case 'x':
25780   case 'Y':
25781     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25782         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25783       weight = CW_Register;
25784     break;
25785   case 'I':
25786     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25787       if (C->getZExtValue() <= 31)
25788         weight = CW_Constant;
25789     }
25790     break;
25791   case 'J':
25792     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25793       if (C->getZExtValue() <= 63)
25794         weight = CW_Constant;
25795     }
25796     break;
25797   case 'K':
25798     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25799       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25800         weight = CW_Constant;
25801     }
25802     break;
25803   case 'L':
25804     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25805       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25806         weight = CW_Constant;
25807     }
25808     break;
25809   case 'M':
25810     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25811       if (C->getZExtValue() <= 3)
25812         weight = CW_Constant;
25813     }
25814     break;
25815   case 'N':
25816     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25817       if (C->getZExtValue() <= 0xff)
25818         weight = CW_Constant;
25819     }
25820     break;
25821   case 'G':
25822   case 'C':
25823     if (isa<ConstantFP>(CallOperandVal)) {
25824       weight = CW_Constant;
25825     }
25826     break;
25827   case 'e':
25828     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25829       if ((C->getSExtValue() >= -0x80000000LL) &&
25830           (C->getSExtValue() <= 0x7fffffffLL))
25831         weight = CW_Constant;
25832     }
25833     break;
25834   case 'Z':
25835     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25836       if (C->getZExtValue() <= 0xffffffff)
25837         weight = CW_Constant;
25838     }
25839     break;
25840   }
25841   return weight;
25842 }
25843
25844 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25845 /// with another that has more specific requirements based on the type of the
25846 /// corresponding operand.
25847 const char *X86TargetLowering::
25848 LowerXConstraint(EVT ConstraintVT) const {
25849   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25850   // 'f' like normal targets.
25851   if (ConstraintVT.isFloatingPoint()) {
25852     if (Subtarget->hasSSE2())
25853       return "Y";
25854     if (Subtarget->hasSSE1())
25855       return "x";
25856   }
25857
25858   return TargetLowering::LowerXConstraint(ConstraintVT);
25859 }
25860
25861 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25862 /// vector.  If it is invalid, don't add anything to Ops.
25863 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25864                                                      std::string &Constraint,
25865                                                      std::vector<SDValue>&Ops,
25866                                                      SelectionDAG &DAG) const {
25867   SDValue Result;
25868
25869   // Only support length 1 constraints for now.
25870   if (Constraint.length() > 1) return;
25871
25872   char ConstraintLetter = Constraint[0];
25873   switch (ConstraintLetter) {
25874   default: break;
25875   case 'I':
25876     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25877       if (C->getZExtValue() <= 31) {
25878         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25879                                        Op.getValueType());
25880         break;
25881       }
25882     }
25883     return;
25884   case 'J':
25885     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25886       if (C->getZExtValue() <= 63) {
25887         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25888                                        Op.getValueType());
25889         break;
25890       }
25891     }
25892     return;
25893   case 'K':
25894     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25895       if (isInt<8>(C->getSExtValue())) {
25896         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25897                                        Op.getValueType());
25898         break;
25899       }
25900     }
25901     return;
25902   case 'L':
25903     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25904       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
25905           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
25906         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
25907                                        Op.getValueType());
25908         break;
25909       }
25910     }
25911     return;
25912   case 'M':
25913     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25914       if (C->getZExtValue() <= 3) {
25915         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25916                                        Op.getValueType());
25917         break;
25918       }
25919     }
25920     return;
25921   case 'N':
25922     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25923       if (C->getZExtValue() <= 255) {
25924         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25925                                        Op.getValueType());
25926         break;
25927       }
25928     }
25929     return;
25930   case 'O':
25931     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25932       if (C->getZExtValue() <= 127) {
25933         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25934                                        Op.getValueType());
25935         break;
25936       }
25937     }
25938     return;
25939   case 'e': {
25940     // 32-bit signed value
25941     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25942       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25943                                            C->getSExtValue())) {
25944         // Widen to 64 bits here to get it sign extended.
25945         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25946         break;
25947       }
25948     // FIXME gcc accepts some relocatable values here too, but only in certain
25949     // memory models; it's complicated.
25950     }
25951     return;
25952   }
25953   case 'Z': {
25954     // 32-bit unsigned value
25955     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25956       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25957                                            C->getZExtValue())) {
25958         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25959                                        Op.getValueType());
25960         break;
25961       }
25962     }
25963     // FIXME gcc accepts some relocatable values here too, but only in certain
25964     // memory models; it's complicated.
25965     return;
25966   }
25967   case 'i': {
25968     // Literal immediates are always ok.
25969     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25970       // Widen to 64 bits here to get it sign extended.
25971       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25972       break;
25973     }
25974
25975     // In any sort of PIC mode addresses need to be computed at runtime by
25976     // adding in a register or some sort of table lookup.  These can't
25977     // be used as immediates.
25978     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25979       return;
25980
25981     // If we are in non-pic codegen mode, we allow the address of a global (with
25982     // an optional displacement) to be used with 'i'.
25983     GlobalAddressSDNode *GA = nullptr;
25984     int64_t Offset = 0;
25985
25986     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25987     while (1) {
25988       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25989         Offset += GA->getOffset();
25990         break;
25991       } else if (Op.getOpcode() == ISD::ADD) {
25992         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25993           Offset += C->getZExtValue();
25994           Op = Op.getOperand(0);
25995           continue;
25996         }
25997       } else if (Op.getOpcode() == ISD::SUB) {
25998         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25999           Offset += -C->getZExtValue();
26000           Op = Op.getOperand(0);
26001           continue;
26002         }
26003       }
26004
26005       // Otherwise, this isn't something we can handle, reject it.
26006       return;
26007     }
26008
26009     const GlobalValue *GV = GA->getGlobal();
26010     // If we require an extra load to get this address, as in PIC mode, we
26011     // can't accept it.
26012     if (isGlobalStubReference(
26013             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26014       return;
26015
26016     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26017                                         GA->getValueType(0), Offset);
26018     break;
26019   }
26020   }
26021
26022   if (Result.getNode()) {
26023     Ops.push_back(Result);
26024     return;
26025   }
26026   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26027 }
26028
26029 std::pair<unsigned, const TargetRegisterClass *>
26030 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26031                                                 StringRef Constraint,
26032                                                 MVT VT) const {
26033   // First, see if this is a constraint that directly corresponds to an LLVM
26034   // register class.
26035   if (Constraint.size() == 1) {
26036     // GCC Constraint Letters
26037     switch (Constraint[0]) {
26038     default: break;
26039       // TODO: Slight differences here in allocation order and leaving
26040       // RIP in the class. Do they matter any more here than they do
26041       // in the normal allocation?
26042     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26043       if (Subtarget->is64Bit()) {
26044         if (VT == MVT::i32 || VT == MVT::f32)
26045           return std::make_pair(0U, &X86::GR32RegClass);
26046         if (VT == MVT::i16)
26047           return std::make_pair(0U, &X86::GR16RegClass);
26048         if (VT == MVT::i8 || VT == MVT::i1)
26049           return std::make_pair(0U, &X86::GR8RegClass);
26050         if (VT == MVT::i64 || VT == MVT::f64)
26051           return std::make_pair(0U, &X86::GR64RegClass);
26052         break;
26053       }
26054       // 32-bit fallthrough
26055     case 'Q':   // Q_REGS
26056       if (VT == MVT::i32 || VT == MVT::f32)
26057         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26058       if (VT == MVT::i16)
26059         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26060       if (VT == MVT::i8 || VT == MVT::i1)
26061         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26062       if (VT == MVT::i64)
26063         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26064       break;
26065     case 'r':   // GENERAL_REGS
26066     case 'l':   // INDEX_REGS
26067       if (VT == MVT::i8 || VT == MVT::i1)
26068         return std::make_pair(0U, &X86::GR8RegClass);
26069       if (VT == MVT::i16)
26070         return std::make_pair(0U, &X86::GR16RegClass);
26071       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26072         return std::make_pair(0U, &X86::GR32RegClass);
26073       return std::make_pair(0U, &X86::GR64RegClass);
26074     case 'R':   // LEGACY_REGS
26075       if (VT == MVT::i8 || VT == MVT::i1)
26076         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26077       if (VT == MVT::i16)
26078         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26079       if (VT == MVT::i32 || !Subtarget->is64Bit())
26080         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26081       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26082     case 'f':  // FP Stack registers.
26083       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26084       // value to the correct fpstack register class.
26085       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26086         return std::make_pair(0U, &X86::RFP32RegClass);
26087       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26088         return std::make_pair(0U, &X86::RFP64RegClass);
26089       return std::make_pair(0U, &X86::RFP80RegClass);
26090     case 'y':   // MMX_REGS if MMX allowed.
26091       if (!Subtarget->hasMMX()) break;
26092       return std::make_pair(0U, &X86::VR64RegClass);
26093     case 'Y':   // SSE_REGS if SSE2 allowed
26094       if (!Subtarget->hasSSE2()) break;
26095       // FALL THROUGH.
26096     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26097       if (!Subtarget->hasSSE1()) break;
26098
26099       switch (VT.SimpleTy) {
26100       default: break;
26101       // Scalar SSE types.
26102       case MVT::f32:
26103       case MVT::i32:
26104         return std::make_pair(0U, &X86::FR32RegClass);
26105       case MVT::f64:
26106       case MVT::i64:
26107         return std::make_pair(0U, &X86::FR64RegClass);
26108       // Vector types.
26109       case MVT::v16i8:
26110       case MVT::v8i16:
26111       case MVT::v4i32:
26112       case MVT::v2i64:
26113       case MVT::v4f32:
26114       case MVT::v2f64:
26115         return std::make_pair(0U, &X86::VR128RegClass);
26116       // AVX types.
26117       case MVT::v32i8:
26118       case MVT::v16i16:
26119       case MVT::v8i32:
26120       case MVT::v4i64:
26121       case MVT::v8f32:
26122       case MVT::v4f64:
26123         return std::make_pair(0U, &X86::VR256RegClass);
26124       case MVT::v8f64:
26125       case MVT::v16f32:
26126       case MVT::v16i32:
26127       case MVT::v8i64:
26128         return std::make_pair(0U, &X86::VR512RegClass);
26129       }
26130       break;
26131     }
26132   }
26133
26134   // Use the default implementation in TargetLowering to convert the register
26135   // constraint into a member of a register class.
26136   std::pair<unsigned, const TargetRegisterClass*> Res;
26137   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26138
26139   // Not found as a standard register?
26140   if (!Res.second) {
26141     // Map st(0) -> st(7) -> ST0
26142     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26143         tolower(Constraint[1]) == 's' &&
26144         tolower(Constraint[2]) == 't' &&
26145         Constraint[3] == '(' &&
26146         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26147         Constraint[5] == ')' &&
26148         Constraint[6] == '}') {
26149
26150       Res.first = X86::FP0+Constraint[4]-'0';
26151       Res.second = &X86::RFP80RegClass;
26152       return Res;
26153     }
26154
26155     // GCC allows "st(0)" to be called just plain "st".
26156     if (StringRef("{st}").equals_lower(Constraint)) {
26157       Res.first = X86::FP0;
26158       Res.second = &X86::RFP80RegClass;
26159       return Res;
26160     }
26161
26162     // flags -> EFLAGS
26163     if (StringRef("{flags}").equals_lower(Constraint)) {
26164       Res.first = X86::EFLAGS;
26165       Res.second = &X86::CCRRegClass;
26166       return Res;
26167     }
26168
26169     // 'A' means EAX + EDX.
26170     if (Constraint == "A") {
26171       Res.first = X86::EAX;
26172       Res.second = &X86::GR32_ADRegClass;
26173       return Res;
26174     }
26175     return Res;
26176   }
26177
26178   // Otherwise, check to see if this is a register class of the wrong value
26179   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26180   // turn into {ax},{dx}.
26181   // MVT::Other is used to specify clobber names.
26182   if (Res.second->hasType(VT) || VT == MVT::Other)
26183     return Res;   // Correct type already, nothing to do.
26184
26185   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26186   // return "eax". This should even work for things like getting 64bit integer
26187   // registers when given an f64 type.
26188   const TargetRegisterClass *Class = Res.second;
26189   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26190       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26191     unsigned Size = VT.getSizeInBits();
26192     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26193                                   : Size == 16 ? MVT::i16
26194                                   : Size == 32 ? MVT::i32
26195                                   : Size == 64 ? MVT::i64
26196                                   : MVT::Other;
26197     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26198     if (DestReg > 0) {
26199       Res.first = DestReg;
26200       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26201                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26202                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26203                  : &X86::GR64RegClass;
26204       assert(Res.second->contains(Res.first) && "Register in register class");
26205     } else {
26206       // No register found/type mismatch.
26207       Res.first = 0;
26208       Res.second = nullptr;
26209     }
26210   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26211              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26212              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26213              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26214              Class == &X86::VR512RegClass) {
26215     // Handle references to XMM physical registers that got mapped into the
26216     // wrong class.  This can happen with constraints like {xmm0} where the
26217     // target independent register mapper will just pick the first match it can
26218     // find, ignoring the required type.
26219
26220     if (VT == MVT::f32 || VT == MVT::i32)
26221       Res.second = &X86::FR32RegClass;
26222     else if (VT == MVT::f64 || VT == MVT::i64)
26223       Res.second = &X86::FR64RegClass;
26224     else if (X86::VR128RegClass.hasType(VT))
26225       Res.second = &X86::VR128RegClass;
26226     else if (X86::VR256RegClass.hasType(VT))
26227       Res.second = &X86::VR256RegClass;
26228     else if (X86::VR512RegClass.hasType(VT))
26229       Res.second = &X86::VR512RegClass;
26230     else {
26231       // Type mismatch and not a clobber: Return an error;
26232       Res.first = 0;
26233       Res.second = nullptr;
26234     }
26235   }
26236
26237   return Res;
26238 }
26239
26240 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26241                                             const AddrMode &AM, Type *Ty,
26242                                             unsigned AS) const {
26243   // Scaling factors are not free at all.
26244   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26245   // will take 2 allocations in the out of order engine instead of 1
26246   // for plain addressing mode, i.e. inst (reg1).
26247   // E.g.,
26248   // vaddps (%rsi,%drx), %ymm0, %ymm1
26249   // Requires two allocations (one for the load, one for the computation)
26250   // whereas:
26251   // vaddps (%rsi), %ymm0, %ymm1
26252   // Requires just 1 allocation, i.e., freeing allocations for other operations
26253   // and having less micro operations to execute.
26254   //
26255   // For some X86 architectures, this is even worse because for instance for
26256   // stores, the complex addressing mode forces the instruction to use the
26257   // "load" ports instead of the dedicated "store" port.
26258   // E.g., on Haswell:
26259   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26260   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26261   if (isLegalAddressingMode(DL, AM, Ty, AS))
26262     // Scale represents reg2 * scale, thus account for 1
26263     // as soon as we use a second register.
26264     return AM.Scale != 0;
26265   return -1;
26266 }
26267
26268 bool X86TargetLowering::isTargetFTOL() const {
26269   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26270 }