Remove access to the DataLayout in the TargetMachine
[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   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
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, PtrVT, 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             auto &DL = DAG.getDataLayout();
16520             // FIXME: should only count parameters that are lowered to integers.
16521             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16522           }
16523
16524         if (InRegCount > 2) {
16525           report_fatal_error("Nest register in use - reduce number of inreg"
16526                              " parameters!");
16527         }
16528       }
16529       break;
16530     }
16531     case CallingConv::X86_FastCall:
16532     case CallingConv::X86_ThisCall:
16533     case CallingConv::Fast:
16534       // Pass 'nest' parameter in EAX.
16535       // Must be kept in sync with X86CallingConv.td
16536       NestReg = X86::EAX;
16537       break;
16538     }
16539
16540     SDValue OutChains[4];
16541     SDValue Addr, Disp;
16542
16543     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16544                        DAG.getConstant(10, dl, MVT::i32));
16545     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16546
16547     // This is storing the opcode for MOV32ri.
16548     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16549     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16550     OutChains[0] = DAG.getStore(Root, dl,
16551                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16552                                 Trmp, MachinePointerInfo(TrmpAddr),
16553                                 false, false, 0);
16554
16555     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16556                        DAG.getConstant(1, dl, MVT::i32));
16557     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16558                                 MachinePointerInfo(TrmpAddr, 1),
16559                                 false, false, 1);
16560
16561     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16562     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16563                        DAG.getConstant(5, dl, MVT::i32));
16564     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16565                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16566                                 false, false, 1);
16567
16568     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16569                        DAG.getConstant(6, dl, MVT::i32));
16570     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16571                                 MachinePointerInfo(TrmpAddr, 6),
16572                                 false, false, 1);
16573
16574     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16575   }
16576 }
16577
16578 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16579                                             SelectionDAG &DAG) const {
16580   /*
16581    The rounding mode is in bits 11:10 of FPSR, and has the following
16582    settings:
16583      00 Round to nearest
16584      01 Round to -inf
16585      10 Round to +inf
16586      11 Round to 0
16587
16588   FLT_ROUNDS, on the other hand, expects the following:
16589     -1 Undefined
16590      0 Round to 0
16591      1 Round to nearest
16592      2 Round to +inf
16593      3 Round to -inf
16594
16595   To perform the conversion, we do:
16596     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16597   */
16598
16599   MachineFunction &MF = DAG.getMachineFunction();
16600   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16601   unsigned StackAlignment = TFI.getStackAlignment();
16602   MVT VT = Op.getSimpleValueType();
16603   SDLoc DL(Op);
16604
16605   // Save FP Control Word to stack slot
16606   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16607   SDValue StackSlot =
16608       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16609
16610   MachineMemOperand *MMO =
16611    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16612                            MachineMemOperand::MOStore, 2, 2);
16613
16614   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16615   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16616                                           DAG.getVTList(MVT::Other),
16617                                           Ops, MVT::i16, MMO);
16618
16619   // Load FP Control Word from stack slot
16620   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16621                             MachinePointerInfo(), false, false, false, 0);
16622
16623   // Transform as necessary
16624   SDValue CWD1 =
16625     DAG.getNode(ISD::SRL, DL, MVT::i16,
16626                 DAG.getNode(ISD::AND, DL, MVT::i16,
16627                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16628                 DAG.getConstant(11, DL, MVT::i8));
16629   SDValue CWD2 =
16630     DAG.getNode(ISD::SRL, DL, MVT::i16,
16631                 DAG.getNode(ISD::AND, DL, MVT::i16,
16632                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16633                 DAG.getConstant(9, DL, MVT::i8));
16634
16635   SDValue RetVal =
16636     DAG.getNode(ISD::AND, DL, MVT::i16,
16637                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16638                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16639                             DAG.getConstant(1, DL, MVT::i16)),
16640                 DAG.getConstant(3, DL, MVT::i16));
16641
16642   return DAG.getNode((VT.getSizeInBits() < 16 ?
16643                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16644 }
16645
16646 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16647   MVT VT = Op.getSimpleValueType();
16648   EVT OpVT = VT;
16649   unsigned NumBits = VT.getSizeInBits();
16650   SDLoc dl(Op);
16651
16652   Op = Op.getOperand(0);
16653   if (VT == MVT::i8) {
16654     // Zero extend to i32 since there is not an i8 bsr.
16655     OpVT = MVT::i32;
16656     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16657   }
16658
16659   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16660   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16661   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16662
16663   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16664   SDValue Ops[] = {
16665     Op,
16666     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16667     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16668     Op.getValue(1)
16669   };
16670   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16671
16672   // Finally xor with NumBits-1.
16673   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16674                    DAG.getConstant(NumBits - 1, dl, OpVT));
16675
16676   if (VT == MVT::i8)
16677     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16678   return Op;
16679 }
16680
16681 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16682   MVT VT = Op.getSimpleValueType();
16683   EVT OpVT = VT;
16684   unsigned NumBits = VT.getSizeInBits();
16685   SDLoc dl(Op);
16686
16687   Op = Op.getOperand(0);
16688   if (VT == MVT::i8) {
16689     // Zero extend to i32 since there is not an i8 bsr.
16690     OpVT = MVT::i32;
16691     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16692   }
16693
16694   // Issue a bsr (scan bits in reverse).
16695   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16696   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16697
16698   // And xor with NumBits-1.
16699   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16700                    DAG.getConstant(NumBits - 1, dl, OpVT));
16701
16702   if (VT == MVT::i8)
16703     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16704   return Op;
16705 }
16706
16707 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16708   MVT VT = Op.getSimpleValueType();
16709   unsigned NumBits = VT.getSizeInBits();
16710   SDLoc dl(Op);
16711   Op = Op.getOperand(0);
16712
16713   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16714   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16715   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16716
16717   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16718   SDValue Ops[] = {
16719     Op,
16720     DAG.getConstant(NumBits, dl, VT),
16721     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16722     Op.getValue(1)
16723   };
16724   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16725 }
16726
16727 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16728 // ones, and then concatenate the result back.
16729 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16730   MVT VT = Op.getSimpleValueType();
16731
16732   assert(VT.is256BitVector() && VT.isInteger() &&
16733          "Unsupported value type for operation");
16734
16735   unsigned NumElems = VT.getVectorNumElements();
16736   SDLoc dl(Op);
16737
16738   // Extract the LHS vectors
16739   SDValue LHS = Op.getOperand(0);
16740   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16741   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16742
16743   // Extract the RHS vectors
16744   SDValue RHS = Op.getOperand(1);
16745   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16746   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16747
16748   MVT EltVT = VT.getVectorElementType();
16749   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16750
16751   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16752                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16753                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16754 }
16755
16756 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16757   if (Op.getValueType() == MVT::i1)
16758     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16759                        Op.getOperand(0), Op.getOperand(1));
16760   assert(Op.getSimpleValueType().is256BitVector() &&
16761          Op.getSimpleValueType().isInteger() &&
16762          "Only handle AVX 256-bit vector integer operation");
16763   return Lower256IntArith(Op, DAG);
16764 }
16765
16766 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16767   if (Op.getValueType() == MVT::i1)
16768     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16769                        Op.getOperand(0), Op.getOperand(1));
16770   assert(Op.getSimpleValueType().is256BitVector() &&
16771          Op.getSimpleValueType().isInteger() &&
16772          "Only handle AVX 256-bit vector integer operation");
16773   return Lower256IntArith(Op, DAG);
16774 }
16775
16776 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16777                         SelectionDAG &DAG) {
16778   SDLoc dl(Op);
16779   MVT VT = Op.getSimpleValueType();
16780
16781   if (VT == MVT::i1)
16782     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16783
16784   // Decompose 256-bit ops into smaller 128-bit ops.
16785   if (VT.is256BitVector() && !Subtarget->hasInt256())
16786     return Lower256IntArith(Op, DAG);
16787
16788   SDValue A = Op.getOperand(0);
16789   SDValue B = Op.getOperand(1);
16790
16791   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16792   // pairs, multiply and truncate.
16793   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16794     if (Subtarget->hasInt256()) {
16795       if (VT == MVT::v32i8) {
16796         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16797         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16798         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16799         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16800         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16801         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16802         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16803         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16804                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16805                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16806       }
16807
16808       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16809       return DAG.getNode(
16810           ISD::TRUNCATE, dl, VT,
16811           DAG.getNode(ISD::MUL, dl, ExVT,
16812                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16813                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16814     }
16815
16816     assert(VT == MVT::v16i8 &&
16817            "Pre-AVX2 support only supports v16i8 multiplication");
16818     MVT ExVT = MVT::v8i16;
16819
16820     // Extract the lo parts and sign extend to i16
16821     SDValue ALo, BLo;
16822     if (Subtarget->hasSSE41()) {
16823       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16824       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16825     } else {
16826       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16827                               -1, 4, -1, 5, -1, 6, -1, 7};
16828       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16829       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16830       ALo = DAG.getBitcast(ExVT, ALo);
16831       BLo = DAG.getBitcast(ExVT, BLo);
16832       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16833       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16834     }
16835
16836     // Extract the hi parts and sign extend to i16
16837     SDValue AHi, BHi;
16838     if (Subtarget->hasSSE41()) {
16839       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16840                               -1, -1, -1, -1, -1, -1, -1, -1};
16841       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16842       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16843       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16844       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16845     } else {
16846       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16847                               -1, 12, -1, 13, -1, 14, -1, 15};
16848       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16849       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16850       AHi = DAG.getBitcast(ExVT, AHi);
16851       BHi = DAG.getBitcast(ExVT, BHi);
16852       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16853       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16854     }
16855
16856     // Multiply, mask the lower 8bits of the lo/hi results and pack
16857     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16858     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16859     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16860     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16861     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16862   }
16863
16864   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16865   if (VT == MVT::v4i32) {
16866     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16867            "Should not custom lower when pmuldq is available!");
16868
16869     // Extract the odd parts.
16870     static const int UnpackMask[] = { 1, -1, 3, -1 };
16871     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16872     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16873
16874     // Multiply the even parts.
16875     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16876     // Now multiply odd parts.
16877     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16878
16879     Evens = DAG.getBitcast(VT, Evens);
16880     Odds = DAG.getBitcast(VT, Odds);
16881
16882     // Merge the two vectors back together with a shuffle. This expands into 2
16883     // shuffles.
16884     static const int ShufMask[] = { 0, 4, 2, 6 };
16885     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16886   }
16887
16888   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16889          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16890
16891   //  Ahi = psrlqi(a, 32);
16892   //  Bhi = psrlqi(b, 32);
16893   //
16894   //  AloBlo = pmuludq(a, b);
16895   //  AloBhi = pmuludq(a, Bhi);
16896   //  AhiBlo = pmuludq(Ahi, b);
16897
16898   //  AloBhi = psllqi(AloBhi, 32);
16899   //  AhiBlo = psllqi(AhiBlo, 32);
16900   //  return AloBlo + AloBhi + AhiBlo;
16901
16902   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16903   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16904
16905   SDValue AhiBlo = Ahi;
16906   SDValue AloBhi = Bhi;
16907   // Bit cast to 32-bit vectors for MULUDQ
16908   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16909                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16910   A = DAG.getBitcast(MulVT, A);
16911   B = DAG.getBitcast(MulVT, B);
16912   Ahi = DAG.getBitcast(MulVT, Ahi);
16913   Bhi = DAG.getBitcast(MulVT, Bhi);
16914
16915   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16916   // After shifting right const values the result may be all-zero.
16917   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
16918     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16919     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16920   }
16921   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
16922     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16923     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16924   }
16925
16926   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16927   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16928 }
16929
16930 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16931   assert(Subtarget->isTargetWin64() && "Unexpected target");
16932   EVT VT = Op.getValueType();
16933   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16934          "Unexpected return type for lowering");
16935
16936   RTLIB::Libcall LC;
16937   bool isSigned;
16938   switch (Op->getOpcode()) {
16939   default: llvm_unreachable("Unexpected request for libcall!");
16940   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16941   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16942   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16943   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16944   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16945   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16946   }
16947
16948   SDLoc dl(Op);
16949   SDValue InChain = DAG.getEntryNode();
16950
16951   TargetLowering::ArgListTy Args;
16952   TargetLowering::ArgListEntry Entry;
16953   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16954     EVT ArgVT = Op->getOperand(i).getValueType();
16955     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16956            "Unexpected argument type for lowering");
16957     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16958     Entry.Node = StackPtr;
16959     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16960                            false, false, 16);
16961     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16962     Entry.Ty = PointerType::get(ArgTy,0);
16963     Entry.isSExt = false;
16964     Entry.isZExt = false;
16965     Args.push_back(Entry);
16966   }
16967
16968   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16969                                          getPointerTy(DAG.getDataLayout()));
16970
16971   TargetLowering::CallLoweringInfo CLI(DAG);
16972   CLI.setDebugLoc(dl).setChain(InChain)
16973     .setCallee(getLibcallCallingConv(LC),
16974                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16975                Callee, std::move(Args), 0)
16976     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16977
16978   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16979   return DAG.getBitcast(VT, CallInfo.first);
16980 }
16981
16982 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16983                              SelectionDAG &DAG) {
16984   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16985   EVT VT = Op0.getValueType();
16986   SDLoc dl(Op);
16987
16988   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16989          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16990
16991   // PMULxD operations multiply each even value (starting at 0) of LHS with
16992   // the related value of RHS and produce a widen result.
16993   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16994   // => <2 x i64> <ae|cg>
16995   //
16996   // In other word, to have all the results, we need to perform two PMULxD:
16997   // 1. one with the even values.
16998   // 2. one with the odd values.
16999   // To achieve #2, with need to place the odd values at an even position.
17000   //
17001   // Place the odd value at an even position (basically, shift all values 1
17002   // step to the left):
17003   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17004   // <a|b|c|d> => <b|undef|d|undef>
17005   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17006   // <e|f|g|h> => <f|undef|h|undef>
17007   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17008
17009   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17010   // ints.
17011   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17012   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17013   unsigned Opcode =
17014       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17015   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17016   // => <2 x i64> <ae|cg>
17017   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17018   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17019   // => <2 x i64> <bf|dh>
17020   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17021
17022   // Shuffle it back into the right order.
17023   SDValue Highs, Lows;
17024   if (VT == MVT::v8i32) {
17025     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17026     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17027     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17028     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17029   } else {
17030     const int HighMask[] = {1, 5, 3, 7};
17031     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17032     const int LowMask[] = {0, 4, 2, 6};
17033     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17034   }
17035
17036   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17037   // unsigned multiply.
17038   if (IsSigned && !Subtarget->hasSSE41()) {
17039     SDValue ShAmt = DAG.getConstant(
17040         31, dl,
17041         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17042     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17043                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17044     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17045                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17046
17047     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17048     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17049   }
17050
17051   // The first result of MUL_LOHI is actually the low value, followed by the
17052   // high value.
17053   SDValue Ops[] = {Lows, Highs};
17054   return DAG.getMergeValues(Ops, dl);
17055 }
17056
17057 // Return true if the required (according to Opcode) shift-imm form is natively
17058 // supported by the Subtarget
17059 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17060                                         unsigned Opcode) {
17061   if (VT.getScalarSizeInBits() < 16)
17062     return false;
17063
17064   if (VT.is512BitVector() &&
17065       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17066     return true;
17067
17068   bool LShift = VT.is128BitVector() ||
17069     (VT.is256BitVector() && Subtarget->hasInt256());
17070
17071   bool AShift = LShift && (Subtarget->hasVLX() ||
17072     (VT != MVT::v2i64 && VT != MVT::v4i64));
17073   return (Opcode == ISD::SRA) ? AShift : LShift;
17074 }
17075
17076 // The shift amount is a variable, but it is the same for all vector lanes.
17077 // These instructions are defined together with shift-immediate.
17078 static
17079 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17080                                       unsigned Opcode) {
17081   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17082 }
17083
17084 // Return true if the required (according to Opcode) variable-shift form is
17085 // natively supported by the Subtarget
17086 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17087                                     unsigned Opcode) {
17088
17089   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17090     return false;
17091
17092   // vXi16 supported only on AVX-512, BWI
17093   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17094     return false;
17095
17096   if (VT.is512BitVector() || Subtarget->hasVLX())
17097     return true;
17098
17099   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17100   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17101   return (Opcode == ISD::SRA) ? AShift : LShift;
17102 }
17103
17104 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17105                                          const X86Subtarget *Subtarget) {
17106   MVT VT = Op.getSimpleValueType();
17107   SDLoc dl(Op);
17108   SDValue R = Op.getOperand(0);
17109   SDValue Amt = Op.getOperand(1);
17110
17111   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17112     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17113
17114   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17115     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17116     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17117     SDValue Ex = DAG.getBitcast(ExVT, R);
17118
17119     if (ShiftAmt >= 32) {
17120       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17121       SDValue Upper =
17122           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17123       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17124                                                  ShiftAmt - 32, DAG);
17125       if (VT == MVT::v2i64)
17126         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17127       if (VT == MVT::v4i64)
17128         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17129                                   {9, 1, 11, 3, 13, 5, 15, 7});
17130     } else {
17131       // SRA upper i32, SHL whole i64 and select lower i32.
17132       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17133                                                  ShiftAmt, DAG);
17134       SDValue Lower =
17135           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17136       Lower = DAG.getBitcast(ExVT, Lower);
17137       if (VT == MVT::v2i64)
17138         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17139       if (VT == MVT::v4i64)
17140         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17141                                   {8, 1, 10, 3, 12, 5, 14, 7});
17142     }
17143     return DAG.getBitcast(VT, Ex);
17144   };
17145
17146   // Optimize shl/srl/sra with constant shift amount.
17147   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17148     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17149       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17150
17151       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17152         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17153
17154       // i64 SRA needs to be performed as partial shifts.
17155       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17156           Op.getOpcode() == ISD::SRA)
17157         return ArithmeticShiftRight64(ShiftAmt);
17158
17159       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17160         unsigned NumElts = VT.getVectorNumElements();
17161         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17162
17163         if (Op.getOpcode() == ISD::SHL) {
17164           // Simple i8 add case
17165           if (ShiftAmt == 1)
17166             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17167
17168           // Make a large shift.
17169           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17170                                                    R, ShiftAmt, DAG);
17171           SHL = DAG.getBitcast(VT, SHL);
17172           // Zero out the rightmost bits.
17173           SmallVector<SDValue, 32> V(
17174               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17175           return DAG.getNode(ISD::AND, dl, VT, SHL,
17176                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17177         }
17178         if (Op.getOpcode() == ISD::SRL) {
17179           // Make a large shift.
17180           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17181                                                    R, ShiftAmt, DAG);
17182           SRL = DAG.getBitcast(VT, SRL);
17183           // Zero out the leftmost bits.
17184           SmallVector<SDValue, 32> V(
17185               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17186           return DAG.getNode(ISD::AND, dl, VT, SRL,
17187                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17188         }
17189         if (Op.getOpcode() == ISD::SRA) {
17190           if (ShiftAmt == 7) {
17191             // R s>> 7  ===  R s< 0
17192             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17193             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17194           }
17195
17196           // R s>> a === ((R u>> a) ^ m) - m
17197           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17198           SmallVector<SDValue, 32> V(NumElts,
17199                                      DAG.getConstant(128 >> ShiftAmt, dl,
17200                                                      MVT::i8));
17201           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17202           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17203           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17204           return Res;
17205         }
17206         llvm_unreachable("Unknown shift opcode.");
17207       }
17208     }
17209   }
17210
17211   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17212   if (!Subtarget->is64Bit() &&
17213       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17214       Amt.getOpcode() == ISD::BITCAST &&
17215       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17216     Amt = Amt.getOperand(0);
17217     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17218                      VT.getVectorNumElements();
17219     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17220     uint64_t ShiftAmt = 0;
17221     for (unsigned i = 0; i != Ratio; ++i) {
17222       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17223       if (!C)
17224         return SDValue();
17225       // 6 == Log2(64)
17226       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17227     }
17228     // Check remaining shift amounts.
17229     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17230       uint64_t ShAmt = 0;
17231       for (unsigned j = 0; j != Ratio; ++j) {
17232         ConstantSDNode *C =
17233           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17234         if (!C)
17235           return SDValue();
17236         // 6 == Log2(64)
17237         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17238       }
17239       if (ShAmt != ShiftAmt)
17240         return SDValue();
17241     }
17242
17243     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17244       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17245
17246     if (Op.getOpcode() == ISD::SRA)
17247       return ArithmeticShiftRight64(ShiftAmt);
17248   }
17249
17250   return SDValue();
17251 }
17252
17253 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17254                                         const X86Subtarget* Subtarget) {
17255   MVT VT = Op.getSimpleValueType();
17256   SDLoc dl(Op);
17257   SDValue R = Op.getOperand(0);
17258   SDValue Amt = Op.getOperand(1);
17259
17260   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17261     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17262
17263   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17264     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17265
17266   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17267     SDValue BaseShAmt;
17268     EVT EltVT = VT.getVectorElementType();
17269
17270     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17271       // Check if this build_vector node is doing a splat.
17272       // If so, then set BaseShAmt equal to the splat value.
17273       BaseShAmt = BV->getSplatValue();
17274       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17275         BaseShAmt = SDValue();
17276     } else {
17277       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17278         Amt = Amt.getOperand(0);
17279
17280       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17281       if (SVN && SVN->isSplat()) {
17282         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17283         SDValue InVec = Amt.getOperand(0);
17284         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17285           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17286                  "Unexpected shuffle index found!");
17287           BaseShAmt = InVec.getOperand(SplatIdx);
17288         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17289            if (ConstantSDNode *C =
17290                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17291              if (C->getZExtValue() == SplatIdx)
17292                BaseShAmt = InVec.getOperand(1);
17293            }
17294         }
17295
17296         if (!BaseShAmt)
17297           // Avoid introducing an extract element from a shuffle.
17298           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17299                                   DAG.getIntPtrConstant(SplatIdx, dl));
17300       }
17301     }
17302
17303     if (BaseShAmt.getNode()) {
17304       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17305       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17306         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17307       else if (EltVT.bitsLT(MVT::i32))
17308         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17309
17310       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17311     }
17312   }
17313
17314   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17315   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17316       Amt.getOpcode() == ISD::BITCAST &&
17317       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17318     Amt = Amt.getOperand(0);
17319     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17320                      VT.getVectorNumElements();
17321     std::vector<SDValue> Vals(Ratio);
17322     for (unsigned i = 0; i != Ratio; ++i)
17323       Vals[i] = Amt.getOperand(i);
17324     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17325       for (unsigned j = 0; j != Ratio; ++j)
17326         if (Vals[j] != Amt.getOperand(i + j))
17327           return SDValue();
17328     }
17329
17330     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17331       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17332   }
17333   return SDValue();
17334 }
17335
17336 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17337                           SelectionDAG &DAG) {
17338   MVT VT = Op.getSimpleValueType();
17339   SDLoc dl(Op);
17340   SDValue R = Op.getOperand(0);
17341   SDValue Amt = Op.getOperand(1);
17342
17343   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17344   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17345
17346   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17347     return V;
17348
17349   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17350       return V;
17351
17352   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17353     return Op;
17354
17355   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17356   // shifts per-lane and then shuffle the partial results back together.
17357   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17358     // Splat the shift amounts so the scalar shifts above will catch it.
17359     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17360     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17361     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17362     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17363     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17364   }
17365
17366   // If possible, lower this packed shift into a vector multiply instead of
17367   // expanding it into a sequence of scalar shifts.
17368   // Do this only if the vector shift count is a constant build_vector.
17369   if (Op.getOpcode() == ISD::SHL &&
17370       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17371        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17372       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17373     SmallVector<SDValue, 8> Elts;
17374     EVT SVT = VT.getScalarType();
17375     unsigned SVTBits = SVT.getSizeInBits();
17376     const APInt &One = APInt(SVTBits, 1);
17377     unsigned NumElems = VT.getVectorNumElements();
17378
17379     for (unsigned i=0; i !=NumElems; ++i) {
17380       SDValue Op = Amt->getOperand(i);
17381       if (Op->getOpcode() == ISD::UNDEF) {
17382         Elts.push_back(Op);
17383         continue;
17384       }
17385
17386       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17387       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17388       uint64_t ShAmt = C.getZExtValue();
17389       if (ShAmt >= SVTBits) {
17390         Elts.push_back(DAG.getUNDEF(SVT));
17391         continue;
17392       }
17393       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17394     }
17395     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17396     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17397   }
17398
17399   // Lower SHL with variable shift amount.
17400   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17401     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17402
17403     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17404                      DAG.getConstant(0x3f800000U, dl, VT));
17405     Op = DAG.getBitcast(MVT::v4f32, Op);
17406     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17407     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17408   }
17409
17410   // If possible, lower this shift as a sequence of two shifts by
17411   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17412   // Example:
17413   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17414   //
17415   // Could be rewritten as:
17416   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17417   //
17418   // The advantage is that the two shifts from the example would be
17419   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17420   // the vector shift into four scalar shifts plus four pairs of vector
17421   // insert/extract.
17422   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17423       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17424     unsigned TargetOpcode = X86ISD::MOVSS;
17425     bool CanBeSimplified;
17426     // The splat value for the first packed shift (the 'X' from the example).
17427     SDValue Amt1 = Amt->getOperand(0);
17428     // The splat value for the second packed shift (the 'Y' from the example).
17429     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17430                                         Amt->getOperand(2);
17431
17432     // See if it is possible to replace this node with a sequence of
17433     // two shifts followed by a MOVSS/MOVSD
17434     if (VT == MVT::v4i32) {
17435       // Check if it is legal to use a MOVSS.
17436       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17437                         Amt2 == Amt->getOperand(3);
17438       if (!CanBeSimplified) {
17439         // Otherwise, check if we can still simplify this node using a MOVSD.
17440         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17441                           Amt->getOperand(2) == Amt->getOperand(3);
17442         TargetOpcode = X86ISD::MOVSD;
17443         Amt2 = Amt->getOperand(2);
17444       }
17445     } else {
17446       // Do similar checks for the case where the machine value type
17447       // is MVT::v8i16.
17448       CanBeSimplified = Amt1 == Amt->getOperand(1);
17449       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17450         CanBeSimplified = Amt2 == Amt->getOperand(i);
17451
17452       if (!CanBeSimplified) {
17453         TargetOpcode = X86ISD::MOVSD;
17454         CanBeSimplified = true;
17455         Amt2 = Amt->getOperand(4);
17456         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17457           CanBeSimplified = Amt1 == Amt->getOperand(i);
17458         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17459           CanBeSimplified = Amt2 == Amt->getOperand(j);
17460       }
17461     }
17462
17463     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17464         isa<ConstantSDNode>(Amt2)) {
17465       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17466       EVT CastVT = MVT::v4i32;
17467       SDValue Splat1 =
17468         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17469       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17470       SDValue Splat2 =
17471         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17472       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17473       if (TargetOpcode == X86ISD::MOVSD)
17474         CastVT = MVT::v2i64;
17475       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17476       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17477       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17478                                             BitCast1, DAG);
17479       return DAG.getBitcast(VT, Result);
17480     }
17481   }
17482
17483   // v4i32 Non Uniform Shifts.
17484   // If the shift amount is constant we can shift each lane using the SSE2
17485   // immediate shifts, else we need to zero-extend each lane to the lower i64
17486   // and shift using the SSE2 variable shifts.
17487   // The separate results can then be blended together.
17488   if (VT == MVT::v4i32) {
17489     unsigned Opc = Op.getOpcode();
17490     SDValue Amt0, Amt1, Amt2, Amt3;
17491     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17492       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17493       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17494       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17495       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17496     } else {
17497       // ISD::SHL is handled above but we include it here for completeness.
17498       switch (Opc) {
17499       default:
17500         llvm_unreachable("Unknown target vector shift node");
17501       case ISD::SHL:
17502         Opc = X86ISD::VSHL;
17503         break;
17504       case ISD::SRL:
17505         Opc = X86ISD::VSRL;
17506         break;
17507       case ISD::SRA:
17508         Opc = X86ISD::VSRA;
17509         break;
17510       }
17511       // The SSE2 shifts use the lower i64 as the same shift amount for
17512       // all lanes and the upper i64 is ignored. These shuffle masks
17513       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17514       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17515       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17516       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17517       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17518       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17519     }
17520
17521     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17522     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17523     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17524     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17525     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17526     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17527     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17528   }
17529
17530   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17531     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17532     unsigned ShiftOpcode = Op->getOpcode();
17533
17534     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17535       // On SSE41 targets we make use of the fact that VSELECT lowers
17536       // to PBLENDVB which selects bytes based just on the sign bit.
17537       if (Subtarget->hasSSE41()) {
17538         V0 = DAG.getBitcast(VT, V0);
17539         V1 = DAG.getBitcast(VT, V1);
17540         Sel = DAG.getBitcast(VT, Sel);
17541         return DAG.getBitcast(SelVT,
17542                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17543       }
17544       // On pre-SSE41 targets we test for the sign bit by comparing to
17545       // zero - a negative value will set all bits of the lanes to true
17546       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17547       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17548       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17549       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17550     };
17551
17552     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17553     // We can safely do this using i16 shifts as we're only interested in
17554     // the 3 lower bits of each byte.
17555     Amt = DAG.getBitcast(ExtVT, Amt);
17556     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17557     Amt = DAG.getBitcast(VT, Amt);
17558
17559     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17560       // r = VSELECT(r, shift(r, 4), a);
17561       SDValue M =
17562           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17563       R = SignBitSelect(VT, Amt, M, R);
17564
17565       // a += a
17566       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17567
17568       // r = VSELECT(r, shift(r, 2), a);
17569       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17570       R = SignBitSelect(VT, Amt, M, R);
17571
17572       // a += a
17573       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17574
17575       // return VSELECT(r, shift(r, 1), a);
17576       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17577       R = SignBitSelect(VT, Amt, M, R);
17578       return R;
17579     }
17580
17581     if (Op->getOpcode() == ISD::SRA) {
17582       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17583       // so we can correctly sign extend. We don't care what happens to the
17584       // lower byte.
17585       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17586       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17587       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17588       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17589       ALo = DAG.getBitcast(ExtVT, ALo);
17590       AHi = DAG.getBitcast(ExtVT, AHi);
17591       RLo = DAG.getBitcast(ExtVT, RLo);
17592       RHi = DAG.getBitcast(ExtVT, RHi);
17593
17594       // r = VSELECT(r, shift(r, 4), a);
17595       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17596                                 DAG.getConstant(4, dl, ExtVT));
17597       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17598                                 DAG.getConstant(4, dl, ExtVT));
17599       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17600       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17601
17602       // a += a
17603       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17604       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17605
17606       // r = VSELECT(r, shift(r, 2), a);
17607       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17608                         DAG.getConstant(2, dl, ExtVT));
17609       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17610                         DAG.getConstant(2, dl, ExtVT));
17611       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17612       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17613
17614       // a += a
17615       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17616       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17617
17618       // r = VSELECT(r, shift(r, 1), a);
17619       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17620                         DAG.getConstant(1, dl, ExtVT));
17621       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17622                         DAG.getConstant(1, dl, ExtVT));
17623       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17624       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17625
17626       // Logical shift the result back to the lower byte, leaving a zero upper
17627       // byte
17628       // meaning that we can safely pack with PACKUSWB.
17629       RLo =
17630           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17631       RHi =
17632           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17633       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17634     }
17635   }
17636
17637   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17638   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17639   // solution better.
17640   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17641     MVT ExtVT = MVT::v8i32;
17642     unsigned ExtOpc =
17643         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17644     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17645     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17646     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17647                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17648   }
17649
17650   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17651     MVT ExtVT = MVT::v8i32;
17652     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17653     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17654     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17655     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17656     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17657     ALo = DAG.getBitcast(ExtVT, ALo);
17658     AHi = DAG.getBitcast(ExtVT, AHi);
17659     RLo = DAG.getBitcast(ExtVT, RLo);
17660     RHi = DAG.getBitcast(ExtVT, RHi);
17661     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17662     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17663     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17664     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17665     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17666   }
17667
17668   if (VT == MVT::v8i16) {
17669     unsigned ShiftOpcode = Op->getOpcode();
17670
17671     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17672       // On SSE41 targets we make use of the fact that VSELECT lowers
17673       // to PBLENDVB which selects bytes based just on the sign bit.
17674       if (Subtarget->hasSSE41()) {
17675         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17676         V0 = DAG.getBitcast(ExtVT, V0);
17677         V1 = DAG.getBitcast(ExtVT, V1);
17678         Sel = DAG.getBitcast(ExtVT, Sel);
17679         return DAG.getBitcast(
17680             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17681       }
17682       // On pre-SSE41 targets we splat the sign bit - a negative value will
17683       // set all bits of the lanes to true and VSELECT uses that in
17684       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17685       SDValue C =
17686           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17687       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17688     };
17689
17690     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17691     if (Subtarget->hasSSE41()) {
17692       // On SSE41 targets we need to replicate the shift mask in both
17693       // bytes for PBLENDVB.
17694       Amt = DAG.getNode(
17695           ISD::OR, dl, VT,
17696           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17697           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17698     } else {
17699       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17700     }
17701
17702     // r = VSELECT(r, shift(r, 8), a);
17703     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17704     R = SignBitSelect(Amt, M, R);
17705
17706     // a += a
17707     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17708
17709     // r = VSELECT(r, shift(r, 4), a);
17710     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17711     R = SignBitSelect(Amt, M, R);
17712
17713     // a += a
17714     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17715
17716     // r = VSELECT(r, shift(r, 2), a);
17717     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17718     R = SignBitSelect(Amt, M, R);
17719
17720     // a += a
17721     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17722
17723     // return VSELECT(r, shift(r, 1), a);
17724     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17725     R = SignBitSelect(Amt, M, R);
17726     return R;
17727   }
17728
17729   // Decompose 256-bit shifts into smaller 128-bit shifts.
17730   if (VT.is256BitVector()) {
17731     unsigned NumElems = VT.getVectorNumElements();
17732     MVT EltVT = VT.getVectorElementType();
17733     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17734
17735     // Extract the two vectors
17736     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17737     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17738
17739     // Recreate the shift amount vectors
17740     SDValue Amt1, Amt2;
17741     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17742       // Constant shift amount
17743       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17744       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17745       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17746
17747       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17748       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17749     } else {
17750       // Variable shift amount
17751       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17752       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17753     }
17754
17755     // Issue new vector shifts for the smaller types
17756     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17757     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17758
17759     // Concatenate the result back
17760     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17761   }
17762
17763   return SDValue();
17764 }
17765
17766 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17767   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17768   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17769   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17770   // has only one use.
17771   SDNode *N = Op.getNode();
17772   SDValue LHS = N->getOperand(0);
17773   SDValue RHS = N->getOperand(1);
17774   unsigned BaseOp = 0;
17775   unsigned Cond = 0;
17776   SDLoc DL(Op);
17777   switch (Op.getOpcode()) {
17778   default: llvm_unreachable("Unknown ovf instruction!");
17779   case ISD::SADDO:
17780     // A subtract of one will be selected as a INC. Note that INC doesn't
17781     // set CF, so we can't do this for UADDO.
17782     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17783       if (C->isOne()) {
17784         BaseOp = X86ISD::INC;
17785         Cond = X86::COND_O;
17786         break;
17787       }
17788     BaseOp = X86ISD::ADD;
17789     Cond = X86::COND_O;
17790     break;
17791   case ISD::UADDO:
17792     BaseOp = X86ISD::ADD;
17793     Cond = X86::COND_B;
17794     break;
17795   case ISD::SSUBO:
17796     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17797     // set CF, so we can't do this for USUBO.
17798     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17799       if (C->isOne()) {
17800         BaseOp = X86ISD::DEC;
17801         Cond = X86::COND_O;
17802         break;
17803       }
17804     BaseOp = X86ISD::SUB;
17805     Cond = X86::COND_O;
17806     break;
17807   case ISD::USUBO:
17808     BaseOp = X86ISD::SUB;
17809     Cond = X86::COND_B;
17810     break;
17811   case ISD::SMULO:
17812     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17813     Cond = X86::COND_O;
17814     break;
17815   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17816     if (N->getValueType(0) == MVT::i8) {
17817       BaseOp = X86ISD::UMUL8;
17818       Cond = X86::COND_O;
17819       break;
17820     }
17821     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17822                                  MVT::i32);
17823     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17824
17825     SDValue SetCC =
17826       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17827                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17828                   SDValue(Sum.getNode(), 2));
17829
17830     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17831   }
17832   }
17833
17834   // Also sets EFLAGS.
17835   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17836   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17837
17838   SDValue SetCC =
17839     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17840                 DAG.getConstant(Cond, DL, MVT::i32),
17841                 SDValue(Sum.getNode(), 1));
17842
17843   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17844 }
17845
17846 /// Returns true if the operand type is exactly twice the native width, and
17847 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17848 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17849 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17850 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17851   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17852
17853   if (OpWidth == 64)
17854     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17855   else if (OpWidth == 128)
17856     return Subtarget->hasCmpxchg16b();
17857   else
17858     return false;
17859 }
17860
17861 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17862   return needsCmpXchgNb(SI->getValueOperand()->getType());
17863 }
17864
17865 // Note: this turns large loads into lock cmpxchg8b/16b.
17866 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17867 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17868   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17869   return needsCmpXchgNb(PTy->getElementType());
17870 }
17871
17872 TargetLoweringBase::AtomicRMWExpansionKind
17873 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17874   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17875   const Type *MemType = AI->getType();
17876
17877   // If the operand is too big, we must see if cmpxchg8/16b is available
17878   // and default to library calls otherwise.
17879   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17880     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17881                                    : AtomicRMWExpansionKind::None;
17882   }
17883
17884   AtomicRMWInst::BinOp Op = AI->getOperation();
17885   switch (Op) {
17886   default:
17887     llvm_unreachable("Unknown atomic operation");
17888   case AtomicRMWInst::Xchg:
17889   case AtomicRMWInst::Add:
17890   case AtomicRMWInst::Sub:
17891     // It's better to use xadd, xsub or xchg for these in all cases.
17892     return AtomicRMWExpansionKind::None;
17893   case AtomicRMWInst::Or:
17894   case AtomicRMWInst::And:
17895   case AtomicRMWInst::Xor:
17896     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17897     // prefix to a normal instruction for these operations.
17898     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17899                             : AtomicRMWExpansionKind::None;
17900   case AtomicRMWInst::Nand:
17901   case AtomicRMWInst::Max:
17902   case AtomicRMWInst::Min:
17903   case AtomicRMWInst::UMax:
17904   case AtomicRMWInst::UMin:
17905     // These always require a non-trivial set of data operations on x86. We must
17906     // use a cmpxchg loop.
17907     return AtomicRMWExpansionKind::CmpXChg;
17908   }
17909 }
17910
17911 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17912   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17913   // no-sse2). There isn't any reason to disable it if the target processor
17914   // supports it.
17915   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17916 }
17917
17918 LoadInst *
17919 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17920   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17921   const Type *MemType = AI->getType();
17922   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17923   // there is no benefit in turning such RMWs into loads, and it is actually
17924   // harmful as it introduces a mfence.
17925   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17926     return nullptr;
17927
17928   auto Builder = IRBuilder<>(AI);
17929   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17930   auto SynchScope = AI->getSynchScope();
17931   // We must restrict the ordering to avoid generating loads with Release or
17932   // ReleaseAcquire orderings.
17933   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17934   auto Ptr = AI->getPointerOperand();
17935
17936   // Before the load we need a fence. Here is an example lifted from
17937   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17938   // is required:
17939   // Thread 0:
17940   //   x.store(1, relaxed);
17941   //   r1 = y.fetch_add(0, release);
17942   // Thread 1:
17943   //   y.fetch_add(42, acquire);
17944   //   r2 = x.load(relaxed);
17945   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17946   // lowered to just a load without a fence. A mfence flushes the store buffer,
17947   // making the optimization clearly correct.
17948   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17949   // otherwise, we might be able to be more agressive on relaxed idempotent
17950   // rmw. In practice, they do not look useful, so we don't try to be
17951   // especially clever.
17952   if (SynchScope == SingleThread)
17953     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17954     // the IR level, so we must wrap it in an intrinsic.
17955     return nullptr;
17956
17957   if (!hasMFENCE(*Subtarget))
17958     // FIXME: it might make sense to use a locked operation here but on a
17959     // different cache-line to prevent cache-line bouncing. In practice it
17960     // is probably a small win, and x86 processors without mfence are rare
17961     // enough that we do not bother.
17962     return nullptr;
17963
17964   Function *MFence =
17965       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17966   Builder.CreateCall(MFence, {});
17967
17968   // Finally we can emit the atomic load.
17969   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17970           AI->getType()->getPrimitiveSizeInBits());
17971   Loaded->setAtomic(Order, SynchScope);
17972   AI->replaceAllUsesWith(Loaded);
17973   AI->eraseFromParent();
17974   return Loaded;
17975 }
17976
17977 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17978                                  SelectionDAG &DAG) {
17979   SDLoc dl(Op);
17980   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17981     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17982   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17983     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17984
17985   // The only fence that needs an instruction is a sequentially-consistent
17986   // cross-thread fence.
17987   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17988     if (hasMFENCE(*Subtarget))
17989       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17990
17991     SDValue Chain = Op.getOperand(0);
17992     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17993     SDValue Ops[] = {
17994       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17995       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17996       DAG.getRegister(0, MVT::i32),            // Index
17997       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17998       DAG.getRegister(0, MVT::i32),            // Segment.
17999       Zero,
18000       Chain
18001     };
18002     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18003     return SDValue(Res, 0);
18004   }
18005
18006   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18007   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18008 }
18009
18010 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18011                              SelectionDAG &DAG) {
18012   MVT T = Op.getSimpleValueType();
18013   SDLoc DL(Op);
18014   unsigned Reg = 0;
18015   unsigned size = 0;
18016   switch(T.SimpleTy) {
18017   default: llvm_unreachable("Invalid value type!");
18018   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18019   case MVT::i16: Reg = X86::AX;  size = 2; break;
18020   case MVT::i32: Reg = X86::EAX; size = 4; break;
18021   case MVT::i64:
18022     assert(Subtarget->is64Bit() && "Node not type legal!");
18023     Reg = X86::RAX; size = 8;
18024     break;
18025   }
18026   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18027                                   Op.getOperand(2), SDValue());
18028   SDValue Ops[] = { cpIn.getValue(0),
18029                     Op.getOperand(1),
18030                     Op.getOperand(3),
18031                     DAG.getTargetConstant(size, DL, MVT::i8),
18032                     cpIn.getValue(1) };
18033   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18034   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18035   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18036                                            Ops, T, MMO);
18037
18038   SDValue cpOut =
18039     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18040   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18041                                       MVT::i32, cpOut.getValue(2));
18042   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18043                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18044                                 EFLAGS);
18045
18046   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18047   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18048   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18049   return SDValue();
18050 }
18051
18052 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18053                             SelectionDAG &DAG) {
18054   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18055   MVT DstVT = Op.getSimpleValueType();
18056
18057   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18058     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18059     if (DstVT != MVT::f64)
18060       // This conversion needs to be expanded.
18061       return SDValue();
18062
18063     SDValue InVec = Op->getOperand(0);
18064     SDLoc dl(Op);
18065     unsigned NumElts = SrcVT.getVectorNumElements();
18066     EVT SVT = SrcVT.getVectorElementType();
18067
18068     // Widen the vector in input in the case of MVT::v2i32.
18069     // Example: from MVT::v2i32 to MVT::v4i32.
18070     SmallVector<SDValue, 16> Elts;
18071     for (unsigned i = 0, e = NumElts; i != e; ++i)
18072       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18073                                  DAG.getIntPtrConstant(i, dl)));
18074
18075     // Explicitly mark the extra elements as Undef.
18076     Elts.append(NumElts, DAG.getUNDEF(SVT));
18077
18078     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18079     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18080     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18081     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18082                        DAG.getIntPtrConstant(0, dl));
18083   }
18084
18085   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18086          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18087   assert((DstVT == MVT::i64 ||
18088           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18089          "Unexpected custom BITCAST");
18090   // i64 <=> MMX conversions are Legal.
18091   if (SrcVT==MVT::i64 && DstVT.isVector())
18092     return Op;
18093   if (DstVT==MVT::i64 && SrcVT.isVector())
18094     return Op;
18095   // MMX <=> MMX conversions are Legal.
18096   if (SrcVT.isVector() && DstVT.isVector())
18097     return Op;
18098   // All other conversions need to be expanded.
18099   return SDValue();
18100 }
18101
18102 /// Compute the horizontal sum of bytes in V for the elements of VT.
18103 ///
18104 /// Requires V to be a byte vector and VT to be an integer vector type with
18105 /// wider elements than V's type. The width of the elements of VT determines
18106 /// how many bytes of V are summed horizontally to produce each element of the
18107 /// result.
18108 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18109                                       const X86Subtarget *Subtarget,
18110                                       SelectionDAG &DAG) {
18111   SDLoc DL(V);
18112   MVT ByteVecVT = V.getSimpleValueType();
18113   MVT EltVT = VT.getVectorElementType();
18114   int NumElts = VT.getVectorNumElements();
18115   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18116          "Expected value to have byte element type.");
18117   assert(EltVT != MVT::i8 &&
18118          "Horizontal byte sum only makes sense for wider elements!");
18119   unsigned VecSize = VT.getSizeInBits();
18120   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18121
18122   // PSADBW instruction horizontally add all bytes and leave the result in i64
18123   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18124   if (EltVT == MVT::i64) {
18125     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18126     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18127     return DAG.getBitcast(VT, V);
18128   }
18129
18130   if (EltVT == MVT::i32) {
18131     // We unpack the low half and high half into i32s interleaved with zeros so
18132     // that we can use PSADBW to horizontally sum them. The most useful part of
18133     // this is that it lines up the results of two PSADBW instructions to be
18134     // two v2i64 vectors which concatenated are the 4 population counts. We can
18135     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18136     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18137     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18138     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18139
18140     // Do the horizontal sums into two v2i64s.
18141     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18142     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18143                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18144     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18145                        DAG.getBitcast(ByteVecVT, High), Zeros);
18146
18147     // Merge them together.
18148     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18149     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18150                     DAG.getBitcast(ShortVecVT, Low),
18151                     DAG.getBitcast(ShortVecVT, High));
18152
18153     return DAG.getBitcast(VT, V);
18154   }
18155
18156   // The only element type left is i16.
18157   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18158
18159   // To obtain pop count for each i16 element starting from the pop count for
18160   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18161   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18162   // directly supported.
18163   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18164   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18165   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18166   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18167                   DAG.getBitcast(ByteVecVT, V));
18168   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18169 }
18170
18171 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18172                                         const X86Subtarget *Subtarget,
18173                                         SelectionDAG &DAG) {
18174   MVT VT = Op.getSimpleValueType();
18175   MVT EltVT = VT.getVectorElementType();
18176   unsigned VecSize = VT.getSizeInBits();
18177
18178   // Implement a lookup table in register by using an algorithm based on:
18179   // http://wm.ite.pl/articles/sse-popcount.html
18180   //
18181   // The general idea is that every lower byte nibble in the input vector is an
18182   // index into a in-register pre-computed pop count table. We then split up the
18183   // input vector in two new ones: (1) a vector with only the shifted-right
18184   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18185   // masked out higher ones) for each byte. PSHUB is used separately with both
18186   // to index the in-register table. Next, both are added and the result is a
18187   // i8 vector where each element contains the pop count for input byte.
18188   //
18189   // To obtain the pop count for elements != i8, we follow up with the same
18190   // approach and use additional tricks as described below.
18191   //
18192   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18193                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18194                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18195                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18196
18197   int NumByteElts = VecSize / 8;
18198   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18199   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18200   SmallVector<SDValue, 16> LUTVec;
18201   for (int i = 0; i < NumByteElts; ++i)
18202     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18203   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18204   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18205                                   DAG.getConstant(0x0F, DL, MVT::i8));
18206   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18207
18208   // High nibbles
18209   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18210   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18211   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18212
18213   // Low nibbles
18214   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18215
18216   // The input vector is used as the shuffle mask that index elements into the
18217   // LUT. After counting low and high nibbles, add the vector to obtain the
18218   // final pop count per i8 element.
18219   SDValue HighPopCnt =
18220       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18221   SDValue LowPopCnt =
18222       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18223   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18224
18225   if (EltVT == MVT::i8)
18226     return PopCnt;
18227
18228   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18229 }
18230
18231 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18232                                        const X86Subtarget *Subtarget,
18233                                        SelectionDAG &DAG) {
18234   MVT VT = Op.getSimpleValueType();
18235   assert(VT.is128BitVector() &&
18236          "Only 128-bit vector bitmath lowering supported.");
18237
18238   int VecSize = VT.getSizeInBits();
18239   MVT EltVT = VT.getVectorElementType();
18240   int Len = EltVT.getSizeInBits();
18241
18242   // This is the vectorized version of the "best" algorithm from
18243   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18244   // with a minor tweak to use a series of adds + shifts instead of vector
18245   // multiplications. Implemented for all integer vector types. We only use
18246   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18247   // much faster, even faster than using native popcnt instructions.
18248
18249   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18250     MVT VT = V.getSimpleValueType();
18251     SmallVector<SDValue, 32> Shifters(
18252         VT.getVectorNumElements(),
18253         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18254     return DAG.getNode(OpCode, DL, VT, V,
18255                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18256   };
18257   auto GetMask = [&](SDValue V, APInt Mask) {
18258     MVT VT = V.getSimpleValueType();
18259     SmallVector<SDValue, 32> Masks(
18260         VT.getVectorNumElements(),
18261         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18262     return DAG.getNode(ISD::AND, DL, VT, V,
18263                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18264   };
18265
18266   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18267   // x86, so set the SRL type to have elements at least i16 wide. This is
18268   // correct because all of our SRLs are followed immediately by a mask anyways
18269   // that handles any bits that sneak into the high bits of the byte elements.
18270   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18271
18272   SDValue V = Op;
18273
18274   // v = v - ((v >> 1) & 0x55555555...)
18275   SDValue Srl =
18276       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18277   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18278   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18279
18280   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18281   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18282   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18283   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18284   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18285
18286   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18287   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18288   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18289   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18290
18291   // At this point, V contains the byte-wise population count, and we are
18292   // merely doing a horizontal sum if necessary to get the wider element
18293   // counts.
18294   if (EltVT == MVT::i8)
18295     return V;
18296
18297   return LowerHorizontalByteSum(
18298       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18299       DAG);
18300 }
18301
18302 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18303                                 SelectionDAG &DAG) {
18304   MVT VT = Op.getSimpleValueType();
18305   // FIXME: Need to add AVX-512 support here!
18306   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18307          "Unknown CTPOP type to handle");
18308   SDLoc DL(Op.getNode());
18309   SDValue Op0 = Op.getOperand(0);
18310
18311   if (!Subtarget->hasSSSE3()) {
18312     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18313     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18314     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18315   }
18316
18317   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18318     unsigned NumElems = VT.getVectorNumElements();
18319
18320     // Extract each 128-bit vector, compute pop count and concat the result.
18321     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18322     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18323
18324     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18325                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18326                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18327   }
18328
18329   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18330 }
18331
18332 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18333                           SelectionDAG &DAG) {
18334   assert(Op.getValueType().isVector() &&
18335          "We only do custom lowering for vector population count.");
18336   return LowerVectorCTPOP(Op, Subtarget, DAG);
18337 }
18338
18339 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18340   SDNode *Node = Op.getNode();
18341   SDLoc dl(Node);
18342   EVT T = Node->getValueType(0);
18343   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18344                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18345   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18346                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18347                        Node->getOperand(0),
18348                        Node->getOperand(1), negOp,
18349                        cast<AtomicSDNode>(Node)->getMemOperand(),
18350                        cast<AtomicSDNode>(Node)->getOrdering(),
18351                        cast<AtomicSDNode>(Node)->getSynchScope());
18352 }
18353
18354 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18355   SDNode *Node = Op.getNode();
18356   SDLoc dl(Node);
18357   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18358
18359   // Convert seq_cst store -> xchg
18360   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18361   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18362   //        (The only way to get a 16-byte store is cmpxchg16b)
18363   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18364   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18365       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18366     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18367                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18368                                  Node->getOperand(0),
18369                                  Node->getOperand(1), Node->getOperand(2),
18370                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18371                                  cast<AtomicSDNode>(Node)->getOrdering(),
18372                                  cast<AtomicSDNode>(Node)->getSynchScope());
18373     return Swap.getValue(1);
18374   }
18375   // Other atomic stores have a simple pattern.
18376   return Op;
18377 }
18378
18379 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18380   EVT VT = Op.getNode()->getSimpleValueType(0);
18381
18382   // Let legalize expand this if it isn't a legal type yet.
18383   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18384     return SDValue();
18385
18386   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18387
18388   unsigned Opc;
18389   bool ExtraOp = false;
18390   switch (Op.getOpcode()) {
18391   default: llvm_unreachable("Invalid code");
18392   case ISD::ADDC: Opc = X86ISD::ADD; break;
18393   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18394   case ISD::SUBC: Opc = X86ISD::SUB; break;
18395   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18396   }
18397
18398   if (!ExtraOp)
18399     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18400                        Op.getOperand(1));
18401   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18402                      Op.getOperand(1), Op.getOperand(2));
18403 }
18404
18405 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18406                             SelectionDAG &DAG) {
18407   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18408
18409   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18410   // which returns the values as { float, float } (in XMM0) or
18411   // { double, double } (which is returned in XMM0, XMM1).
18412   SDLoc dl(Op);
18413   SDValue Arg = Op.getOperand(0);
18414   EVT ArgVT = Arg.getValueType();
18415   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18416
18417   TargetLowering::ArgListTy Args;
18418   TargetLowering::ArgListEntry Entry;
18419
18420   Entry.Node = Arg;
18421   Entry.Ty = ArgTy;
18422   Entry.isSExt = false;
18423   Entry.isZExt = false;
18424   Args.push_back(Entry);
18425
18426   bool isF64 = ArgVT == MVT::f64;
18427   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18428   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18429   // the results are returned via SRet in memory.
18430   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18431   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18432   SDValue Callee =
18433       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18434
18435   Type *RetTy = isF64
18436     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18437     : (Type*)VectorType::get(ArgTy, 4);
18438
18439   TargetLowering::CallLoweringInfo CLI(DAG);
18440   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18441     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18442
18443   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18444
18445   if (isF64)
18446     // Returned in xmm0 and xmm1.
18447     return CallResult.first;
18448
18449   // Returned in bits 0:31 and 32:64 xmm0.
18450   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18451                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18452   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18453                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18454   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18455   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18456 }
18457
18458 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18459                              SelectionDAG &DAG) {
18460   assert(Subtarget->hasAVX512() &&
18461          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18462
18463   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18464   EVT VT = N->getValue().getValueType();
18465   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18466   SDLoc dl(Op);
18467
18468   // X86 scatter kills mask register, so its type should be added to
18469   // the list of return values
18470   if (N->getNumValues() == 1) {
18471     SDValue Index = N->getIndex();
18472     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18473         !Index.getValueType().is512BitVector())
18474       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18475
18476     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18477     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18478                       N->getOperand(3), Index };
18479
18480     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18481     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18482     return SDValue(NewScatter.getNode(), 0);
18483   }
18484   return Op;
18485 }
18486
18487 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18488                             SelectionDAG &DAG) {
18489   assert(Subtarget->hasAVX512() &&
18490          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18491
18492   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18493   EVT VT = Op.getValueType();
18494   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18495   SDLoc dl(Op);
18496
18497   SDValue Index = N->getIndex();
18498   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18499       !Index.getValueType().is512BitVector()) {
18500     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18501     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18502                       N->getOperand(3), Index };
18503     DAG.UpdateNodeOperands(N, Ops);
18504   }
18505   return Op;
18506 }
18507
18508 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18509                                                     SelectionDAG &DAG) const {
18510   // TODO: Eventually, the lowering of these nodes should be informed by or
18511   // deferred to the GC strategy for the function in which they appear. For
18512   // now, however, they must be lowered to something. Since they are logically
18513   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18514   // require special handling for these nodes), lower them as literal NOOPs for
18515   // the time being.
18516   SmallVector<SDValue, 2> Ops;
18517
18518   Ops.push_back(Op.getOperand(0));
18519   if (Op->getGluedNode())
18520     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18521
18522   SDLoc OpDL(Op);
18523   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18524   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18525
18526   return NOOP;
18527 }
18528
18529 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18530                                                   SelectionDAG &DAG) const {
18531   // TODO: Eventually, the lowering of these nodes should be informed by or
18532   // deferred to the GC strategy for the function in which they appear. For
18533   // now, however, they must be lowered to something. Since they are logically
18534   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18535   // require special handling for these nodes), lower them as literal NOOPs for
18536   // the time being.
18537   SmallVector<SDValue, 2> Ops;
18538
18539   Ops.push_back(Op.getOperand(0));
18540   if (Op->getGluedNode())
18541     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18542
18543   SDLoc OpDL(Op);
18544   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18545   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18546
18547   return NOOP;
18548 }
18549
18550 /// LowerOperation - Provide custom lowering hooks for some operations.
18551 ///
18552 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18553   switch (Op.getOpcode()) {
18554   default: llvm_unreachable("Should not custom lower this!");
18555   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18556   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18557     return LowerCMP_SWAP(Op, Subtarget, DAG);
18558   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18559   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18560   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18561   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18562   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18563   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18564   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18565   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18566   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18567   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18568   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18569   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18570   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18571   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18572   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18573   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18574   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18575   case ISD::SHL_PARTS:
18576   case ISD::SRA_PARTS:
18577   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18578   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18579   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18580   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18581   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18582   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18583   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18584   case ISD::SIGN_EXTEND_VECTOR_INREG:
18585     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18586   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18587   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18588   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18589   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18590   case ISD::FABS:
18591   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18592   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18593   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18594   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18595   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18596   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18597   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18598   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18599   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18600   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18601   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18602   case ISD::INTRINSIC_VOID:
18603   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18604   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18605   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18606   case ISD::FRAME_TO_ARGS_OFFSET:
18607                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18608   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18609   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18610   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18611   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18612   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18613   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18614   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18615   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18616   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18617   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18618   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18619   case ISD::UMUL_LOHI:
18620   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18621   case ISD::SRA:
18622   case ISD::SRL:
18623   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18624   case ISD::SADDO:
18625   case ISD::UADDO:
18626   case ISD::SSUBO:
18627   case ISD::USUBO:
18628   case ISD::SMULO:
18629   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18630   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18631   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18632   case ISD::ADDC:
18633   case ISD::ADDE:
18634   case ISD::SUBC:
18635   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18636   case ISD::ADD:                return LowerADD(Op, DAG);
18637   case ISD::SUB:                return LowerSUB(Op, DAG);
18638   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18639   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18640   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18641   case ISD::GC_TRANSITION_START:
18642                                 return LowerGC_TRANSITION_START(Op, DAG);
18643   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18644   }
18645 }
18646
18647 /// ReplaceNodeResults - Replace a node with an illegal result type
18648 /// with a new node built out of custom code.
18649 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18650                                            SmallVectorImpl<SDValue>&Results,
18651                                            SelectionDAG &DAG) const {
18652   SDLoc dl(N);
18653   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18654   switch (N->getOpcode()) {
18655   default:
18656     llvm_unreachable("Do not know how to custom type legalize this operation!");
18657   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18658   case X86ISD::FMINC:
18659   case X86ISD::FMIN:
18660   case X86ISD::FMAXC:
18661   case X86ISD::FMAX: {
18662     EVT VT = N->getValueType(0);
18663     if (VT != MVT::v2f32)
18664       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18665     SDValue UNDEF = DAG.getUNDEF(VT);
18666     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18667                               N->getOperand(0), UNDEF);
18668     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18669                               N->getOperand(1), UNDEF);
18670     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18671     return;
18672   }
18673   case ISD::SIGN_EXTEND_INREG:
18674   case ISD::ADDC:
18675   case ISD::ADDE:
18676   case ISD::SUBC:
18677   case ISD::SUBE:
18678     // We don't want to expand or promote these.
18679     return;
18680   case ISD::SDIV:
18681   case ISD::UDIV:
18682   case ISD::SREM:
18683   case ISD::UREM:
18684   case ISD::SDIVREM:
18685   case ISD::UDIVREM: {
18686     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18687     Results.push_back(V);
18688     return;
18689   }
18690   case ISD::FP_TO_SINT:
18691     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18692     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18693     if (N->getOperand(0).getValueType() == MVT::f16)
18694       break;
18695     // fallthrough
18696   case ISD::FP_TO_UINT: {
18697     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18698
18699     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18700       return;
18701
18702     std::pair<SDValue,SDValue> Vals =
18703         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18704     SDValue FIST = Vals.first, StackSlot = Vals.second;
18705     if (FIST.getNode()) {
18706       EVT VT = N->getValueType(0);
18707       // Return a load from the stack slot.
18708       if (StackSlot.getNode())
18709         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18710                                       MachinePointerInfo(),
18711                                       false, false, false, 0));
18712       else
18713         Results.push_back(FIST);
18714     }
18715     return;
18716   }
18717   case ISD::UINT_TO_FP: {
18718     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18719     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18720         N->getValueType(0) != MVT::v2f32)
18721       return;
18722     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18723                                  N->getOperand(0));
18724     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18725                                      MVT::f64);
18726     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18727     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18728                              DAG.getBitcast(MVT::v2i64, VBias));
18729     Or = DAG.getBitcast(MVT::v2f64, Or);
18730     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18731     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18732     return;
18733   }
18734   case ISD::FP_ROUND: {
18735     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18736         return;
18737     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18738     Results.push_back(V);
18739     return;
18740   }
18741   case ISD::FP_EXTEND: {
18742     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18743     // No other ValueType for FP_EXTEND should reach this point.
18744     assert(N->getValueType(0) == MVT::v2f32 &&
18745            "Do not know how to legalize this Node");
18746     return;
18747   }
18748   case ISD::INTRINSIC_W_CHAIN: {
18749     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18750     switch (IntNo) {
18751     default : llvm_unreachable("Do not know how to custom type "
18752                                "legalize this intrinsic operation!");
18753     case Intrinsic::x86_rdtsc:
18754       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18755                                      Results);
18756     case Intrinsic::x86_rdtscp:
18757       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18758                                      Results);
18759     case Intrinsic::x86_rdpmc:
18760       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18761     }
18762   }
18763   case ISD::READCYCLECOUNTER: {
18764     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18765                                    Results);
18766   }
18767   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18768     EVT T = N->getValueType(0);
18769     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18770     bool Regs64bit = T == MVT::i128;
18771     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18772     SDValue cpInL, cpInH;
18773     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18774                         DAG.getConstant(0, dl, HalfT));
18775     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18776                         DAG.getConstant(1, dl, HalfT));
18777     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18778                              Regs64bit ? X86::RAX : X86::EAX,
18779                              cpInL, SDValue());
18780     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18781                              Regs64bit ? X86::RDX : X86::EDX,
18782                              cpInH, cpInL.getValue(1));
18783     SDValue swapInL, swapInH;
18784     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18785                           DAG.getConstant(0, dl, HalfT));
18786     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18787                           DAG.getConstant(1, dl, HalfT));
18788     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18789                                Regs64bit ? X86::RBX : X86::EBX,
18790                                swapInL, cpInH.getValue(1));
18791     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18792                                Regs64bit ? X86::RCX : X86::ECX,
18793                                swapInH, swapInL.getValue(1));
18794     SDValue Ops[] = { swapInH.getValue(0),
18795                       N->getOperand(1),
18796                       swapInH.getValue(1) };
18797     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18798     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18799     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18800                                   X86ISD::LCMPXCHG8_DAG;
18801     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18802     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18803                                         Regs64bit ? X86::RAX : X86::EAX,
18804                                         HalfT, Result.getValue(1));
18805     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18806                                         Regs64bit ? X86::RDX : X86::EDX,
18807                                         HalfT, cpOutL.getValue(2));
18808     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18809
18810     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18811                                         MVT::i32, cpOutH.getValue(2));
18812     SDValue Success =
18813         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18814                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18815     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18816
18817     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18818     Results.push_back(Success);
18819     Results.push_back(EFLAGS.getValue(1));
18820     return;
18821   }
18822   case ISD::ATOMIC_SWAP:
18823   case ISD::ATOMIC_LOAD_ADD:
18824   case ISD::ATOMIC_LOAD_SUB:
18825   case ISD::ATOMIC_LOAD_AND:
18826   case ISD::ATOMIC_LOAD_OR:
18827   case ISD::ATOMIC_LOAD_XOR:
18828   case ISD::ATOMIC_LOAD_NAND:
18829   case ISD::ATOMIC_LOAD_MIN:
18830   case ISD::ATOMIC_LOAD_MAX:
18831   case ISD::ATOMIC_LOAD_UMIN:
18832   case ISD::ATOMIC_LOAD_UMAX:
18833   case ISD::ATOMIC_LOAD: {
18834     // Delegate to generic TypeLegalization. Situations we can really handle
18835     // should have already been dealt with by AtomicExpandPass.cpp.
18836     break;
18837   }
18838   case ISD::BITCAST: {
18839     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18840     EVT DstVT = N->getValueType(0);
18841     EVT SrcVT = N->getOperand(0)->getValueType(0);
18842
18843     if (SrcVT != MVT::f64 ||
18844         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18845       return;
18846
18847     unsigned NumElts = DstVT.getVectorNumElements();
18848     EVT SVT = DstVT.getVectorElementType();
18849     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18850     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18851                                    MVT::v2f64, N->getOperand(0));
18852     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18853
18854     if (ExperimentalVectorWideningLegalization) {
18855       // If we are legalizing vectors by widening, we already have the desired
18856       // legal vector type, just return it.
18857       Results.push_back(ToVecInt);
18858       return;
18859     }
18860
18861     SmallVector<SDValue, 8> Elts;
18862     for (unsigned i = 0, e = NumElts; i != e; ++i)
18863       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18864                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18865
18866     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18867   }
18868   }
18869 }
18870
18871 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18872   switch ((X86ISD::NodeType)Opcode) {
18873   case X86ISD::FIRST_NUMBER:       break;
18874   case X86ISD::BSF:                return "X86ISD::BSF";
18875   case X86ISD::BSR:                return "X86ISD::BSR";
18876   case X86ISD::SHLD:               return "X86ISD::SHLD";
18877   case X86ISD::SHRD:               return "X86ISD::SHRD";
18878   case X86ISD::FAND:               return "X86ISD::FAND";
18879   case X86ISD::FANDN:              return "X86ISD::FANDN";
18880   case X86ISD::FOR:                return "X86ISD::FOR";
18881   case X86ISD::FXOR:               return "X86ISD::FXOR";
18882   case X86ISD::FILD:               return "X86ISD::FILD";
18883   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18884   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18885   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18886   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18887   case X86ISD::FLD:                return "X86ISD::FLD";
18888   case X86ISD::FST:                return "X86ISD::FST";
18889   case X86ISD::CALL:               return "X86ISD::CALL";
18890   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18891   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18892   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18893   case X86ISD::BT:                 return "X86ISD::BT";
18894   case X86ISD::CMP:                return "X86ISD::CMP";
18895   case X86ISD::COMI:               return "X86ISD::COMI";
18896   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18897   case X86ISD::CMPM:               return "X86ISD::CMPM";
18898   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18899   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18900   case X86ISD::SETCC:              return "X86ISD::SETCC";
18901   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18902   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18903   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18904   case X86ISD::CMOV:               return "X86ISD::CMOV";
18905   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18906   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18907   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18908   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18909   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18910   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18911   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18912   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
18913   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
18914   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
18915   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
18916   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
18917   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
18918   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
18919   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
18920   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
18921   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
18922   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
18923   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
18924   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
18925   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
18926   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
18927   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
18928   case X86ISD::HADD:               return "X86ISD::HADD";
18929   case X86ISD::HSUB:               return "X86ISD::HSUB";
18930   case X86ISD::FHADD:              return "X86ISD::FHADD";
18931   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
18932   case X86ISD::ABS:                return "X86ISD::ABS";
18933   case X86ISD::FMAX:               return "X86ISD::FMAX";
18934   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
18935   case X86ISD::FMIN:               return "X86ISD::FMIN";
18936   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18937   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18938   case X86ISD::FMINC:              return "X86ISD::FMINC";
18939   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18940   case X86ISD::FRCP:               return "X86ISD::FRCP";
18941   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
18942   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
18943   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18944   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18945   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18946   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18947   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18948   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18949   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18950   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18951   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18952   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18953   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18954   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18955   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18956   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18957   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18958   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18959   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18960   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18961   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18962   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18963   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18964   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
18965   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
18966   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18967   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18968   case X86ISD::VSHL:               return "X86ISD::VSHL";
18969   case X86ISD::VSRL:               return "X86ISD::VSRL";
18970   case X86ISD::VSRA:               return "X86ISD::VSRA";
18971   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18972   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18973   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18974   case X86ISD::CMPP:               return "X86ISD::CMPP";
18975   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18976   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18977   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18978   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18979   case X86ISD::ADD:                return "X86ISD::ADD";
18980   case X86ISD::SUB:                return "X86ISD::SUB";
18981   case X86ISD::ADC:                return "X86ISD::ADC";
18982   case X86ISD::SBB:                return "X86ISD::SBB";
18983   case X86ISD::SMUL:               return "X86ISD::SMUL";
18984   case X86ISD::UMUL:               return "X86ISD::UMUL";
18985   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18986   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18987   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18988   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18989   case X86ISD::INC:                return "X86ISD::INC";
18990   case X86ISD::DEC:                return "X86ISD::DEC";
18991   case X86ISD::OR:                 return "X86ISD::OR";
18992   case X86ISD::XOR:                return "X86ISD::XOR";
18993   case X86ISD::AND:                return "X86ISD::AND";
18994   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18995   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18996   case X86ISD::PTEST:              return "X86ISD::PTEST";
18997   case X86ISD::TESTP:              return "X86ISD::TESTP";
18998   case X86ISD::TESTM:              return "X86ISD::TESTM";
18999   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19000   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19001   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19002   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19003   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19004   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19005   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19006   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19007   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19008   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19009   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19010   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19011   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19012   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19013   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19014   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19015   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19016   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19017   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19018   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19019   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19020   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19021   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19022   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19023   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19024   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19025   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19026   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19027   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19028   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19029   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19030   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19031   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19032   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19033   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19034   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19035   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19036   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19037   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19038   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19039   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19040   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19041   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19042   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19043   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19044   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19045   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19046   case X86ISD::SAHF:               return "X86ISD::SAHF";
19047   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19048   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19049   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19050   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19051   case X86ISD::FMADD:              return "X86ISD::FMADD";
19052   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19053   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19054   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19055   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19056   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19057   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19058   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19059   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19060   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19061   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19062   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19063   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19064   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19065   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19066   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19067   case X86ISD::XTEST:              return "X86ISD::XTEST";
19068   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19069   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19070   case X86ISD::SELECT:             return "X86ISD::SELECT";
19071   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19072   case X86ISD::RCP28:              return "X86ISD::RCP28";
19073   case X86ISD::EXP2:               return "X86ISD::EXP2";
19074   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19075   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19076   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19077   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19078   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19079   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19080   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19081   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19082   case X86ISD::ADDS:               return "X86ISD::ADDS";
19083   case X86ISD::SUBS:               return "X86ISD::SUBS";
19084   case X86ISD::AVG:                return "X86ISD::AVG";
19085   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19086   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19087   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19088   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19089   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19090   }
19091   return nullptr;
19092 }
19093
19094 // isLegalAddressingMode - Return true if the addressing mode represented
19095 // by AM is legal for this target, for a load/store of the specified type.
19096 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19097                                               const AddrMode &AM, Type *Ty,
19098                                               unsigned AS) const {
19099   // X86 supports extremely general addressing modes.
19100   CodeModel::Model M = getTargetMachine().getCodeModel();
19101   Reloc::Model R = getTargetMachine().getRelocationModel();
19102
19103   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19104   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19105     return false;
19106
19107   if (AM.BaseGV) {
19108     unsigned GVFlags =
19109       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19110
19111     // If a reference to this global requires an extra load, we can't fold it.
19112     if (isGlobalStubReference(GVFlags))
19113       return false;
19114
19115     // If BaseGV requires a register for the PIC base, we cannot also have a
19116     // BaseReg specified.
19117     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19118       return false;
19119
19120     // If lower 4G is not available, then we must use rip-relative addressing.
19121     if ((M != CodeModel::Small || R != Reloc::Static) &&
19122         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19123       return false;
19124   }
19125
19126   switch (AM.Scale) {
19127   case 0:
19128   case 1:
19129   case 2:
19130   case 4:
19131   case 8:
19132     // These scales always work.
19133     break;
19134   case 3:
19135   case 5:
19136   case 9:
19137     // These scales are formed with basereg+scalereg.  Only accept if there is
19138     // no basereg yet.
19139     if (AM.HasBaseReg)
19140       return false;
19141     break;
19142   default:  // Other stuff never works.
19143     return false;
19144   }
19145
19146   return true;
19147 }
19148
19149 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19150   unsigned Bits = Ty->getScalarSizeInBits();
19151
19152   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19153   // particularly cheaper than those without.
19154   if (Bits == 8)
19155     return false;
19156
19157   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19158   // variable shifts just as cheap as scalar ones.
19159   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19160     return false;
19161
19162   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19163   // fully general vector.
19164   return true;
19165 }
19166
19167 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19168   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19169     return false;
19170   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19171   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19172   return NumBits1 > NumBits2;
19173 }
19174
19175 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19176   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19177     return false;
19178
19179   if (!isTypeLegal(EVT::getEVT(Ty1)))
19180     return false;
19181
19182   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19183
19184   // Assuming the caller doesn't have a zeroext or signext return parameter,
19185   // truncation all the way down to i1 is valid.
19186   return true;
19187 }
19188
19189 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19190   return isInt<32>(Imm);
19191 }
19192
19193 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19194   // Can also use sub to handle negated immediates.
19195   return isInt<32>(Imm);
19196 }
19197
19198 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19199   if (!VT1.isInteger() || !VT2.isInteger())
19200     return false;
19201   unsigned NumBits1 = VT1.getSizeInBits();
19202   unsigned NumBits2 = VT2.getSizeInBits();
19203   return NumBits1 > NumBits2;
19204 }
19205
19206 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19207   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19208   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19209 }
19210
19211 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19212   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19213   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19214 }
19215
19216 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19217   EVT VT1 = Val.getValueType();
19218   if (isZExtFree(VT1, VT2))
19219     return true;
19220
19221   if (Val.getOpcode() != ISD::LOAD)
19222     return false;
19223
19224   if (!VT1.isSimple() || !VT1.isInteger() ||
19225       !VT2.isSimple() || !VT2.isInteger())
19226     return false;
19227
19228   switch (VT1.getSimpleVT().SimpleTy) {
19229   default: break;
19230   case MVT::i8:
19231   case MVT::i16:
19232   case MVT::i32:
19233     // X86 has 8, 16, and 32-bit zero-extending loads.
19234     return true;
19235   }
19236
19237   return false;
19238 }
19239
19240 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19241
19242 bool
19243 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19244   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19245     return false;
19246
19247   VT = VT.getScalarType();
19248
19249   if (!VT.isSimple())
19250     return false;
19251
19252   switch (VT.getSimpleVT().SimpleTy) {
19253   case MVT::f32:
19254   case MVT::f64:
19255     return true;
19256   default:
19257     break;
19258   }
19259
19260   return false;
19261 }
19262
19263 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19264   // i16 instructions are longer (0x66 prefix) and potentially slower.
19265   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19266 }
19267
19268 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19269 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19270 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19271 /// are assumed to be legal.
19272 bool
19273 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19274                                       EVT VT) const {
19275   if (!VT.isSimple())
19276     return false;
19277
19278   // Not for i1 vectors
19279   if (VT.getScalarType() == MVT::i1)
19280     return false;
19281
19282   // Very little shuffling can be done for 64-bit vectors right now.
19283   if (VT.getSizeInBits() == 64)
19284     return false;
19285
19286   // We only care that the types being shuffled are legal. The lowering can
19287   // handle any possible shuffle mask that results.
19288   return isTypeLegal(VT.getSimpleVT());
19289 }
19290
19291 bool
19292 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19293                                           EVT VT) const {
19294   // Just delegate to the generic legality, clear masks aren't special.
19295   return isShuffleMaskLegal(Mask, VT);
19296 }
19297
19298 //===----------------------------------------------------------------------===//
19299 //                           X86 Scheduler Hooks
19300 //===----------------------------------------------------------------------===//
19301
19302 /// Utility function to emit xbegin specifying the start of an RTM region.
19303 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19304                                      const TargetInstrInfo *TII) {
19305   DebugLoc DL = MI->getDebugLoc();
19306
19307   const BasicBlock *BB = MBB->getBasicBlock();
19308   MachineFunction::iterator I = MBB;
19309   ++I;
19310
19311   // For the v = xbegin(), we generate
19312   //
19313   // thisMBB:
19314   //  xbegin sinkMBB
19315   //
19316   // mainMBB:
19317   //  eax = -1
19318   //
19319   // sinkMBB:
19320   //  v = eax
19321
19322   MachineBasicBlock *thisMBB = MBB;
19323   MachineFunction *MF = MBB->getParent();
19324   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19325   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19326   MF->insert(I, mainMBB);
19327   MF->insert(I, sinkMBB);
19328
19329   // Transfer the remainder of BB and its successor edges to sinkMBB.
19330   sinkMBB->splice(sinkMBB->begin(), MBB,
19331                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19332   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19333
19334   // thisMBB:
19335   //  xbegin sinkMBB
19336   //  # fallthrough to mainMBB
19337   //  # abortion to sinkMBB
19338   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19339   thisMBB->addSuccessor(mainMBB);
19340   thisMBB->addSuccessor(sinkMBB);
19341
19342   // mainMBB:
19343   //  EAX = -1
19344   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19345   mainMBB->addSuccessor(sinkMBB);
19346
19347   // sinkMBB:
19348   // EAX is live into the sinkMBB
19349   sinkMBB->addLiveIn(X86::EAX);
19350   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19351           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19352     .addReg(X86::EAX);
19353
19354   MI->eraseFromParent();
19355   return sinkMBB;
19356 }
19357
19358 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19359 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19360 // in the .td file.
19361 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19362                                        const TargetInstrInfo *TII) {
19363   unsigned Opc;
19364   switch (MI->getOpcode()) {
19365   default: llvm_unreachable("illegal opcode!");
19366   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19367   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19368   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19369   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19370   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19371   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19372   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19373   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19374   }
19375
19376   DebugLoc dl = MI->getDebugLoc();
19377   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19378
19379   unsigned NumArgs = MI->getNumOperands();
19380   for (unsigned i = 1; i < NumArgs; ++i) {
19381     MachineOperand &Op = MI->getOperand(i);
19382     if (!(Op.isReg() && Op.isImplicit()))
19383       MIB.addOperand(Op);
19384   }
19385   if (MI->hasOneMemOperand())
19386     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19387
19388   BuildMI(*BB, MI, dl,
19389     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19390     .addReg(X86::XMM0);
19391
19392   MI->eraseFromParent();
19393   return BB;
19394 }
19395
19396 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19397 // defs in an instruction pattern
19398 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19399                                        const TargetInstrInfo *TII) {
19400   unsigned Opc;
19401   switch (MI->getOpcode()) {
19402   default: llvm_unreachable("illegal opcode!");
19403   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19404   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19405   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19406   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19407   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19408   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19409   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19410   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19411   }
19412
19413   DebugLoc dl = MI->getDebugLoc();
19414   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19415
19416   unsigned NumArgs = MI->getNumOperands(); // remove the results
19417   for (unsigned i = 1; i < NumArgs; ++i) {
19418     MachineOperand &Op = MI->getOperand(i);
19419     if (!(Op.isReg() && Op.isImplicit()))
19420       MIB.addOperand(Op);
19421   }
19422   if (MI->hasOneMemOperand())
19423     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19424
19425   BuildMI(*BB, MI, dl,
19426     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19427     .addReg(X86::ECX);
19428
19429   MI->eraseFromParent();
19430   return BB;
19431 }
19432
19433 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19434                                       const X86Subtarget *Subtarget) {
19435   DebugLoc dl = MI->getDebugLoc();
19436   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19437   // Address into RAX/EAX, other two args into ECX, EDX.
19438   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19439   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19440   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19441   for (int i = 0; i < X86::AddrNumOperands; ++i)
19442     MIB.addOperand(MI->getOperand(i));
19443
19444   unsigned ValOps = X86::AddrNumOperands;
19445   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19446     .addReg(MI->getOperand(ValOps).getReg());
19447   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19448     .addReg(MI->getOperand(ValOps+1).getReg());
19449
19450   // The instruction doesn't actually take any operands though.
19451   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19452
19453   MI->eraseFromParent(); // The pseudo is gone now.
19454   return BB;
19455 }
19456
19457 MachineBasicBlock *
19458 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19459                                                  MachineBasicBlock *MBB) const {
19460   // Emit va_arg instruction on X86-64.
19461
19462   // Operands to this pseudo-instruction:
19463   // 0  ) Output        : destination address (reg)
19464   // 1-5) Input         : va_list address (addr, i64mem)
19465   // 6  ) ArgSize       : Size (in bytes) of vararg type
19466   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19467   // 8  ) Align         : Alignment of type
19468   // 9  ) EFLAGS (implicit-def)
19469
19470   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19471   static_assert(X86::AddrNumOperands == 5,
19472                 "VAARG_64 assumes 5 address operands");
19473
19474   unsigned DestReg = MI->getOperand(0).getReg();
19475   MachineOperand &Base = MI->getOperand(1);
19476   MachineOperand &Scale = MI->getOperand(2);
19477   MachineOperand &Index = MI->getOperand(3);
19478   MachineOperand &Disp = MI->getOperand(4);
19479   MachineOperand &Segment = MI->getOperand(5);
19480   unsigned ArgSize = MI->getOperand(6).getImm();
19481   unsigned ArgMode = MI->getOperand(7).getImm();
19482   unsigned Align = MI->getOperand(8).getImm();
19483
19484   // Memory Reference
19485   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19486   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19487   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19488
19489   // Machine Information
19490   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19491   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19492   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19493   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19494   DebugLoc DL = MI->getDebugLoc();
19495
19496   // struct va_list {
19497   //   i32   gp_offset
19498   //   i32   fp_offset
19499   //   i64   overflow_area (address)
19500   //   i64   reg_save_area (address)
19501   // }
19502   // sizeof(va_list) = 24
19503   // alignment(va_list) = 8
19504
19505   unsigned TotalNumIntRegs = 6;
19506   unsigned TotalNumXMMRegs = 8;
19507   bool UseGPOffset = (ArgMode == 1);
19508   bool UseFPOffset = (ArgMode == 2);
19509   unsigned MaxOffset = TotalNumIntRegs * 8 +
19510                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19511
19512   /* Align ArgSize to a multiple of 8 */
19513   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19514   bool NeedsAlign = (Align > 8);
19515
19516   MachineBasicBlock *thisMBB = MBB;
19517   MachineBasicBlock *overflowMBB;
19518   MachineBasicBlock *offsetMBB;
19519   MachineBasicBlock *endMBB;
19520
19521   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19522   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19523   unsigned OffsetReg = 0;
19524
19525   if (!UseGPOffset && !UseFPOffset) {
19526     // If we only pull from the overflow region, we don't create a branch.
19527     // We don't need to alter control flow.
19528     OffsetDestReg = 0; // unused
19529     OverflowDestReg = DestReg;
19530
19531     offsetMBB = nullptr;
19532     overflowMBB = thisMBB;
19533     endMBB = thisMBB;
19534   } else {
19535     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19536     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19537     // If not, pull from overflow_area. (branch to overflowMBB)
19538     //
19539     //       thisMBB
19540     //         |     .
19541     //         |        .
19542     //     offsetMBB   overflowMBB
19543     //         |        .
19544     //         |     .
19545     //        endMBB
19546
19547     // Registers for the PHI in endMBB
19548     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19549     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19550
19551     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19552     MachineFunction *MF = MBB->getParent();
19553     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19554     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19555     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19556
19557     MachineFunction::iterator MBBIter = MBB;
19558     ++MBBIter;
19559
19560     // Insert the new basic blocks
19561     MF->insert(MBBIter, offsetMBB);
19562     MF->insert(MBBIter, overflowMBB);
19563     MF->insert(MBBIter, endMBB);
19564
19565     // Transfer the remainder of MBB and its successor edges to endMBB.
19566     endMBB->splice(endMBB->begin(), thisMBB,
19567                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19568     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19569
19570     // Make offsetMBB and overflowMBB successors of thisMBB
19571     thisMBB->addSuccessor(offsetMBB);
19572     thisMBB->addSuccessor(overflowMBB);
19573
19574     // endMBB is a successor of both offsetMBB and overflowMBB
19575     offsetMBB->addSuccessor(endMBB);
19576     overflowMBB->addSuccessor(endMBB);
19577
19578     // Load the offset value into a register
19579     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19580     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19581       .addOperand(Base)
19582       .addOperand(Scale)
19583       .addOperand(Index)
19584       .addDisp(Disp, UseFPOffset ? 4 : 0)
19585       .addOperand(Segment)
19586       .setMemRefs(MMOBegin, MMOEnd);
19587
19588     // Check if there is enough room left to pull this argument.
19589     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19590       .addReg(OffsetReg)
19591       .addImm(MaxOffset + 8 - ArgSizeA8);
19592
19593     // Branch to "overflowMBB" if offset >= max
19594     // Fall through to "offsetMBB" otherwise
19595     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19596       .addMBB(overflowMBB);
19597   }
19598
19599   // In offsetMBB, emit code to use the reg_save_area.
19600   if (offsetMBB) {
19601     assert(OffsetReg != 0);
19602
19603     // Read the reg_save_area address.
19604     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19605     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19606       .addOperand(Base)
19607       .addOperand(Scale)
19608       .addOperand(Index)
19609       .addDisp(Disp, 16)
19610       .addOperand(Segment)
19611       .setMemRefs(MMOBegin, MMOEnd);
19612
19613     // Zero-extend the offset
19614     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19615       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19616         .addImm(0)
19617         .addReg(OffsetReg)
19618         .addImm(X86::sub_32bit);
19619
19620     // Add the offset to the reg_save_area to get the final address.
19621     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19622       .addReg(OffsetReg64)
19623       .addReg(RegSaveReg);
19624
19625     // Compute the offset for the next argument
19626     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19627     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19628       .addReg(OffsetReg)
19629       .addImm(UseFPOffset ? 16 : 8);
19630
19631     // Store it back into the va_list.
19632     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19633       .addOperand(Base)
19634       .addOperand(Scale)
19635       .addOperand(Index)
19636       .addDisp(Disp, UseFPOffset ? 4 : 0)
19637       .addOperand(Segment)
19638       .addReg(NextOffsetReg)
19639       .setMemRefs(MMOBegin, MMOEnd);
19640
19641     // Jump to endMBB
19642     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19643       .addMBB(endMBB);
19644   }
19645
19646   //
19647   // Emit code to use overflow area
19648   //
19649
19650   // Load the overflow_area address into a register.
19651   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19652   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19653     .addOperand(Base)
19654     .addOperand(Scale)
19655     .addOperand(Index)
19656     .addDisp(Disp, 8)
19657     .addOperand(Segment)
19658     .setMemRefs(MMOBegin, MMOEnd);
19659
19660   // If we need to align it, do so. Otherwise, just copy the address
19661   // to OverflowDestReg.
19662   if (NeedsAlign) {
19663     // Align the overflow address
19664     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19665     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19666
19667     // aligned_addr = (addr + (align-1)) & ~(align-1)
19668     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19669       .addReg(OverflowAddrReg)
19670       .addImm(Align-1);
19671
19672     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19673       .addReg(TmpReg)
19674       .addImm(~(uint64_t)(Align-1));
19675   } else {
19676     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19677       .addReg(OverflowAddrReg);
19678   }
19679
19680   // Compute the next overflow address after this argument.
19681   // (the overflow address should be kept 8-byte aligned)
19682   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19683   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19684     .addReg(OverflowDestReg)
19685     .addImm(ArgSizeA8);
19686
19687   // Store the new overflow address.
19688   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19689     .addOperand(Base)
19690     .addOperand(Scale)
19691     .addOperand(Index)
19692     .addDisp(Disp, 8)
19693     .addOperand(Segment)
19694     .addReg(NextAddrReg)
19695     .setMemRefs(MMOBegin, MMOEnd);
19696
19697   // If we branched, emit the PHI to the front of endMBB.
19698   if (offsetMBB) {
19699     BuildMI(*endMBB, endMBB->begin(), DL,
19700             TII->get(X86::PHI), DestReg)
19701       .addReg(OffsetDestReg).addMBB(offsetMBB)
19702       .addReg(OverflowDestReg).addMBB(overflowMBB);
19703   }
19704
19705   // Erase the pseudo instruction
19706   MI->eraseFromParent();
19707
19708   return endMBB;
19709 }
19710
19711 MachineBasicBlock *
19712 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19713                                                  MachineInstr *MI,
19714                                                  MachineBasicBlock *MBB) const {
19715   // Emit code to save XMM registers to the stack. The ABI says that the
19716   // number of registers to save is given in %al, so it's theoretically
19717   // possible to do an indirect jump trick to avoid saving all of them,
19718   // however this code takes a simpler approach and just executes all
19719   // of the stores if %al is non-zero. It's less code, and it's probably
19720   // easier on the hardware branch predictor, and stores aren't all that
19721   // expensive anyway.
19722
19723   // Create the new basic blocks. One block contains all the XMM stores,
19724   // and one block is the final destination regardless of whether any
19725   // stores were performed.
19726   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19727   MachineFunction *F = MBB->getParent();
19728   MachineFunction::iterator MBBIter = MBB;
19729   ++MBBIter;
19730   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19731   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19732   F->insert(MBBIter, XMMSaveMBB);
19733   F->insert(MBBIter, EndMBB);
19734
19735   // Transfer the remainder of MBB and its successor edges to EndMBB.
19736   EndMBB->splice(EndMBB->begin(), MBB,
19737                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19738   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19739
19740   // The original block will now fall through to the XMM save block.
19741   MBB->addSuccessor(XMMSaveMBB);
19742   // The XMMSaveMBB will fall through to the end block.
19743   XMMSaveMBB->addSuccessor(EndMBB);
19744
19745   // Now add the instructions.
19746   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19747   DebugLoc DL = MI->getDebugLoc();
19748
19749   unsigned CountReg = MI->getOperand(0).getReg();
19750   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19751   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19752
19753   if (!Subtarget->isTargetWin64()) {
19754     // If %al is 0, branch around the XMM save block.
19755     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19756     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19757     MBB->addSuccessor(EndMBB);
19758   }
19759
19760   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19761   // that was just emitted, but clearly shouldn't be "saved".
19762   assert((MI->getNumOperands() <= 3 ||
19763           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19764           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19765          && "Expected last argument to be EFLAGS");
19766   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19767   // In the XMM save block, save all the XMM argument registers.
19768   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19769     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19770     MachineMemOperand *MMO =
19771       F->getMachineMemOperand(
19772           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19773         MachineMemOperand::MOStore,
19774         /*Size=*/16, /*Align=*/16);
19775     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19776       .addFrameIndex(RegSaveFrameIndex)
19777       .addImm(/*Scale=*/1)
19778       .addReg(/*IndexReg=*/0)
19779       .addImm(/*Disp=*/Offset)
19780       .addReg(/*Segment=*/0)
19781       .addReg(MI->getOperand(i).getReg())
19782       .addMemOperand(MMO);
19783   }
19784
19785   MI->eraseFromParent();   // The pseudo instruction is gone now.
19786
19787   return EndMBB;
19788 }
19789
19790 // The EFLAGS operand of SelectItr might be missing a kill marker
19791 // because there were multiple uses of EFLAGS, and ISel didn't know
19792 // which to mark. Figure out whether SelectItr should have had a
19793 // kill marker, and set it if it should. Returns the correct kill
19794 // marker value.
19795 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19796                                      MachineBasicBlock* BB,
19797                                      const TargetRegisterInfo* TRI) {
19798   // Scan forward through BB for a use/def of EFLAGS.
19799   MachineBasicBlock::iterator miI(std::next(SelectItr));
19800   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19801     const MachineInstr& mi = *miI;
19802     if (mi.readsRegister(X86::EFLAGS))
19803       return false;
19804     if (mi.definesRegister(X86::EFLAGS))
19805       break; // Should have kill-flag - update below.
19806   }
19807
19808   // If we hit the end of the block, check whether EFLAGS is live into a
19809   // successor.
19810   if (miI == BB->end()) {
19811     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19812                                           sEnd = BB->succ_end();
19813          sItr != sEnd; ++sItr) {
19814       MachineBasicBlock* succ = *sItr;
19815       if (succ->isLiveIn(X86::EFLAGS))
19816         return false;
19817     }
19818   }
19819
19820   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19821   // out. SelectMI should have a kill flag on EFLAGS.
19822   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19823   return true;
19824 }
19825
19826 MachineBasicBlock *
19827 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19828                                      MachineBasicBlock *BB) const {
19829   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19830   DebugLoc DL = MI->getDebugLoc();
19831
19832   // To "insert" a SELECT_CC instruction, we actually have to insert the
19833   // diamond control-flow pattern.  The incoming instruction knows the
19834   // destination vreg to set, the condition code register to branch on, the
19835   // true/false values to select between, and a branch opcode to use.
19836   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19837   MachineFunction::iterator It = BB;
19838   ++It;
19839
19840   //  thisMBB:
19841   //  ...
19842   //   TrueVal = ...
19843   //   cmpTY ccX, r1, r2
19844   //   bCC copy1MBB
19845   //   fallthrough --> copy0MBB
19846   MachineBasicBlock *thisMBB = BB;
19847   MachineFunction *F = BB->getParent();
19848
19849   // We also lower double CMOVs:
19850   //   (CMOV (CMOV F, T, cc1), T, cc2)
19851   // to two successives branches.  For that, we look for another CMOV as the
19852   // following instruction.
19853   //
19854   // Without this, we would add a PHI between the two jumps, which ends up
19855   // creating a few copies all around. For instance, for
19856   //
19857   //    (sitofp (zext (fcmp une)))
19858   //
19859   // we would generate:
19860   //
19861   //         ucomiss %xmm1, %xmm0
19862   //         movss  <1.0f>, %xmm0
19863   //         movaps  %xmm0, %xmm1
19864   //         jne     .LBB5_2
19865   //         xorps   %xmm1, %xmm1
19866   // .LBB5_2:
19867   //         jp      .LBB5_4
19868   //         movaps  %xmm1, %xmm0
19869   // .LBB5_4:
19870   //         retq
19871   //
19872   // because this custom-inserter would have generated:
19873   //
19874   //   A
19875   //   | \
19876   //   |  B
19877   //   | /
19878   //   C
19879   //   | \
19880   //   |  D
19881   //   | /
19882   //   E
19883   //
19884   // A: X = ...; Y = ...
19885   // B: empty
19886   // C: Z = PHI [X, A], [Y, B]
19887   // D: empty
19888   // E: PHI [X, C], [Z, D]
19889   //
19890   // If we lower both CMOVs in a single step, we can instead generate:
19891   //
19892   //   A
19893   //   | \
19894   //   |  C
19895   //   | /|
19896   //   |/ |
19897   //   |  |
19898   //   |  D
19899   //   | /
19900   //   E
19901   //
19902   // A: X = ...; Y = ...
19903   // D: empty
19904   // E: PHI [X, A], [X, C], [Y, D]
19905   //
19906   // Which, in our sitofp/fcmp example, gives us something like:
19907   //
19908   //         ucomiss %xmm1, %xmm0
19909   //         movss  <1.0f>, %xmm0
19910   //         jne     .LBB5_4
19911   //         jp      .LBB5_4
19912   //         xorps   %xmm0, %xmm0
19913   // .LBB5_4:
19914   //         retq
19915   //
19916   MachineInstr *NextCMOV = nullptr;
19917   MachineBasicBlock::iterator NextMIIt =
19918       std::next(MachineBasicBlock::iterator(MI));
19919   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19920       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19921       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19922     NextCMOV = &*NextMIIt;
19923
19924   MachineBasicBlock *jcc1MBB = nullptr;
19925
19926   // If we have a double CMOV, we lower it to two successive branches to
19927   // the same block.  EFLAGS is used by both, so mark it as live in the second.
19928   if (NextCMOV) {
19929     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19930     F->insert(It, jcc1MBB);
19931     jcc1MBB->addLiveIn(X86::EFLAGS);
19932   }
19933
19934   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19935   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19936   F->insert(It, copy0MBB);
19937   F->insert(It, sinkMBB);
19938
19939   // If the EFLAGS register isn't dead in the terminator, then claim that it's
19940   // live into the sink and copy blocks.
19941   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19942
19943   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19944   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19945       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19946     copy0MBB->addLiveIn(X86::EFLAGS);
19947     sinkMBB->addLiveIn(X86::EFLAGS);
19948   }
19949
19950   // Transfer the remainder of BB and its successor edges to sinkMBB.
19951   sinkMBB->splice(sinkMBB->begin(), BB,
19952                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
19953   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19954
19955   // Add the true and fallthrough blocks as its successors.
19956   if (NextCMOV) {
19957     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19958     BB->addSuccessor(jcc1MBB);
19959
19960     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19961     // jump to the sinkMBB.
19962     jcc1MBB->addSuccessor(copy0MBB);
19963     jcc1MBB->addSuccessor(sinkMBB);
19964   } else {
19965     BB->addSuccessor(copy0MBB);
19966   }
19967
19968   // The true block target of the first (or only) branch is always sinkMBB.
19969   BB->addSuccessor(sinkMBB);
19970
19971   // Create the conditional branch instruction.
19972   unsigned Opc =
19973     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19974   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19975
19976   if (NextCMOV) {
19977     unsigned Opc2 = X86::GetCondBranchFromCond(
19978         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19979     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19980   }
19981
19982   //  copy0MBB:
19983   //   %FalseValue = ...
19984   //   # fallthrough to sinkMBB
19985   copy0MBB->addSuccessor(sinkMBB);
19986
19987   //  sinkMBB:
19988   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19989   //  ...
19990   MachineInstrBuilder MIB =
19991       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19992               MI->getOperand(0).getReg())
19993           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19994           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19995
19996   // If we have a double CMOV, the second Jcc provides the same incoming
19997   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19998   if (NextCMOV) {
19999     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20000     // Copy the PHI result to the register defined by the second CMOV.
20001     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20002             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
20003         .addReg(MI->getOperand(0).getReg());
20004     NextCMOV->eraseFromParent();
20005   }
20006
20007   MI->eraseFromParent();   // The pseudo instruction is gone now.
20008   return sinkMBB;
20009 }
20010
20011 MachineBasicBlock *
20012 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20013                                         MachineBasicBlock *BB) const {
20014   MachineFunction *MF = BB->getParent();
20015   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20016   DebugLoc DL = MI->getDebugLoc();
20017   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20018
20019   assert(MF->shouldSplitStack());
20020
20021   const bool Is64Bit = Subtarget->is64Bit();
20022   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20023
20024   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20025   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20026
20027   // BB:
20028   //  ... [Till the alloca]
20029   // If stacklet is not large enough, jump to mallocMBB
20030   //
20031   // bumpMBB:
20032   //  Allocate by subtracting from RSP
20033   //  Jump to continueMBB
20034   //
20035   // mallocMBB:
20036   //  Allocate by call to runtime
20037   //
20038   // continueMBB:
20039   //  ...
20040   //  [rest of original BB]
20041   //
20042
20043   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20044   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20045   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20046
20047   MachineRegisterInfo &MRI = MF->getRegInfo();
20048   const TargetRegisterClass *AddrRegClass =
20049       getRegClassFor(getPointerTy(MF->getDataLayout()));
20050
20051   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20052     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20053     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20054     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20055     sizeVReg = MI->getOperand(1).getReg(),
20056     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20057
20058   MachineFunction::iterator MBBIter = BB;
20059   ++MBBIter;
20060
20061   MF->insert(MBBIter, bumpMBB);
20062   MF->insert(MBBIter, mallocMBB);
20063   MF->insert(MBBIter, continueMBB);
20064
20065   continueMBB->splice(continueMBB->begin(), BB,
20066                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20067   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20068
20069   // Add code to the main basic block to check if the stack limit has been hit,
20070   // and if so, jump to mallocMBB otherwise to bumpMBB.
20071   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20072   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20073     .addReg(tmpSPVReg).addReg(sizeVReg);
20074   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20075     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20076     .addReg(SPLimitVReg);
20077   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20078
20079   // bumpMBB simply decreases the stack pointer, since we know the current
20080   // stacklet has enough space.
20081   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20082     .addReg(SPLimitVReg);
20083   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20084     .addReg(SPLimitVReg);
20085   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20086
20087   // Calls into a routine in libgcc to allocate more space from the heap.
20088   const uint32_t *RegMask =
20089       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20090   if (IsLP64) {
20091     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20092       .addReg(sizeVReg);
20093     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20094       .addExternalSymbol("__morestack_allocate_stack_space")
20095       .addRegMask(RegMask)
20096       .addReg(X86::RDI, RegState::Implicit)
20097       .addReg(X86::RAX, RegState::ImplicitDefine);
20098   } else if (Is64Bit) {
20099     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20100       .addReg(sizeVReg);
20101     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20102       .addExternalSymbol("__morestack_allocate_stack_space")
20103       .addRegMask(RegMask)
20104       .addReg(X86::EDI, RegState::Implicit)
20105       .addReg(X86::EAX, RegState::ImplicitDefine);
20106   } else {
20107     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20108       .addImm(12);
20109     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20110     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20111       .addExternalSymbol("__morestack_allocate_stack_space")
20112       .addRegMask(RegMask)
20113       .addReg(X86::EAX, RegState::ImplicitDefine);
20114   }
20115
20116   if (!Is64Bit)
20117     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20118       .addImm(16);
20119
20120   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20121     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20122   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20123
20124   // Set up the CFG correctly.
20125   BB->addSuccessor(bumpMBB);
20126   BB->addSuccessor(mallocMBB);
20127   mallocMBB->addSuccessor(continueMBB);
20128   bumpMBB->addSuccessor(continueMBB);
20129
20130   // Take care of the PHI nodes.
20131   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20132           MI->getOperand(0).getReg())
20133     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20134     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20135
20136   // Delete the original pseudo instruction.
20137   MI->eraseFromParent();
20138
20139   // And we're done.
20140   return continueMBB;
20141 }
20142
20143 MachineBasicBlock *
20144 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20145                                         MachineBasicBlock *BB) const {
20146   DebugLoc DL = MI->getDebugLoc();
20147
20148   assert(!Subtarget->isTargetMachO());
20149
20150   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20151                                                     DL);
20152
20153   MI->eraseFromParent();   // The pseudo instruction is gone now.
20154   return BB;
20155 }
20156
20157 MachineBasicBlock *
20158 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20159                                       MachineBasicBlock *BB) const {
20160   // This is pretty easy.  We're taking the value that we received from
20161   // our load from the relocation, sticking it in either RDI (x86-64)
20162   // or EAX and doing an indirect call.  The return value will then
20163   // be in the normal return register.
20164   MachineFunction *F = BB->getParent();
20165   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20166   DebugLoc DL = MI->getDebugLoc();
20167
20168   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20169   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20170
20171   // Get a register mask for the lowered call.
20172   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20173   // proper register mask.
20174   const uint32_t *RegMask =
20175       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20176   if (Subtarget->is64Bit()) {
20177     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20178                                       TII->get(X86::MOV64rm), X86::RDI)
20179     .addReg(X86::RIP)
20180     .addImm(0).addReg(0)
20181     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20182                       MI->getOperand(3).getTargetFlags())
20183     .addReg(0);
20184     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20185     addDirectMem(MIB, X86::RDI);
20186     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20187   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20188     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20189                                       TII->get(X86::MOV32rm), X86::EAX)
20190     .addReg(0)
20191     .addImm(0).addReg(0)
20192     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20193                       MI->getOperand(3).getTargetFlags())
20194     .addReg(0);
20195     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20196     addDirectMem(MIB, X86::EAX);
20197     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20198   } else {
20199     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20200                                       TII->get(X86::MOV32rm), X86::EAX)
20201     .addReg(TII->getGlobalBaseReg(F))
20202     .addImm(0).addReg(0)
20203     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20204                       MI->getOperand(3).getTargetFlags())
20205     .addReg(0);
20206     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20207     addDirectMem(MIB, X86::EAX);
20208     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20209   }
20210
20211   MI->eraseFromParent(); // The pseudo instruction is gone now.
20212   return BB;
20213 }
20214
20215 MachineBasicBlock *
20216 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20217                                     MachineBasicBlock *MBB) const {
20218   DebugLoc DL = MI->getDebugLoc();
20219   MachineFunction *MF = MBB->getParent();
20220   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20221   MachineRegisterInfo &MRI = MF->getRegInfo();
20222
20223   const BasicBlock *BB = MBB->getBasicBlock();
20224   MachineFunction::iterator I = MBB;
20225   ++I;
20226
20227   // Memory Reference
20228   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20229   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20230
20231   unsigned DstReg;
20232   unsigned MemOpndSlot = 0;
20233
20234   unsigned CurOp = 0;
20235
20236   DstReg = MI->getOperand(CurOp++).getReg();
20237   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20238   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20239   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20240   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20241
20242   MemOpndSlot = CurOp;
20243
20244   MVT PVT = getPointerTy(MF->getDataLayout());
20245   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20246          "Invalid Pointer Size!");
20247
20248   // For v = setjmp(buf), we generate
20249   //
20250   // thisMBB:
20251   //  buf[LabelOffset] = restoreMBB
20252   //  SjLjSetup restoreMBB
20253   //
20254   // mainMBB:
20255   //  v_main = 0
20256   //
20257   // sinkMBB:
20258   //  v = phi(main, restore)
20259   //
20260   // restoreMBB:
20261   //  if base pointer being used, load it from frame
20262   //  v_restore = 1
20263
20264   MachineBasicBlock *thisMBB = MBB;
20265   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20266   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20267   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20268   MF->insert(I, mainMBB);
20269   MF->insert(I, sinkMBB);
20270   MF->push_back(restoreMBB);
20271
20272   MachineInstrBuilder MIB;
20273
20274   // Transfer the remainder of BB and its successor edges to sinkMBB.
20275   sinkMBB->splice(sinkMBB->begin(), MBB,
20276                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20277   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20278
20279   // thisMBB:
20280   unsigned PtrStoreOpc = 0;
20281   unsigned LabelReg = 0;
20282   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20283   Reloc::Model RM = MF->getTarget().getRelocationModel();
20284   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20285                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20286
20287   // Prepare IP either in reg or imm.
20288   if (!UseImmLabel) {
20289     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20290     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20291     LabelReg = MRI.createVirtualRegister(PtrRC);
20292     if (Subtarget->is64Bit()) {
20293       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20294               .addReg(X86::RIP)
20295               .addImm(0)
20296               .addReg(0)
20297               .addMBB(restoreMBB)
20298               .addReg(0);
20299     } else {
20300       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20301       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20302               .addReg(XII->getGlobalBaseReg(MF))
20303               .addImm(0)
20304               .addReg(0)
20305               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20306               .addReg(0);
20307     }
20308   } else
20309     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20310   // Store IP
20311   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20312   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20313     if (i == X86::AddrDisp)
20314       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20315     else
20316       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20317   }
20318   if (!UseImmLabel)
20319     MIB.addReg(LabelReg);
20320   else
20321     MIB.addMBB(restoreMBB);
20322   MIB.setMemRefs(MMOBegin, MMOEnd);
20323   // Setup
20324   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20325           .addMBB(restoreMBB);
20326
20327   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20328   MIB.addRegMask(RegInfo->getNoPreservedMask());
20329   thisMBB->addSuccessor(mainMBB);
20330   thisMBB->addSuccessor(restoreMBB);
20331
20332   // mainMBB:
20333   //  EAX = 0
20334   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20335   mainMBB->addSuccessor(sinkMBB);
20336
20337   // sinkMBB:
20338   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20339           TII->get(X86::PHI), DstReg)
20340     .addReg(mainDstReg).addMBB(mainMBB)
20341     .addReg(restoreDstReg).addMBB(restoreMBB);
20342
20343   // restoreMBB:
20344   if (RegInfo->hasBasePointer(*MF)) {
20345     const bool Uses64BitFramePtr =
20346         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20347     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20348     X86FI->setRestoreBasePointer(MF);
20349     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20350     unsigned BasePtr = RegInfo->getBaseRegister();
20351     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20352     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20353                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20354       .setMIFlag(MachineInstr::FrameSetup);
20355   }
20356   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20357   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20358   restoreMBB->addSuccessor(sinkMBB);
20359
20360   MI->eraseFromParent();
20361   return sinkMBB;
20362 }
20363
20364 MachineBasicBlock *
20365 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20366                                      MachineBasicBlock *MBB) const {
20367   DebugLoc DL = MI->getDebugLoc();
20368   MachineFunction *MF = MBB->getParent();
20369   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20370   MachineRegisterInfo &MRI = MF->getRegInfo();
20371
20372   // Memory Reference
20373   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20374   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20375
20376   MVT PVT = getPointerTy(MF->getDataLayout());
20377   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20378          "Invalid Pointer Size!");
20379
20380   const TargetRegisterClass *RC =
20381     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20382   unsigned Tmp = MRI.createVirtualRegister(RC);
20383   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20384   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20385   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20386   unsigned SP = RegInfo->getStackRegister();
20387
20388   MachineInstrBuilder MIB;
20389
20390   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20391   const int64_t SPOffset = 2 * PVT.getStoreSize();
20392
20393   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20394   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20395
20396   // Reload FP
20397   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20398   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20399     MIB.addOperand(MI->getOperand(i));
20400   MIB.setMemRefs(MMOBegin, MMOEnd);
20401   // Reload IP
20402   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20403   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20404     if (i == X86::AddrDisp)
20405       MIB.addDisp(MI->getOperand(i), LabelOffset);
20406     else
20407       MIB.addOperand(MI->getOperand(i));
20408   }
20409   MIB.setMemRefs(MMOBegin, MMOEnd);
20410   // Reload SP
20411   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20412   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20413     if (i == X86::AddrDisp)
20414       MIB.addDisp(MI->getOperand(i), SPOffset);
20415     else
20416       MIB.addOperand(MI->getOperand(i));
20417   }
20418   MIB.setMemRefs(MMOBegin, MMOEnd);
20419   // Jump
20420   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20421
20422   MI->eraseFromParent();
20423   return MBB;
20424 }
20425
20426 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20427 // accumulator loops. Writing back to the accumulator allows the coalescer
20428 // to remove extra copies in the loop.
20429 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20430 MachineBasicBlock *
20431 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20432                                  MachineBasicBlock *MBB) const {
20433   MachineOperand &AddendOp = MI->getOperand(3);
20434
20435   // Bail out early if the addend isn't a register - we can't switch these.
20436   if (!AddendOp.isReg())
20437     return MBB;
20438
20439   MachineFunction &MF = *MBB->getParent();
20440   MachineRegisterInfo &MRI = MF.getRegInfo();
20441
20442   // Check whether the addend is defined by a PHI:
20443   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20444   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20445   if (!AddendDef.isPHI())
20446     return MBB;
20447
20448   // Look for the following pattern:
20449   // loop:
20450   //   %addend = phi [%entry, 0], [%loop, %result]
20451   //   ...
20452   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20453
20454   // Replace with:
20455   //   loop:
20456   //   %addend = phi [%entry, 0], [%loop, %result]
20457   //   ...
20458   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20459
20460   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20461     assert(AddendDef.getOperand(i).isReg());
20462     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20463     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20464     if (&PHISrcInst == MI) {
20465       // Found a matching instruction.
20466       unsigned NewFMAOpc = 0;
20467       switch (MI->getOpcode()) {
20468         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20469         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20470         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20471         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20472         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20473         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20474         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20475         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20476         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20477         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20478         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20479         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20480         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20481         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20482         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20483         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20484         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20485         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20486         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20487         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20488
20489         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20490         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20491         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20492         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20493         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20494         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20495         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20496         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20497         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20498         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20499         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20500         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20501         default: llvm_unreachable("Unrecognized FMA variant.");
20502       }
20503
20504       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20505       MachineInstrBuilder MIB =
20506         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20507         .addOperand(MI->getOperand(0))
20508         .addOperand(MI->getOperand(3))
20509         .addOperand(MI->getOperand(2))
20510         .addOperand(MI->getOperand(1));
20511       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20512       MI->eraseFromParent();
20513     }
20514   }
20515
20516   return MBB;
20517 }
20518
20519 MachineBasicBlock *
20520 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20521                                                MachineBasicBlock *BB) const {
20522   switch (MI->getOpcode()) {
20523   default: llvm_unreachable("Unexpected instr type to insert");
20524   case X86::TAILJMPd64:
20525   case X86::TAILJMPr64:
20526   case X86::TAILJMPm64:
20527   case X86::TAILJMPd64_REX:
20528   case X86::TAILJMPr64_REX:
20529   case X86::TAILJMPm64_REX:
20530     llvm_unreachable("TAILJMP64 would not be touched here.");
20531   case X86::TCRETURNdi64:
20532   case X86::TCRETURNri64:
20533   case X86::TCRETURNmi64:
20534     return BB;
20535   case X86::WIN_ALLOCA:
20536     return EmitLoweredWinAlloca(MI, BB);
20537   case X86::SEG_ALLOCA_32:
20538   case X86::SEG_ALLOCA_64:
20539     return EmitLoweredSegAlloca(MI, BB);
20540   case X86::TLSCall_32:
20541   case X86::TLSCall_64:
20542     return EmitLoweredTLSCall(MI, BB);
20543   case X86::CMOV_GR8:
20544   case X86::CMOV_FR32:
20545   case X86::CMOV_FR64:
20546   case X86::CMOV_V4F32:
20547   case X86::CMOV_V2F64:
20548   case X86::CMOV_V2I64:
20549   case X86::CMOV_V8F32:
20550   case X86::CMOV_V4F64:
20551   case X86::CMOV_V4I64:
20552   case X86::CMOV_V16F32:
20553   case X86::CMOV_V8F64:
20554   case X86::CMOV_V8I64:
20555   case X86::CMOV_GR16:
20556   case X86::CMOV_GR32:
20557   case X86::CMOV_RFP32:
20558   case X86::CMOV_RFP64:
20559   case X86::CMOV_RFP80:
20560   case X86::CMOV_V8I1:
20561   case X86::CMOV_V16I1:
20562   case X86::CMOV_V32I1:
20563   case X86::CMOV_V64I1:
20564     return EmitLoweredSelect(MI, BB);
20565
20566   case X86::FP32_TO_INT16_IN_MEM:
20567   case X86::FP32_TO_INT32_IN_MEM:
20568   case X86::FP32_TO_INT64_IN_MEM:
20569   case X86::FP64_TO_INT16_IN_MEM:
20570   case X86::FP64_TO_INT32_IN_MEM:
20571   case X86::FP64_TO_INT64_IN_MEM:
20572   case X86::FP80_TO_INT16_IN_MEM:
20573   case X86::FP80_TO_INT32_IN_MEM:
20574   case X86::FP80_TO_INT64_IN_MEM: {
20575     MachineFunction *F = BB->getParent();
20576     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20577     DebugLoc DL = MI->getDebugLoc();
20578
20579     // Change the floating point control register to use "round towards zero"
20580     // mode when truncating to an integer value.
20581     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20582     addFrameReference(BuildMI(*BB, MI, DL,
20583                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20584
20585     // Load the old value of the high byte of the control word...
20586     unsigned OldCW =
20587       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20588     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20589                       CWFrameIdx);
20590
20591     // Set the high part to be round to zero...
20592     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20593       .addImm(0xC7F);
20594
20595     // Reload the modified control word now...
20596     addFrameReference(BuildMI(*BB, MI, DL,
20597                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20598
20599     // Restore the memory image of control word to original value
20600     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20601       .addReg(OldCW);
20602
20603     // Get the X86 opcode to use.
20604     unsigned Opc;
20605     switch (MI->getOpcode()) {
20606     default: llvm_unreachable("illegal opcode!");
20607     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20608     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20609     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20610     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20611     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20612     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20613     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20614     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20615     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20616     }
20617
20618     X86AddressMode AM;
20619     MachineOperand &Op = MI->getOperand(0);
20620     if (Op.isReg()) {
20621       AM.BaseType = X86AddressMode::RegBase;
20622       AM.Base.Reg = Op.getReg();
20623     } else {
20624       AM.BaseType = X86AddressMode::FrameIndexBase;
20625       AM.Base.FrameIndex = Op.getIndex();
20626     }
20627     Op = MI->getOperand(1);
20628     if (Op.isImm())
20629       AM.Scale = Op.getImm();
20630     Op = MI->getOperand(2);
20631     if (Op.isImm())
20632       AM.IndexReg = Op.getImm();
20633     Op = MI->getOperand(3);
20634     if (Op.isGlobal()) {
20635       AM.GV = Op.getGlobal();
20636     } else {
20637       AM.Disp = Op.getImm();
20638     }
20639     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20640                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20641
20642     // Reload the original control word now.
20643     addFrameReference(BuildMI(*BB, MI, DL,
20644                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20645
20646     MI->eraseFromParent();   // The pseudo instruction is gone now.
20647     return BB;
20648   }
20649     // String/text processing lowering.
20650   case X86::PCMPISTRM128REG:
20651   case X86::VPCMPISTRM128REG:
20652   case X86::PCMPISTRM128MEM:
20653   case X86::VPCMPISTRM128MEM:
20654   case X86::PCMPESTRM128REG:
20655   case X86::VPCMPESTRM128REG:
20656   case X86::PCMPESTRM128MEM:
20657   case X86::VPCMPESTRM128MEM:
20658     assert(Subtarget->hasSSE42() &&
20659            "Target must have SSE4.2 or AVX features enabled");
20660     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20661
20662   // String/text processing lowering.
20663   case X86::PCMPISTRIREG:
20664   case X86::VPCMPISTRIREG:
20665   case X86::PCMPISTRIMEM:
20666   case X86::VPCMPISTRIMEM:
20667   case X86::PCMPESTRIREG:
20668   case X86::VPCMPESTRIREG:
20669   case X86::PCMPESTRIMEM:
20670   case X86::VPCMPESTRIMEM:
20671     assert(Subtarget->hasSSE42() &&
20672            "Target must have SSE4.2 or AVX features enabled");
20673     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20674
20675   // Thread synchronization.
20676   case X86::MONITOR:
20677     return EmitMonitor(MI, BB, Subtarget);
20678
20679   // xbegin
20680   case X86::XBEGIN:
20681     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20682
20683   case X86::VASTART_SAVE_XMM_REGS:
20684     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20685
20686   case X86::VAARG_64:
20687     return EmitVAARG64WithCustomInserter(MI, BB);
20688
20689   case X86::EH_SjLj_SetJmp32:
20690   case X86::EH_SjLj_SetJmp64:
20691     return emitEHSjLjSetJmp(MI, BB);
20692
20693   case X86::EH_SjLj_LongJmp32:
20694   case X86::EH_SjLj_LongJmp64:
20695     return emitEHSjLjLongJmp(MI, BB);
20696
20697   case TargetOpcode::STATEPOINT:
20698     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20699     // this point in the process.  We diverge later.
20700     return emitPatchPoint(MI, BB);
20701
20702   case TargetOpcode::STACKMAP:
20703   case TargetOpcode::PATCHPOINT:
20704     return emitPatchPoint(MI, BB);
20705
20706   case X86::VFMADDPDr213r:
20707   case X86::VFMADDPSr213r:
20708   case X86::VFMADDSDr213r:
20709   case X86::VFMADDSSr213r:
20710   case X86::VFMSUBPDr213r:
20711   case X86::VFMSUBPSr213r:
20712   case X86::VFMSUBSDr213r:
20713   case X86::VFMSUBSSr213r:
20714   case X86::VFNMADDPDr213r:
20715   case X86::VFNMADDPSr213r:
20716   case X86::VFNMADDSDr213r:
20717   case X86::VFNMADDSSr213r:
20718   case X86::VFNMSUBPDr213r:
20719   case X86::VFNMSUBPSr213r:
20720   case X86::VFNMSUBSDr213r:
20721   case X86::VFNMSUBSSr213r:
20722   case X86::VFMADDSUBPDr213r:
20723   case X86::VFMADDSUBPSr213r:
20724   case X86::VFMSUBADDPDr213r:
20725   case X86::VFMSUBADDPSr213r:
20726   case X86::VFMADDPDr213rY:
20727   case X86::VFMADDPSr213rY:
20728   case X86::VFMSUBPDr213rY:
20729   case X86::VFMSUBPSr213rY:
20730   case X86::VFNMADDPDr213rY:
20731   case X86::VFNMADDPSr213rY:
20732   case X86::VFNMSUBPDr213rY:
20733   case X86::VFNMSUBPSr213rY:
20734   case X86::VFMADDSUBPDr213rY:
20735   case X86::VFMADDSUBPSr213rY:
20736   case X86::VFMSUBADDPDr213rY:
20737   case X86::VFMSUBADDPSr213rY:
20738     return emitFMA3Instr(MI, BB);
20739   }
20740 }
20741
20742 //===----------------------------------------------------------------------===//
20743 //                           X86 Optimization Hooks
20744 //===----------------------------------------------------------------------===//
20745
20746 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20747                                                       APInt &KnownZero,
20748                                                       APInt &KnownOne,
20749                                                       const SelectionDAG &DAG,
20750                                                       unsigned Depth) const {
20751   unsigned BitWidth = KnownZero.getBitWidth();
20752   unsigned Opc = Op.getOpcode();
20753   assert((Opc >= ISD::BUILTIN_OP_END ||
20754           Opc == ISD::INTRINSIC_WO_CHAIN ||
20755           Opc == ISD::INTRINSIC_W_CHAIN ||
20756           Opc == ISD::INTRINSIC_VOID) &&
20757          "Should use MaskedValueIsZero if you don't know whether Op"
20758          " is a target node!");
20759
20760   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20761   switch (Opc) {
20762   default: break;
20763   case X86ISD::ADD:
20764   case X86ISD::SUB:
20765   case X86ISD::ADC:
20766   case X86ISD::SBB:
20767   case X86ISD::SMUL:
20768   case X86ISD::UMUL:
20769   case X86ISD::INC:
20770   case X86ISD::DEC:
20771   case X86ISD::OR:
20772   case X86ISD::XOR:
20773   case X86ISD::AND:
20774     // These nodes' second result is a boolean.
20775     if (Op.getResNo() == 0)
20776       break;
20777     // Fallthrough
20778   case X86ISD::SETCC:
20779     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20780     break;
20781   case ISD::INTRINSIC_WO_CHAIN: {
20782     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20783     unsigned NumLoBits = 0;
20784     switch (IntId) {
20785     default: break;
20786     case Intrinsic::x86_sse_movmsk_ps:
20787     case Intrinsic::x86_avx_movmsk_ps_256:
20788     case Intrinsic::x86_sse2_movmsk_pd:
20789     case Intrinsic::x86_avx_movmsk_pd_256:
20790     case Intrinsic::x86_mmx_pmovmskb:
20791     case Intrinsic::x86_sse2_pmovmskb_128:
20792     case Intrinsic::x86_avx2_pmovmskb: {
20793       // High bits of movmskp{s|d}, pmovmskb are known zero.
20794       switch (IntId) {
20795         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20796         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20797         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20798         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20799         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20800         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20801         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20802         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20803       }
20804       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20805       break;
20806     }
20807     }
20808     break;
20809   }
20810   }
20811 }
20812
20813 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20814   SDValue Op,
20815   const SelectionDAG &,
20816   unsigned Depth) const {
20817   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20818   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20819     return Op.getValueType().getScalarType().getSizeInBits();
20820
20821   // Fallback case.
20822   return 1;
20823 }
20824
20825 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20826 /// node is a GlobalAddress + offset.
20827 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20828                                        const GlobalValue* &GA,
20829                                        int64_t &Offset) const {
20830   if (N->getOpcode() == X86ISD::Wrapper) {
20831     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20832       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20833       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20834       return true;
20835     }
20836   }
20837   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20838 }
20839
20840 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20841 /// same as extracting the high 128-bit part of 256-bit vector and then
20842 /// inserting the result into the low part of a new 256-bit vector
20843 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20844   EVT VT = SVOp->getValueType(0);
20845   unsigned NumElems = VT.getVectorNumElements();
20846
20847   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20848   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20849     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20850         SVOp->getMaskElt(j) >= 0)
20851       return false;
20852
20853   return true;
20854 }
20855
20856 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20857 /// same as extracting the low 128-bit part of 256-bit vector and then
20858 /// inserting the result into the high part of a new 256-bit vector
20859 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20860   EVT VT = SVOp->getValueType(0);
20861   unsigned NumElems = VT.getVectorNumElements();
20862
20863   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20864   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20865     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20866         SVOp->getMaskElt(j) >= 0)
20867       return false;
20868
20869   return true;
20870 }
20871
20872 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20873 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20874                                         TargetLowering::DAGCombinerInfo &DCI,
20875                                         const X86Subtarget* Subtarget) {
20876   SDLoc dl(N);
20877   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20878   SDValue V1 = SVOp->getOperand(0);
20879   SDValue V2 = SVOp->getOperand(1);
20880   EVT VT = SVOp->getValueType(0);
20881   unsigned NumElems = VT.getVectorNumElements();
20882
20883   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20884       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20885     //
20886     //                   0,0,0,...
20887     //                      |
20888     //    V      UNDEF    BUILD_VECTOR    UNDEF
20889     //     \      /           \           /
20890     //  CONCAT_VECTOR         CONCAT_VECTOR
20891     //         \                  /
20892     //          \                /
20893     //          RESULT: V + zero extended
20894     //
20895     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20896         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20897         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20898       return SDValue();
20899
20900     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20901       return SDValue();
20902
20903     // To match the shuffle mask, the first half of the mask should
20904     // be exactly the first vector, and all the rest a splat with the
20905     // first element of the second one.
20906     for (unsigned i = 0; i != NumElems/2; ++i)
20907       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20908           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20909         return SDValue();
20910
20911     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20912     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20913       if (Ld->hasNUsesOfValue(1, 0)) {
20914         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20915         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20916         SDValue ResNode =
20917           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20918                                   Ld->getMemoryVT(),
20919                                   Ld->getPointerInfo(),
20920                                   Ld->getAlignment(),
20921                                   false/*isVolatile*/, true/*ReadMem*/,
20922                                   false/*WriteMem*/);
20923
20924         // Make sure the newly-created LOAD is in the same position as Ld in
20925         // terms of dependency. We create a TokenFactor for Ld and ResNode,
20926         // and update uses of Ld's output chain to use the TokenFactor.
20927         if (Ld->hasAnyUseOfValue(1)) {
20928           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20929                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20930           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20931           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20932                                  SDValue(ResNode.getNode(), 1));
20933         }
20934
20935         return DAG.getBitcast(VT, ResNode);
20936       }
20937     }
20938
20939     // Emit a zeroed vector and insert the desired subvector on its
20940     // first half.
20941     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20942     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20943     return DCI.CombineTo(N, InsV);
20944   }
20945
20946   //===--------------------------------------------------------------------===//
20947   // Combine some shuffles into subvector extracts and inserts:
20948   //
20949
20950   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20951   if (isShuffleHigh128VectorInsertLow(SVOp)) {
20952     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20953     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20954     return DCI.CombineTo(N, InsV);
20955   }
20956
20957   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20958   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20959     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20960     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20961     return DCI.CombineTo(N, InsV);
20962   }
20963
20964   return SDValue();
20965 }
20966
20967 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20968 /// possible.
20969 ///
20970 /// This is the leaf of the recursive combinine below. When we have found some
20971 /// chain of single-use x86 shuffle instructions and accumulated the combined
20972 /// shuffle mask represented by them, this will try to pattern match that mask
20973 /// into either a single instruction if there is a special purpose instruction
20974 /// for this operation, or into a PSHUFB instruction which is a fully general
20975 /// instruction but should only be used to replace chains over a certain depth.
20976 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20977                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20978                                    TargetLowering::DAGCombinerInfo &DCI,
20979                                    const X86Subtarget *Subtarget) {
20980   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20981
20982   // Find the operand that enters the chain. Note that multiple uses are OK
20983   // here, we're not going to remove the operand we find.
20984   SDValue Input = Op.getOperand(0);
20985   while (Input.getOpcode() == ISD::BITCAST)
20986     Input = Input.getOperand(0);
20987
20988   MVT VT = Input.getSimpleValueType();
20989   MVT RootVT = Root.getSimpleValueType();
20990   SDLoc DL(Root);
20991
20992   // Just remove no-op shuffle masks.
20993   if (Mask.size() == 1) {
20994     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
20995                   /*AddTo*/ true);
20996     return true;
20997   }
20998
20999   // Use the float domain if the operand type is a floating point type.
21000   bool FloatDomain = VT.isFloatingPoint();
21001
21002   // For floating point shuffles, we don't have free copies in the shuffle
21003   // instructions or the ability to load as part of the instruction, so
21004   // canonicalize their shuffles to UNPCK or MOV variants.
21005   //
21006   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21007   // vectors because it can have a load folded into it that UNPCK cannot. This
21008   // doesn't preclude something switching to the shorter encoding post-RA.
21009   //
21010   // FIXME: Should teach these routines about AVX vector widths.
21011   if (FloatDomain && VT.getSizeInBits() == 128) {
21012     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21013       bool Lo = Mask.equals({0, 0});
21014       unsigned Shuffle;
21015       MVT ShuffleVT;
21016       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21017       // is no slower than UNPCKLPD but has the option to fold the input operand
21018       // into even an unaligned memory load.
21019       if (Lo && Subtarget->hasSSE3()) {
21020         Shuffle = X86ISD::MOVDDUP;
21021         ShuffleVT = MVT::v2f64;
21022       } else {
21023         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21024         // than the UNPCK variants.
21025         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21026         ShuffleVT = MVT::v4f32;
21027       }
21028       if (Depth == 1 && Root->getOpcode() == Shuffle)
21029         return false; // Nothing to do!
21030       Op = DAG.getBitcast(ShuffleVT, Input);
21031       DCI.AddToWorklist(Op.getNode());
21032       if (Shuffle == X86ISD::MOVDDUP)
21033         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21034       else
21035         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21036       DCI.AddToWorklist(Op.getNode());
21037       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21038                     /*AddTo*/ true);
21039       return true;
21040     }
21041     if (Subtarget->hasSSE3() &&
21042         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21043       bool Lo = Mask.equals({0, 0, 2, 2});
21044       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21045       MVT ShuffleVT = MVT::v4f32;
21046       if (Depth == 1 && Root->getOpcode() == Shuffle)
21047         return false; // Nothing to do!
21048       Op = DAG.getBitcast(ShuffleVT, Input);
21049       DCI.AddToWorklist(Op.getNode());
21050       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21051       DCI.AddToWorklist(Op.getNode());
21052       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21053                     /*AddTo*/ true);
21054       return true;
21055     }
21056     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21057       bool Lo = Mask.equals({0, 0, 1, 1});
21058       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21059       MVT ShuffleVT = MVT::v4f32;
21060       if (Depth == 1 && Root->getOpcode() == Shuffle)
21061         return false; // Nothing to do!
21062       Op = DAG.getBitcast(ShuffleVT, Input);
21063       DCI.AddToWorklist(Op.getNode());
21064       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21065       DCI.AddToWorklist(Op.getNode());
21066       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21067                     /*AddTo*/ true);
21068       return true;
21069     }
21070   }
21071
21072   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21073   // variants as none of these have single-instruction variants that are
21074   // superior to the UNPCK formulation.
21075   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21076       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21077        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21078        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21079        Mask.equals(
21080            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21081     bool Lo = Mask[0] == 0;
21082     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21083     if (Depth == 1 && Root->getOpcode() == Shuffle)
21084       return false; // Nothing to do!
21085     MVT ShuffleVT;
21086     switch (Mask.size()) {
21087     case 8:
21088       ShuffleVT = MVT::v8i16;
21089       break;
21090     case 16:
21091       ShuffleVT = MVT::v16i8;
21092       break;
21093     default:
21094       llvm_unreachable("Impossible mask size!");
21095     };
21096     Op = DAG.getBitcast(ShuffleVT, Input);
21097     DCI.AddToWorklist(Op.getNode());
21098     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21099     DCI.AddToWorklist(Op.getNode());
21100     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21101                   /*AddTo*/ true);
21102     return true;
21103   }
21104
21105   // Don't try to re-form single instruction chains under any circumstances now
21106   // that we've done encoding canonicalization for them.
21107   if (Depth < 2)
21108     return false;
21109
21110   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21111   // can replace them with a single PSHUFB instruction profitably. Intel's
21112   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21113   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21114   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21115     SmallVector<SDValue, 16> PSHUFBMask;
21116     int NumBytes = VT.getSizeInBits() / 8;
21117     int Ratio = NumBytes / Mask.size();
21118     for (int i = 0; i < NumBytes; ++i) {
21119       if (Mask[i / Ratio] == SM_SentinelUndef) {
21120         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21121         continue;
21122       }
21123       int M = Mask[i / Ratio] != SM_SentinelZero
21124                   ? Ratio * Mask[i / Ratio] + i % Ratio
21125                   : 255;
21126       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21127     }
21128     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21129     Op = DAG.getBitcast(ByteVT, Input);
21130     DCI.AddToWorklist(Op.getNode());
21131     SDValue PSHUFBMaskOp =
21132         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21133     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21134     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21135     DCI.AddToWorklist(Op.getNode());
21136     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21137                   /*AddTo*/ true);
21138     return true;
21139   }
21140
21141   // Failed to find any combines.
21142   return false;
21143 }
21144
21145 /// \brief Fully generic combining of x86 shuffle instructions.
21146 ///
21147 /// This should be the last combine run over the x86 shuffle instructions. Once
21148 /// they have been fully optimized, this will recursively consider all chains
21149 /// of single-use shuffle instructions, build a generic model of the cumulative
21150 /// shuffle operation, and check for simpler instructions which implement this
21151 /// operation. We use this primarily for two purposes:
21152 ///
21153 /// 1) Collapse generic shuffles to specialized single instructions when
21154 ///    equivalent. In most cases, this is just an encoding size win, but
21155 ///    sometimes we will collapse multiple generic shuffles into a single
21156 ///    special-purpose shuffle.
21157 /// 2) Look for sequences of shuffle instructions with 3 or more total
21158 ///    instructions, and replace them with the slightly more expensive SSSE3
21159 ///    PSHUFB instruction if available. We do this as the last combining step
21160 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21161 ///    a suitable short sequence of other instructions. The PHUFB will either
21162 ///    use a register or have to read from memory and so is slightly (but only
21163 ///    slightly) more expensive than the other shuffle instructions.
21164 ///
21165 /// Because this is inherently a quadratic operation (for each shuffle in
21166 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21167 /// This should never be an issue in practice as the shuffle lowering doesn't
21168 /// produce sequences of more than 8 instructions.
21169 ///
21170 /// FIXME: We will currently miss some cases where the redundant shuffling
21171 /// would simplify under the threshold for PSHUFB formation because of
21172 /// combine-ordering. To fix this, we should do the redundant instruction
21173 /// combining in this recursive walk.
21174 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21175                                           ArrayRef<int> RootMask,
21176                                           int Depth, bool HasPSHUFB,
21177                                           SelectionDAG &DAG,
21178                                           TargetLowering::DAGCombinerInfo &DCI,
21179                                           const X86Subtarget *Subtarget) {
21180   // Bound the depth of our recursive combine because this is ultimately
21181   // quadratic in nature.
21182   if (Depth > 8)
21183     return false;
21184
21185   // Directly rip through bitcasts to find the underlying operand.
21186   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21187     Op = Op.getOperand(0);
21188
21189   MVT VT = Op.getSimpleValueType();
21190   if (!VT.isVector())
21191     return false; // Bail if we hit a non-vector.
21192
21193   assert(Root.getSimpleValueType().isVector() &&
21194          "Shuffles operate on vector types!");
21195   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21196          "Can only combine shuffles of the same vector register size.");
21197
21198   if (!isTargetShuffle(Op.getOpcode()))
21199     return false;
21200   SmallVector<int, 16> OpMask;
21201   bool IsUnary;
21202   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21203   // We only can combine unary shuffles which we can decode the mask for.
21204   if (!HaveMask || !IsUnary)
21205     return false;
21206
21207   assert(VT.getVectorNumElements() == OpMask.size() &&
21208          "Different mask size from vector size!");
21209   assert(((RootMask.size() > OpMask.size() &&
21210            RootMask.size() % OpMask.size() == 0) ||
21211           (OpMask.size() > RootMask.size() &&
21212            OpMask.size() % RootMask.size() == 0) ||
21213           OpMask.size() == RootMask.size()) &&
21214          "The smaller number of elements must divide the larger.");
21215   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21216   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21217   assert(((RootRatio == 1 && OpRatio == 1) ||
21218           (RootRatio == 1) != (OpRatio == 1)) &&
21219          "Must not have a ratio for both incoming and op masks!");
21220
21221   SmallVector<int, 16> Mask;
21222   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21223
21224   // Merge this shuffle operation's mask into our accumulated mask. Note that
21225   // this shuffle's mask will be the first applied to the input, followed by the
21226   // root mask to get us all the way to the root value arrangement. The reason
21227   // for this order is that we are recursing up the operation chain.
21228   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21229     int RootIdx = i / RootRatio;
21230     if (RootMask[RootIdx] < 0) {
21231       // This is a zero or undef lane, we're done.
21232       Mask.push_back(RootMask[RootIdx]);
21233       continue;
21234     }
21235
21236     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21237     int OpIdx = RootMaskedIdx / OpRatio;
21238     if (OpMask[OpIdx] < 0) {
21239       // The incoming lanes are zero or undef, it doesn't matter which ones we
21240       // are using.
21241       Mask.push_back(OpMask[OpIdx]);
21242       continue;
21243     }
21244
21245     // Ok, we have non-zero lanes, map them through.
21246     Mask.push_back(OpMask[OpIdx] * OpRatio +
21247                    RootMaskedIdx % OpRatio);
21248   }
21249
21250   // See if we can recurse into the operand to combine more things.
21251   switch (Op.getOpcode()) {
21252     case X86ISD::PSHUFB:
21253       HasPSHUFB = true;
21254     case X86ISD::PSHUFD:
21255     case X86ISD::PSHUFHW:
21256     case X86ISD::PSHUFLW:
21257       if (Op.getOperand(0).hasOneUse() &&
21258           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21259                                         HasPSHUFB, DAG, DCI, Subtarget))
21260         return true;
21261       break;
21262
21263     case X86ISD::UNPCKL:
21264     case X86ISD::UNPCKH:
21265       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21266       // We can't check for single use, we have to check that this shuffle is the only user.
21267       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21268           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21269                                         HasPSHUFB, DAG, DCI, Subtarget))
21270           return true;
21271       break;
21272   }
21273
21274   // Minor canonicalization of the accumulated shuffle mask to make it easier
21275   // to match below. All this does is detect masks with squential pairs of
21276   // elements, and shrink them to the half-width mask. It does this in a loop
21277   // so it will reduce the size of the mask to the minimal width mask which
21278   // performs an equivalent shuffle.
21279   SmallVector<int, 16> WidenedMask;
21280   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21281     Mask = std::move(WidenedMask);
21282     WidenedMask.clear();
21283   }
21284
21285   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21286                                 Subtarget);
21287 }
21288
21289 /// \brief Get the PSHUF-style mask from PSHUF node.
21290 ///
21291 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21292 /// PSHUF-style masks that can be reused with such instructions.
21293 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21294   MVT VT = N.getSimpleValueType();
21295   SmallVector<int, 4> Mask;
21296   bool IsUnary;
21297   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21298   (void)HaveMask;
21299   assert(HaveMask);
21300
21301   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21302   // matter. Check that the upper masks are repeats and remove them.
21303   if (VT.getSizeInBits() > 128) {
21304     int LaneElts = 128 / VT.getScalarSizeInBits();
21305 #ifndef NDEBUG
21306     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21307       for (int j = 0; j < LaneElts; ++j)
21308         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21309                "Mask doesn't repeat in high 128-bit lanes!");
21310 #endif
21311     Mask.resize(LaneElts);
21312   }
21313
21314   switch (N.getOpcode()) {
21315   case X86ISD::PSHUFD:
21316     return Mask;
21317   case X86ISD::PSHUFLW:
21318     Mask.resize(4);
21319     return Mask;
21320   case X86ISD::PSHUFHW:
21321     Mask.erase(Mask.begin(), Mask.begin() + 4);
21322     for (int &M : Mask)
21323       M -= 4;
21324     return Mask;
21325   default:
21326     llvm_unreachable("No valid shuffle instruction found!");
21327   }
21328 }
21329
21330 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21331 ///
21332 /// We walk up the chain and look for a combinable shuffle, skipping over
21333 /// shuffles that we could hoist this shuffle's transformation past without
21334 /// altering anything.
21335 static SDValue
21336 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21337                              SelectionDAG &DAG,
21338                              TargetLowering::DAGCombinerInfo &DCI) {
21339   assert(N.getOpcode() == X86ISD::PSHUFD &&
21340          "Called with something other than an x86 128-bit half shuffle!");
21341   SDLoc DL(N);
21342
21343   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21344   // of the shuffles in the chain so that we can form a fresh chain to replace
21345   // this one.
21346   SmallVector<SDValue, 8> Chain;
21347   SDValue V = N.getOperand(0);
21348   for (; V.hasOneUse(); V = V.getOperand(0)) {
21349     switch (V.getOpcode()) {
21350     default:
21351       return SDValue(); // Nothing combined!
21352
21353     case ISD::BITCAST:
21354       // Skip bitcasts as we always know the type for the target specific
21355       // instructions.
21356       continue;
21357
21358     case X86ISD::PSHUFD:
21359       // Found another dword shuffle.
21360       break;
21361
21362     case X86ISD::PSHUFLW:
21363       // Check that the low words (being shuffled) are the identity in the
21364       // dword shuffle, and the high words are self-contained.
21365       if (Mask[0] != 0 || Mask[1] != 1 ||
21366           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21367         return SDValue();
21368
21369       Chain.push_back(V);
21370       continue;
21371
21372     case X86ISD::PSHUFHW:
21373       // Check that the high words (being shuffled) are the identity in the
21374       // dword shuffle, and the low words are self-contained.
21375       if (Mask[2] != 2 || Mask[3] != 3 ||
21376           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21377         return SDValue();
21378
21379       Chain.push_back(V);
21380       continue;
21381
21382     case X86ISD::UNPCKL:
21383     case X86ISD::UNPCKH:
21384       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21385       // shuffle into a preceding word shuffle.
21386       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21387           V.getSimpleValueType().getScalarType() != MVT::i16)
21388         return SDValue();
21389
21390       // Search for a half-shuffle which we can combine with.
21391       unsigned CombineOp =
21392           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21393       if (V.getOperand(0) != V.getOperand(1) ||
21394           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21395         return SDValue();
21396       Chain.push_back(V);
21397       V = V.getOperand(0);
21398       do {
21399         switch (V.getOpcode()) {
21400         default:
21401           return SDValue(); // Nothing to combine.
21402
21403         case X86ISD::PSHUFLW:
21404         case X86ISD::PSHUFHW:
21405           if (V.getOpcode() == CombineOp)
21406             break;
21407
21408           Chain.push_back(V);
21409
21410           // Fallthrough!
21411         case ISD::BITCAST:
21412           V = V.getOperand(0);
21413           continue;
21414         }
21415         break;
21416       } while (V.hasOneUse());
21417       break;
21418     }
21419     // Break out of the loop if we break out of the switch.
21420     break;
21421   }
21422
21423   if (!V.hasOneUse())
21424     // We fell out of the loop without finding a viable combining instruction.
21425     return SDValue();
21426
21427   // Merge this node's mask and our incoming mask.
21428   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21429   for (int &M : Mask)
21430     M = VMask[M];
21431   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21432                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21433
21434   // Rebuild the chain around this new shuffle.
21435   while (!Chain.empty()) {
21436     SDValue W = Chain.pop_back_val();
21437
21438     if (V.getValueType() != W.getOperand(0).getValueType())
21439       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21440
21441     switch (W.getOpcode()) {
21442     default:
21443       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21444
21445     case X86ISD::UNPCKL:
21446     case X86ISD::UNPCKH:
21447       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21448       break;
21449
21450     case X86ISD::PSHUFD:
21451     case X86ISD::PSHUFLW:
21452     case X86ISD::PSHUFHW:
21453       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21454       break;
21455     }
21456   }
21457   if (V.getValueType() != N.getValueType())
21458     V = DAG.getBitcast(N.getValueType(), V);
21459
21460   // Return the new chain to replace N.
21461   return V;
21462 }
21463
21464 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21465 ///
21466 /// We walk up the chain, skipping shuffles of the other half and looking
21467 /// through shuffles which switch halves trying to find a shuffle of the same
21468 /// pair of dwords.
21469 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21470                                         SelectionDAG &DAG,
21471                                         TargetLowering::DAGCombinerInfo &DCI) {
21472   assert(
21473       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21474       "Called with something other than an x86 128-bit half shuffle!");
21475   SDLoc DL(N);
21476   unsigned CombineOpcode = N.getOpcode();
21477
21478   // Walk up a single-use chain looking for a combinable shuffle.
21479   SDValue V = N.getOperand(0);
21480   for (; V.hasOneUse(); V = V.getOperand(0)) {
21481     switch (V.getOpcode()) {
21482     default:
21483       return false; // Nothing combined!
21484
21485     case ISD::BITCAST:
21486       // Skip bitcasts as we always know the type for the target specific
21487       // instructions.
21488       continue;
21489
21490     case X86ISD::PSHUFLW:
21491     case X86ISD::PSHUFHW:
21492       if (V.getOpcode() == CombineOpcode)
21493         break;
21494
21495       // Other-half shuffles are no-ops.
21496       continue;
21497     }
21498     // Break out of the loop if we break out of the switch.
21499     break;
21500   }
21501
21502   if (!V.hasOneUse())
21503     // We fell out of the loop without finding a viable combining instruction.
21504     return false;
21505
21506   // Combine away the bottom node as its shuffle will be accumulated into
21507   // a preceding shuffle.
21508   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21509
21510   // Record the old value.
21511   SDValue Old = V;
21512
21513   // Merge this node's mask and our incoming mask (adjusted to account for all
21514   // the pshufd instructions encountered).
21515   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21516   for (int &M : Mask)
21517     M = VMask[M];
21518   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21519                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21520
21521   // Check that the shuffles didn't cancel each other out. If not, we need to
21522   // combine to the new one.
21523   if (Old != V)
21524     // Replace the combinable shuffle with the combined one, updating all users
21525     // so that we re-evaluate the chain here.
21526     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21527
21528   return true;
21529 }
21530
21531 /// \brief Try to combine x86 target specific shuffles.
21532 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21533                                            TargetLowering::DAGCombinerInfo &DCI,
21534                                            const X86Subtarget *Subtarget) {
21535   SDLoc DL(N);
21536   MVT VT = N.getSimpleValueType();
21537   SmallVector<int, 4> Mask;
21538
21539   switch (N.getOpcode()) {
21540   case X86ISD::PSHUFD:
21541   case X86ISD::PSHUFLW:
21542   case X86ISD::PSHUFHW:
21543     Mask = getPSHUFShuffleMask(N);
21544     assert(Mask.size() == 4);
21545     break;
21546   default:
21547     return SDValue();
21548   }
21549
21550   // Nuke no-op shuffles that show up after combining.
21551   if (isNoopShuffleMask(Mask))
21552     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21553
21554   // Look for simplifications involving one or two shuffle instructions.
21555   SDValue V = N.getOperand(0);
21556   switch (N.getOpcode()) {
21557   default:
21558     break;
21559   case X86ISD::PSHUFLW:
21560   case X86ISD::PSHUFHW:
21561     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21562
21563     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21564       return SDValue(); // We combined away this shuffle, so we're done.
21565
21566     // See if this reduces to a PSHUFD which is no more expensive and can
21567     // combine with more operations. Note that it has to at least flip the
21568     // dwords as otherwise it would have been removed as a no-op.
21569     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21570       int DMask[] = {0, 1, 2, 3};
21571       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21572       DMask[DOffset + 0] = DOffset + 1;
21573       DMask[DOffset + 1] = DOffset + 0;
21574       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21575       V = DAG.getBitcast(DVT, V);
21576       DCI.AddToWorklist(V.getNode());
21577       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21578                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21579       DCI.AddToWorklist(V.getNode());
21580       return DAG.getBitcast(VT, V);
21581     }
21582
21583     // Look for shuffle patterns which can be implemented as a single unpack.
21584     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21585     // only works when we have a PSHUFD followed by two half-shuffles.
21586     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21587         (V.getOpcode() == X86ISD::PSHUFLW ||
21588          V.getOpcode() == X86ISD::PSHUFHW) &&
21589         V.getOpcode() != N.getOpcode() &&
21590         V.hasOneUse()) {
21591       SDValue D = V.getOperand(0);
21592       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21593         D = D.getOperand(0);
21594       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21595         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21596         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21597         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21598         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21599         int WordMask[8];
21600         for (int i = 0; i < 4; ++i) {
21601           WordMask[i + NOffset] = Mask[i] + NOffset;
21602           WordMask[i + VOffset] = VMask[i] + VOffset;
21603         }
21604         // Map the word mask through the DWord mask.
21605         int MappedMask[8];
21606         for (int i = 0; i < 8; ++i)
21607           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21608         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21609             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21610           // We can replace all three shuffles with an unpack.
21611           V = DAG.getBitcast(VT, D.getOperand(0));
21612           DCI.AddToWorklist(V.getNode());
21613           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21614                                                 : X86ISD::UNPCKH,
21615                              DL, VT, V, V);
21616         }
21617       }
21618     }
21619
21620     break;
21621
21622   case X86ISD::PSHUFD:
21623     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21624       return NewN;
21625
21626     break;
21627   }
21628
21629   return SDValue();
21630 }
21631
21632 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21633 ///
21634 /// We combine this directly on the abstract vector shuffle nodes so it is
21635 /// easier to generically match. We also insert dummy vector shuffle nodes for
21636 /// the operands which explicitly discard the lanes which are unused by this
21637 /// operation to try to flow through the rest of the combiner the fact that
21638 /// they're unused.
21639 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21640   SDLoc DL(N);
21641   EVT VT = N->getValueType(0);
21642
21643   // We only handle target-independent shuffles.
21644   // FIXME: It would be easy and harmless to use the target shuffle mask
21645   // extraction tool to support more.
21646   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21647     return SDValue();
21648
21649   auto *SVN = cast<ShuffleVectorSDNode>(N);
21650   ArrayRef<int> Mask = SVN->getMask();
21651   SDValue V1 = N->getOperand(0);
21652   SDValue V2 = N->getOperand(1);
21653
21654   // We require the first shuffle operand to be the SUB node, and the second to
21655   // be the ADD node.
21656   // FIXME: We should support the commuted patterns.
21657   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21658     return SDValue();
21659
21660   // If there are other uses of these operations we can't fold them.
21661   if (!V1->hasOneUse() || !V2->hasOneUse())
21662     return SDValue();
21663
21664   // Ensure that both operations have the same operands. Note that we can
21665   // commute the FADD operands.
21666   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21667   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21668       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21669     return SDValue();
21670
21671   // We're looking for blends between FADD and FSUB nodes. We insist on these
21672   // nodes being lined up in a specific expected pattern.
21673   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21674         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21675         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21676     return SDValue();
21677
21678   // Only specific types are legal at this point, assert so we notice if and
21679   // when these change.
21680   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21681           VT == MVT::v4f64) &&
21682          "Unknown vector type encountered!");
21683
21684   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21685 }
21686
21687 /// PerformShuffleCombine - Performs several different shuffle combines.
21688 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21689                                      TargetLowering::DAGCombinerInfo &DCI,
21690                                      const X86Subtarget *Subtarget) {
21691   SDLoc dl(N);
21692   SDValue N0 = N->getOperand(0);
21693   SDValue N1 = N->getOperand(1);
21694   EVT VT = N->getValueType(0);
21695
21696   // Don't create instructions with illegal types after legalize types has run.
21697   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21698   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21699     return SDValue();
21700
21701   // If we have legalized the vector types, look for blends of FADD and FSUB
21702   // nodes that we can fuse into an ADDSUB node.
21703   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21704     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21705       return AddSub;
21706
21707   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21708   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21709       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21710     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21711
21712   // During Type Legalization, when promoting illegal vector types,
21713   // the backend might introduce new shuffle dag nodes and bitcasts.
21714   //
21715   // This code performs the following transformation:
21716   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21717   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21718   //
21719   // We do this only if both the bitcast and the BINOP dag nodes have
21720   // one use. Also, perform this transformation only if the new binary
21721   // operation is legal. This is to avoid introducing dag nodes that
21722   // potentially need to be further expanded (or custom lowered) into a
21723   // less optimal sequence of dag nodes.
21724   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21725       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21726       N0.getOpcode() == ISD::BITCAST) {
21727     SDValue BC0 = N0.getOperand(0);
21728     EVT SVT = BC0.getValueType();
21729     unsigned Opcode = BC0.getOpcode();
21730     unsigned NumElts = VT.getVectorNumElements();
21731
21732     if (BC0.hasOneUse() && SVT.isVector() &&
21733         SVT.getVectorNumElements() * 2 == NumElts &&
21734         TLI.isOperationLegal(Opcode, VT)) {
21735       bool CanFold = false;
21736       switch (Opcode) {
21737       default : break;
21738       case ISD::ADD :
21739       case ISD::FADD :
21740       case ISD::SUB :
21741       case ISD::FSUB :
21742       case ISD::MUL :
21743       case ISD::FMUL :
21744         CanFold = true;
21745       }
21746
21747       unsigned SVTNumElts = SVT.getVectorNumElements();
21748       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21749       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21750         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21751       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21752         CanFold = SVOp->getMaskElt(i) < 0;
21753
21754       if (CanFold) {
21755         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21756         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21757         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21758         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21759       }
21760     }
21761   }
21762
21763   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21764   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21765   // consecutive, non-overlapping, and in the right order.
21766   SmallVector<SDValue, 16> Elts;
21767   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21768     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21769
21770   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21771     return LD;
21772
21773   if (isTargetShuffle(N->getOpcode())) {
21774     SDValue Shuffle =
21775         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21776     if (Shuffle.getNode())
21777       return Shuffle;
21778
21779     // Try recursively combining arbitrary sequences of x86 shuffle
21780     // instructions into higher-order shuffles. We do this after combining
21781     // specific PSHUF instruction sequences into their minimal form so that we
21782     // can evaluate how many specialized shuffle instructions are involved in
21783     // a particular chain.
21784     SmallVector<int, 1> NonceMask; // Just a placeholder.
21785     NonceMask.push_back(0);
21786     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21787                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21788                                       DCI, Subtarget))
21789       return SDValue(); // This routine will use CombineTo to replace N.
21790   }
21791
21792   return SDValue();
21793 }
21794
21795 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21796 /// specific shuffle of a load can be folded into a single element load.
21797 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21798 /// shuffles have been custom lowered so we need to handle those here.
21799 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21800                                          TargetLowering::DAGCombinerInfo &DCI) {
21801   if (DCI.isBeforeLegalizeOps())
21802     return SDValue();
21803
21804   SDValue InVec = N->getOperand(0);
21805   SDValue EltNo = N->getOperand(1);
21806
21807   if (!isa<ConstantSDNode>(EltNo))
21808     return SDValue();
21809
21810   EVT OriginalVT = InVec.getValueType();
21811
21812   if (InVec.getOpcode() == ISD::BITCAST) {
21813     // Don't duplicate a load with other uses.
21814     if (!InVec.hasOneUse())
21815       return SDValue();
21816     EVT BCVT = InVec.getOperand(0).getValueType();
21817     if (!BCVT.isVector() ||
21818         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21819       return SDValue();
21820     InVec = InVec.getOperand(0);
21821   }
21822
21823   EVT CurrentVT = InVec.getValueType();
21824
21825   if (!isTargetShuffle(InVec.getOpcode()))
21826     return SDValue();
21827
21828   // Don't duplicate a load with other uses.
21829   if (!InVec.hasOneUse())
21830     return SDValue();
21831
21832   SmallVector<int, 16> ShuffleMask;
21833   bool UnaryShuffle;
21834   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21835                             ShuffleMask, UnaryShuffle))
21836     return SDValue();
21837
21838   // Select the input vector, guarding against out of range extract vector.
21839   unsigned NumElems = CurrentVT.getVectorNumElements();
21840   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21841   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21842   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21843                                          : InVec.getOperand(1);
21844
21845   // If inputs to shuffle are the same for both ops, then allow 2 uses
21846   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21847                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21848
21849   if (LdNode.getOpcode() == ISD::BITCAST) {
21850     // Don't duplicate a load with other uses.
21851     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21852       return SDValue();
21853
21854     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21855     LdNode = LdNode.getOperand(0);
21856   }
21857
21858   if (!ISD::isNormalLoad(LdNode.getNode()))
21859     return SDValue();
21860
21861   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21862
21863   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21864     return SDValue();
21865
21866   EVT EltVT = N->getValueType(0);
21867   // If there's a bitcast before the shuffle, check if the load type and
21868   // alignment is valid.
21869   unsigned Align = LN0->getAlignment();
21870   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21871   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
21872       EltVT.getTypeForEVT(*DAG.getContext()));
21873
21874   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21875     return SDValue();
21876
21877   // All checks match so transform back to vector_shuffle so that DAG combiner
21878   // can finish the job
21879   SDLoc dl(N);
21880
21881   // Create shuffle node taking into account the case that its a unary shuffle
21882   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21883                                    : InVec.getOperand(1);
21884   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21885                                  InVec.getOperand(0), Shuffle,
21886                                  &ShuffleMask[0]);
21887   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21888   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21889                      EltNo);
21890 }
21891
21892 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21893 /// special and don't usually play with other vector types, it's better to
21894 /// handle them early to be sure we emit efficient code by avoiding
21895 /// store-load conversions.
21896 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21897   if (N->getValueType(0) != MVT::x86mmx ||
21898       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21899       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21900     return SDValue();
21901
21902   SDValue V = N->getOperand(0);
21903   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21904   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21905     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21906                        N->getValueType(0), V.getOperand(0));
21907
21908   return SDValue();
21909 }
21910
21911 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21912 /// generation and convert it from being a bunch of shuffles and extracts
21913 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21914 /// storing the value and loading scalars back, while for x64 we should
21915 /// use 64-bit extracts and shifts.
21916 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21917                                          TargetLowering::DAGCombinerInfo &DCI) {
21918   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
21919     return NewOp;
21920
21921   SDValue InputVector = N->getOperand(0);
21922   SDLoc dl(InputVector);
21923   // Detect mmx to i32 conversion through a v2i32 elt extract.
21924   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21925       N->getValueType(0) == MVT::i32 &&
21926       InputVector.getValueType() == MVT::v2i32) {
21927
21928     // The bitcast source is a direct mmx result.
21929     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21930     if (MMXSrc.getValueType() == MVT::x86mmx)
21931       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21932                          N->getValueType(0),
21933                          InputVector.getNode()->getOperand(0));
21934
21935     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21936     SDValue MMXSrcOp = MMXSrc.getOperand(0);
21937     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21938         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21939         MMXSrcOp.getOpcode() == ISD::BITCAST &&
21940         MMXSrcOp.getValueType() == MVT::v1i64 &&
21941         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21942       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21943                          N->getValueType(0),
21944                          MMXSrcOp.getOperand(0));
21945   }
21946
21947   EVT VT = N->getValueType(0);
21948
21949   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21950       InputVector.getOpcode() == ISD::BITCAST &&
21951       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21952     uint64_t ExtractedElt =
21953           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21954     uint64_t InputValue =
21955           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21956     uint64_t Res = (InputValue >> ExtractedElt) & 1;
21957     return DAG.getConstant(Res, dl, MVT::i1);
21958   }
21959   // Only operate on vectors of 4 elements, where the alternative shuffling
21960   // gets to be more expensive.
21961   if (InputVector.getValueType() != MVT::v4i32)
21962     return SDValue();
21963
21964   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21965   // single use which is a sign-extend or zero-extend, and all elements are
21966   // used.
21967   SmallVector<SDNode *, 4> Uses;
21968   unsigned ExtractedElements = 0;
21969   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21970        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21971     if (UI.getUse().getResNo() != InputVector.getResNo())
21972       return SDValue();
21973
21974     SDNode *Extract = *UI;
21975     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21976       return SDValue();
21977
21978     if (Extract->getValueType(0) != MVT::i32)
21979       return SDValue();
21980     if (!Extract->hasOneUse())
21981       return SDValue();
21982     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21983         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21984       return SDValue();
21985     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21986       return SDValue();
21987
21988     // Record which element was extracted.
21989     ExtractedElements |=
21990       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21991
21992     Uses.push_back(Extract);
21993   }
21994
21995   // If not all the elements were used, this may not be worthwhile.
21996   if (ExtractedElements != 15)
21997     return SDValue();
21998
21999   // Ok, we've now decided to do the transformation.
22000   // If 64-bit shifts are legal, use the extract-shift sequence,
22001   // otherwise bounce the vector off the cache.
22002   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22003   SDValue Vals[4];
22004
22005   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22006     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22007     auto &DL = DAG.getDataLayout();
22008     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22009     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22010       DAG.getConstant(0, dl, VecIdxTy));
22011     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22012       DAG.getConstant(1, dl, VecIdxTy));
22013
22014     SDValue ShAmt = DAG.getConstant(
22015         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22016     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22017     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22018       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22019     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22020     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22021       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22022   } else {
22023     // Store the value to a temporary stack slot.
22024     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22025     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22026       MachinePointerInfo(), false, false, 0);
22027
22028     EVT ElementType = InputVector.getValueType().getVectorElementType();
22029     unsigned EltSize = ElementType.getSizeInBits() / 8;
22030
22031     // Replace each use (extract) with a load of the appropriate element.
22032     for (unsigned i = 0; i < 4; ++i) {
22033       uint64_t Offset = EltSize * i;
22034       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22035       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22036
22037       SDValue ScalarAddr =
22038           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22039
22040       // Load the scalar.
22041       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22042                             ScalarAddr, MachinePointerInfo(),
22043                             false, false, false, 0);
22044
22045     }
22046   }
22047
22048   // Replace the extracts
22049   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22050     UE = Uses.end(); UI != UE; ++UI) {
22051     SDNode *Extract = *UI;
22052
22053     SDValue Idx = Extract->getOperand(1);
22054     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22055     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22056   }
22057
22058   // The replacement was made in place; don't return anything.
22059   return SDValue();
22060 }
22061
22062 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22063 static std::pair<unsigned, bool>
22064 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22065                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22066   if (!VT.isVector())
22067     return std::make_pair(0, false);
22068
22069   bool NeedSplit = false;
22070   switch (VT.getSimpleVT().SimpleTy) {
22071   default: return std::make_pair(0, false);
22072   case MVT::v4i64:
22073   case MVT::v2i64:
22074     if (!Subtarget->hasVLX())
22075       return std::make_pair(0, false);
22076     break;
22077   case MVT::v64i8:
22078   case MVT::v32i16:
22079     if (!Subtarget->hasBWI())
22080       return std::make_pair(0, false);
22081     break;
22082   case MVT::v16i32:
22083   case MVT::v8i64:
22084     if (!Subtarget->hasAVX512())
22085       return std::make_pair(0, false);
22086     break;
22087   case MVT::v32i8:
22088   case MVT::v16i16:
22089   case MVT::v8i32:
22090     if (!Subtarget->hasAVX2())
22091       NeedSplit = true;
22092     if (!Subtarget->hasAVX())
22093       return std::make_pair(0, false);
22094     break;
22095   case MVT::v16i8:
22096   case MVT::v8i16:
22097   case MVT::v4i32:
22098     if (!Subtarget->hasSSE2())
22099       return std::make_pair(0, false);
22100   }
22101
22102   // SSE2 has only a small subset of the operations.
22103   bool hasUnsigned = Subtarget->hasSSE41() ||
22104                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22105   bool hasSigned = Subtarget->hasSSE41() ||
22106                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22107
22108   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22109
22110   unsigned Opc = 0;
22111   // Check for x CC y ? x : y.
22112   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22113       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22114     switch (CC) {
22115     default: break;
22116     case ISD::SETULT:
22117     case ISD::SETULE:
22118       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22119     case ISD::SETUGT:
22120     case ISD::SETUGE:
22121       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22122     case ISD::SETLT:
22123     case ISD::SETLE:
22124       Opc = hasSigned ? ISD::SMIN : 0; break;
22125     case ISD::SETGT:
22126     case ISD::SETGE:
22127       Opc = hasSigned ? ISD::SMAX : 0; break;
22128     }
22129   // Check for x CC y ? y : x -- a min/max with reversed arms.
22130   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22131              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22132     switch (CC) {
22133     default: break;
22134     case ISD::SETULT:
22135     case ISD::SETULE:
22136       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22137     case ISD::SETUGT:
22138     case ISD::SETUGE:
22139       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22140     case ISD::SETLT:
22141     case ISD::SETLE:
22142       Opc = hasSigned ? ISD::SMAX : 0; break;
22143     case ISD::SETGT:
22144     case ISD::SETGE:
22145       Opc = hasSigned ? ISD::SMIN : 0; break;
22146     }
22147   }
22148
22149   return std::make_pair(Opc, NeedSplit);
22150 }
22151
22152 static SDValue
22153 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22154                                       const X86Subtarget *Subtarget) {
22155   SDLoc dl(N);
22156   SDValue Cond = N->getOperand(0);
22157   SDValue LHS = N->getOperand(1);
22158   SDValue RHS = N->getOperand(2);
22159
22160   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22161     SDValue CondSrc = Cond->getOperand(0);
22162     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22163       Cond = CondSrc->getOperand(0);
22164   }
22165
22166   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22167     return SDValue();
22168
22169   // A vselect where all conditions and data are constants can be optimized into
22170   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22171   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22172       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22173     return SDValue();
22174
22175   unsigned MaskValue = 0;
22176   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22177     return SDValue();
22178
22179   MVT VT = N->getSimpleValueType(0);
22180   unsigned NumElems = VT.getVectorNumElements();
22181   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22182   for (unsigned i = 0; i < NumElems; ++i) {
22183     // Be sure we emit undef where we can.
22184     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22185       ShuffleMask[i] = -1;
22186     else
22187       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22188   }
22189
22190   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22191   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22192     return SDValue();
22193   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22194 }
22195
22196 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22197 /// nodes.
22198 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22199                                     TargetLowering::DAGCombinerInfo &DCI,
22200                                     const X86Subtarget *Subtarget) {
22201   SDLoc DL(N);
22202   SDValue Cond = N->getOperand(0);
22203   // Get the LHS/RHS of the select.
22204   SDValue LHS = N->getOperand(1);
22205   SDValue RHS = N->getOperand(2);
22206   EVT VT = LHS.getValueType();
22207   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22208
22209   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22210   // instructions match the semantics of the common C idiom x<y?x:y but not
22211   // x<=y?x:y, because of how they handle negative zero (which can be
22212   // ignored in unsafe-math mode).
22213   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22214   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22215       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22216       (Subtarget->hasSSE2() ||
22217        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22218     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22219
22220     unsigned Opcode = 0;
22221     // Check for x CC y ? x : y.
22222     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22223         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22224       switch (CC) {
22225       default: break;
22226       case ISD::SETULT:
22227         // Converting this to a min would handle NaNs incorrectly, and swapping
22228         // the operands would cause it to handle comparisons between positive
22229         // and negative zero incorrectly.
22230         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22231           if (!DAG.getTarget().Options.UnsafeFPMath &&
22232               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22233             break;
22234           std::swap(LHS, RHS);
22235         }
22236         Opcode = X86ISD::FMIN;
22237         break;
22238       case ISD::SETOLE:
22239         // Converting this to a min would handle comparisons between positive
22240         // and negative zero incorrectly.
22241         if (!DAG.getTarget().Options.UnsafeFPMath &&
22242             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22243           break;
22244         Opcode = X86ISD::FMIN;
22245         break;
22246       case ISD::SETULE:
22247         // Converting this to a min would handle both negative zeros and NaNs
22248         // incorrectly, but we can swap the operands to fix both.
22249         std::swap(LHS, RHS);
22250       case ISD::SETOLT:
22251       case ISD::SETLT:
22252       case ISD::SETLE:
22253         Opcode = X86ISD::FMIN;
22254         break;
22255
22256       case ISD::SETOGE:
22257         // Converting this to a max would handle comparisons between positive
22258         // and negative zero incorrectly.
22259         if (!DAG.getTarget().Options.UnsafeFPMath &&
22260             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22261           break;
22262         Opcode = X86ISD::FMAX;
22263         break;
22264       case ISD::SETUGT:
22265         // Converting this to a max would handle NaNs incorrectly, and swapping
22266         // the operands would cause it to handle comparisons between positive
22267         // and negative zero incorrectly.
22268         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22269           if (!DAG.getTarget().Options.UnsafeFPMath &&
22270               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22271             break;
22272           std::swap(LHS, RHS);
22273         }
22274         Opcode = X86ISD::FMAX;
22275         break;
22276       case ISD::SETUGE:
22277         // Converting this to a max would handle both negative zeros and NaNs
22278         // incorrectly, but we can swap the operands to fix both.
22279         std::swap(LHS, RHS);
22280       case ISD::SETOGT:
22281       case ISD::SETGT:
22282       case ISD::SETGE:
22283         Opcode = X86ISD::FMAX;
22284         break;
22285       }
22286     // Check for x CC y ? y : x -- a min/max with reversed arms.
22287     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22288                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22289       switch (CC) {
22290       default: break;
22291       case ISD::SETOGE:
22292         // Converting this to a min would handle comparisons between positive
22293         // and negative zero incorrectly, and swapping the operands would
22294         // cause it to handle NaNs incorrectly.
22295         if (!DAG.getTarget().Options.UnsafeFPMath &&
22296             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22297           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22298             break;
22299           std::swap(LHS, RHS);
22300         }
22301         Opcode = X86ISD::FMIN;
22302         break;
22303       case ISD::SETUGT:
22304         // Converting this to a min would handle NaNs incorrectly.
22305         if (!DAG.getTarget().Options.UnsafeFPMath &&
22306             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22307           break;
22308         Opcode = X86ISD::FMIN;
22309         break;
22310       case ISD::SETUGE:
22311         // Converting this to a min would handle both negative zeros and NaNs
22312         // incorrectly, but we can swap the operands to fix both.
22313         std::swap(LHS, RHS);
22314       case ISD::SETOGT:
22315       case ISD::SETGT:
22316       case ISD::SETGE:
22317         Opcode = X86ISD::FMIN;
22318         break;
22319
22320       case ISD::SETULT:
22321         // Converting this to a max would handle NaNs incorrectly.
22322         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22323           break;
22324         Opcode = X86ISD::FMAX;
22325         break;
22326       case ISD::SETOLE:
22327         // Converting this to a max would handle comparisons between positive
22328         // and negative zero incorrectly, and swapping the operands would
22329         // cause it to handle NaNs incorrectly.
22330         if (!DAG.getTarget().Options.UnsafeFPMath &&
22331             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22332           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22333             break;
22334           std::swap(LHS, RHS);
22335         }
22336         Opcode = X86ISD::FMAX;
22337         break;
22338       case ISD::SETULE:
22339         // Converting this to a max would handle both negative zeros and NaNs
22340         // incorrectly, but we can swap the operands to fix both.
22341         std::swap(LHS, RHS);
22342       case ISD::SETOLT:
22343       case ISD::SETLT:
22344       case ISD::SETLE:
22345         Opcode = X86ISD::FMAX;
22346         break;
22347       }
22348     }
22349
22350     if (Opcode)
22351       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22352   }
22353
22354   EVT CondVT = Cond.getValueType();
22355   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22356       CondVT.getVectorElementType() == MVT::i1) {
22357     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22358     // lowering on KNL. In this case we convert it to
22359     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22360     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22361     // Since SKX these selects have a proper lowering.
22362     EVT OpVT = LHS.getValueType();
22363     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22364         (OpVT.getVectorElementType() == MVT::i8 ||
22365          OpVT.getVectorElementType() == MVT::i16) &&
22366         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22367       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22368       DCI.AddToWorklist(Cond.getNode());
22369       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22370     }
22371   }
22372   // If this is a select between two integer constants, try to do some
22373   // optimizations.
22374   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22375     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22376       // Don't do this for crazy integer types.
22377       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22378         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22379         // so that TrueC (the true value) is larger than FalseC.
22380         bool NeedsCondInvert = false;
22381
22382         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22383             // Efficiently invertible.
22384             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22385              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22386               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22387           NeedsCondInvert = true;
22388           std::swap(TrueC, FalseC);
22389         }
22390
22391         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22392         if (FalseC->getAPIntValue() == 0 &&
22393             TrueC->getAPIntValue().isPowerOf2()) {
22394           if (NeedsCondInvert) // Invert the condition if needed.
22395             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22396                                DAG.getConstant(1, DL, Cond.getValueType()));
22397
22398           // Zero extend the condition if needed.
22399           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22400
22401           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22402           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22403                              DAG.getConstant(ShAmt, DL, MVT::i8));
22404         }
22405
22406         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22407         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22408           if (NeedsCondInvert) // Invert the condition if needed.
22409             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22410                                DAG.getConstant(1, DL, Cond.getValueType()));
22411
22412           // Zero extend the condition if needed.
22413           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22414                              FalseC->getValueType(0), Cond);
22415           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22416                              SDValue(FalseC, 0));
22417         }
22418
22419         // Optimize cases that will turn into an LEA instruction.  This requires
22420         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22421         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22422           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22423           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22424
22425           bool isFastMultiplier = false;
22426           if (Diff < 10) {
22427             switch ((unsigned char)Diff) {
22428               default: break;
22429               case 1:  // result = add base, cond
22430               case 2:  // result = lea base(    , cond*2)
22431               case 3:  // result = lea base(cond, cond*2)
22432               case 4:  // result = lea base(    , cond*4)
22433               case 5:  // result = lea base(cond, cond*4)
22434               case 8:  // result = lea base(    , cond*8)
22435               case 9:  // result = lea base(cond, cond*8)
22436                 isFastMultiplier = true;
22437                 break;
22438             }
22439           }
22440
22441           if (isFastMultiplier) {
22442             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22443             if (NeedsCondInvert) // Invert the condition if needed.
22444               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22445                                  DAG.getConstant(1, DL, Cond.getValueType()));
22446
22447             // Zero extend the condition if needed.
22448             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22449                                Cond);
22450             // Scale the condition by the difference.
22451             if (Diff != 1)
22452               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22453                                  DAG.getConstant(Diff, DL,
22454                                                  Cond.getValueType()));
22455
22456             // Add the base if non-zero.
22457             if (FalseC->getAPIntValue() != 0)
22458               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22459                                  SDValue(FalseC, 0));
22460             return Cond;
22461           }
22462         }
22463       }
22464   }
22465
22466   // Canonicalize max and min:
22467   // (x > y) ? x : y -> (x >= y) ? x : y
22468   // (x < y) ? x : y -> (x <= y) ? x : y
22469   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22470   // the need for an extra compare
22471   // against zero. e.g.
22472   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22473   // subl   %esi, %edi
22474   // testl  %edi, %edi
22475   // movl   $0, %eax
22476   // cmovgl %edi, %eax
22477   // =>
22478   // xorl   %eax, %eax
22479   // subl   %esi, $edi
22480   // cmovsl %eax, %edi
22481   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22482       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22483       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22484     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22485     switch (CC) {
22486     default: break;
22487     case ISD::SETLT:
22488     case ISD::SETGT: {
22489       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22490       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22491                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22492       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22493     }
22494     }
22495   }
22496
22497   // Early exit check
22498   if (!TLI.isTypeLegal(VT))
22499     return SDValue();
22500
22501   // Match VSELECTs into subs with unsigned saturation.
22502   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22503       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22504       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22505        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22506     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22507
22508     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22509     // left side invert the predicate to simplify logic below.
22510     SDValue Other;
22511     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22512       Other = RHS;
22513       CC = ISD::getSetCCInverse(CC, true);
22514     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22515       Other = LHS;
22516     }
22517
22518     if (Other.getNode() && Other->getNumOperands() == 2 &&
22519         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22520       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22521       SDValue CondRHS = Cond->getOperand(1);
22522
22523       // Look for a general sub with unsigned saturation first.
22524       // x >= y ? x-y : 0 --> subus x, y
22525       // x >  y ? x-y : 0 --> subus x, y
22526       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22527           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22528         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22529
22530       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22531         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22532           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22533             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22534               // If the RHS is a constant we have to reverse the const
22535               // canonicalization.
22536               // x > C-1 ? x+-C : 0 --> subus x, C
22537               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22538                   CondRHSConst->getAPIntValue() ==
22539                       (-OpRHSConst->getAPIntValue() - 1))
22540                 return DAG.getNode(
22541                     X86ISD::SUBUS, DL, VT, OpLHS,
22542                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22543
22544           // Another special case: If C was a sign bit, the sub has been
22545           // canonicalized into a xor.
22546           // FIXME: Would it be better to use computeKnownBits to determine
22547           //        whether it's safe to decanonicalize the xor?
22548           // x s< 0 ? x^C : 0 --> subus x, C
22549           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22550               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22551               OpRHSConst->getAPIntValue().isSignBit())
22552             // Note that we have to rebuild the RHS constant here to ensure we
22553             // don't rely on particular values of undef lanes.
22554             return DAG.getNode(
22555                 X86ISD::SUBUS, DL, VT, OpLHS,
22556                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22557         }
22558     }
22559   }
22560
22561   // Try to match a min/max vector operation.
22562   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22563     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22564     unsigned Opc = ret.first;
22565     bool NeedSplit = ret.second;
22566
22567     if (Opc && NeedSplit) {
22568       unsigned NumElems = VT.getVectorNumElements();
22569       // Extract the LHS vectors
22570       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22571       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22572
22573       // Extract the RHS vectors
22574       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22575       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22576
22577       // Create min/max for each subvector
22578       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22579       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22580
22581       // Merge the result
22582       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22583     } else if (Opc)
22584       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22585   }
22586
22587   // Simplify vector selection if condition value type matches vselect
22588   // operand type
22589   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22590     assert(Cond.getValueType().isVector() &&
22591            "vector select expects a vector selector!");
22592
22593     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22594     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22595
22596     // Try invert the condition if true value is not all 1s and false value
22597     // is not all 0s.
22598     if (!TValIsAllOnes && !FValIsAllZeros &&
22599         // Check if the selector will be produced by CMPP*/PCMP*
22600         Cond.getOpcode() == ISD::SETCC &&
22601         // Check if SETCC has already been promoted
22602         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22603             CondVT) {
22604       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22605       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22606
22607       if (TValIsAllZeros || FValIsAllOnes) {
22608         SDValue CC = Cond.getOperand(2);
22609         ISD::CondCode NewCC =
22610           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22611                                Cond.getOperand(0).getValueType().isInteger());
22612         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22613         std::swap(LHS, RHS);
22614         TValIsAllOnes = FValIsAllOnes;
22615         FValIsAllZeros = TValIsAllZeros;
22616       }
22617     }
22618
22619     if (TValIsAllOnes || FValIsAllZeros) {
22620       SDValue Ret;
22621
22622       if (TValIsAllOnes && FValIsAllZeros)
22623         Ret = Cond;
22624       else if (TValIsAllOnes)
22625         Ret =
22626             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22627       else if (FValIsAllZeros)
22628         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22629                           DAG.getBitcast(CondVT, LHS));
22630
22631       return DAG.getBitcast(VT, Ret);
22632     }
22633   }
22634
22635   // We should generate an X86ISD::BLENDI from a vselect if its argument
22636   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22637   // constants. This specific pattern gets generated when we split a
22638   // selector for a 512 bit vector in a machine without AVX512 (but with
22639   // 256-bit vectors), during legalization:
22640   //
22641   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22642   //
22643   // Iff we find this pattern and the build_vectors are built from
22644   // constants, we translate the vselect into a shuffle_vector that we
22645   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22646   if ((N->getOpcode() == ISD::VSELECT ||
22647        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22648       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22649     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22650     if (Shuffle.getNode())
22651       return Shuffle;
22652   }
22653
22654   // If this is a *dynamic* select (non-constant condition) and we can match
22655   // this node with one of the variable blend instructions, restructure the
22656   // condition so that the blends can use the high bit of each element and use
22657   // SimplifyDemandedBits to simplify the condition operand.
22658   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22659       !DCI.isBeforeLegalize() &&
22660       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22661     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22662
22663     // Don't optimize vector selects that map to mask-registers.
22664     if (BitWidth == 1)
22665       return SDValue();
22666
22667     // We can only handle the cases where VSELECT is directly legal on the
22668     // subtarget. We custom lower VSELECT nodes with constant conditions and
22669     // this makes it hard to see whether a dynamic VSELECT will correctly
22670     // lower, so we both check the operation's status and explicitly handle the
22671     // cases where a *dynamic* blend will fail even though a constant-condition
22672     // blend could be custom lowered.
22673     // FIXME: We should find a better way to handle this class of problems.
22674     // Potentially, we should combine constant-condition vselect nodes
22675     // pre-legalization into shuffles and not mark as many types as custom
22676     // lowered.
22677     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22678       return SDValue();
22679     // FIXME: We don't support i16-element blends currently. We could and
22680     // should support them by making *all* the bits in the condition be set
22681     // rather than just the high bit and using an i8-element blend.
22682     if (VT.getScalarType() == MVT::i16)
22683       return SDValue();
22684     // Dynamic blending was only available from SSE4.1 onward.
22685     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22686       return SDValue();
22687     // Byte blends are only available in AVX2
22688     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22689         !Subtarget->hasAVX2())
22690       return SDValue();
22691
22692     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22693     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22694
22695     APInt KnownZero, KnownOne;
22696     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22697                                           DCI.isBeforeLegalizeOps());
22698     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22699         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22700                                  TLO)) {
22701       // If we changed the computation somewhere in the DAG, this change
22702       // will affect all users of Cond.
22703       // Make sure it is fine and update all the nodes so that we do not
22704       // use the generic VSELECT anymore. Otherwise, we may perform
22705       // wrong optimizations as we messed up with the actual expectation
22706       // for the vector boolean values.
22707       if (Cond != TLO.Old) {
22708         // Check all uses of that condition operand to check whether it will be
22709         // consumed by non-BLEND instructions, which may depend on all bits are
22710         // set properly.
22711         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22712              I != E; ++I)
22713           if (I->getOpcode() != ISD::VSELECT)
22714             // TODO: Add other opcodes eventually lowered into BLEND.
22715             return SDValue();
22716
22717         // Update all the users of the condition, before committing the change,
22718         // so that the VSELECT optimizations that expect the correct vector
22719         // boolean value will not be triggered.
22720         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22721              I != E; ++I)
22722           DAG.ReplaceAllUsesOfValueWith(
22723               SDValue(*I, 0),
22724               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22725                           Cond, I->getOperand(1), I->getOperand(2)));
22726         DCI.CommitTargetLoweringOpt(TLO);
22727         return SDValue();
22728       }
22729       // At this point, only Cond is changed. Change the condition
22730       // just for N to keep the opportunity to optimize all other
22731       // users their own way.
22732       DAG.ReplaceAllUsesOfValueWith(
22733           SDValue(N, 0),
22734           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22735                       TLO.New, N->getOperand(1), N->getOperand(2)));
22736       return SDValue();
22737     }
22738   }
22739
22740   return SDValue();
22741 }
22742
22743 // Check whether a boolean test is testing a boolean value generated by
22744 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22745 // code.
22746 //
22747 // Simplify the following patterns:
22748 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22749 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22750 // to (Op EFLAGS Cond)
22751 //
22752 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22753 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22754 // to (Op EFLAGS !Cond)
22755 //
22756 // where Op could be BRCOND or CMOV.
22757 //
22758 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22759   // Quit if not CMP and SUB with its value result used.
22760   if (Cmp.getOpcode() != X86ISD::CMP &&
22761       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22762       return SDValue();
22763
22764   // Quit if not used as a boolean value.
22765   if (CC != X86::COND_E && CC != X86::COND_NE)
22766     return SDValue();
22767
22768   // Check CMP operands. One of them should be 0 or 1 and the other should be
22769   // an SetCC or extended from it.
22770   SDValue Op1 = Cmp.getOperand(0);
22771   SDValue Op2 = Cmp.getOperand(1);
22772
22773   SDValue SetCC;
22774   const ConstantSDNode* C = nullptr;
22775   bool needOppositeCond = (CC == X86::COND_E);
22776   bool checkAgainstTrue = false; // Is it a comparison against 1?
22777
22778   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22779     SetCC = Op2;
22780   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22781     SetCC = Op1;
22782   else // Quit if all operands are not constants.
22783     return SDValue();
22784
22785   if (C->getZExtValue() == 1) {
22786     needOppositeCond = !needOppositeCond;
22787     checkAgainstTrue = true;
22788   } else if (C->getZExtValue() != 0)
22789     // Quit if the constant is neither 0 or 1.
22790     return SDValue();
22791
22792   bool truncatedToBoolWithAnd = false;
22793   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22794   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22795          SetCC.getOpcode() == ISD::TRUNCATE ||
22796          SetCC.getOpcode() == ISD::AND) {
22797     if (SetCC.getOpcode() == ISD::AND) {
22798       int OpIdx = -1;
22799       ConstantSDNode *CS;
22800       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22801           CS->getZExtValue() == 1)
22802         OpIdx = 1;
22803       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22804           CS->getZExtValue() == 1)
22805         OpIdx = 0;
22806       if (OpIdx == -1)
22807         break;
22808       SetCC = SetCC.getOperand(OpIdx);
22809       truncatedToBoolWithAnd = true;
22810     } else
22811       SetCC = SetCC.getOperand(0);
22812   }
22813
22814   switch (SetCC.getOpcode()) {
22815   case X86ISD::SETCC_CARRY:
22816     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22817     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22818     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22819     // truncated to i1 using 'and'.
22820     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22821       break;
22822     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22823            "Invalid use of SETCC_CARRY!");
22824     // FALL THROUGH
22825   case X86ISD::SETCC:
22826     // Set the condition code or opposite one if necessary.
22827     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22828     if (needOppositeCond)
22829       CC = X86::GetOppositeBranchCondition(CC);
22830     return SetCC.getOperand(1);
22831   case X86ISD::CMOV: {
22832     // Check whether false/true value has canonical one, i.e. 0 or 1.
22833     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22834     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22835     // Quit if true value is not a constant.
22836     if (!TVal)
22837       return SDValue();
22838     // Quit if false value is not a constant.
22839     if (!FVal) {
22840       SDValue Op = SetCC.getOperand(0);
22841       // Skip 'zext' or 'trunc' node.
22842       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22843           Op.getOpcode() == ISD::TRUNCATE)
22844         Op = Op.getOperand(0);
22845       // A special case for rdrand/rdseed, where 0 is set if false cond is
22846       // found.
22847       if ((Op.getOpcode() != X86ISD::RDRAND &&
22848            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22849         return SDValue();
22850     }
22851     // Quit if false value is not the constant 0 or 1.
22852     bool FValIsFalse = true;
22853     if (FVal && FVal->getZExtValue() != 0) {
22854       if (FVal->getZExtValue() != 1)
22855         return SDValue();
22856       // If FVal is 1, opposite cond is needed.
22857       needOppositeCond = !needOppositeCond;
22858       FValIsFalse = false;
22859     }
22860     // Quit if TVal is not the constant opposite of FVal.
22861     if (FValIsFalse && TVal->getZExtValue() != 1)
22862       return SDValue();
22863     if (!FValIsFalse && TVal->getZExtValue() != 0)
22864       return SDValue();
22865     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22866     if (needOppositeCond)
22867       CC = X86::GetOppositeBranchCondition(CC);
22868     return SetCC.getOperand(3);
22869   }
22870   }
22871
22872   return SDValue();
22873 }
22874
22875 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22876 /// Match:
22877 ///   (X86or (X86setcc) (X86setcc))
22878 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22879 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22880                                            X86::CondCode &CC1, SDValue &Flags,
22881                                            bool &isAnd) {
22882   if (Cond->getOpcode() == X86ISD::CMP) {
22883     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22884     if (!CondOp1C || !CondOp1C->isNullValue())
22885       return false;
22886
22887     Cond = Cond->getOperand(0);
22888   }
22889
22890   isAnd = false;
22891
22892   SDValue SetCC0, SetCC1;
22893   switch (Cond->getOpcode()) {
22894   default: return false;
22895   case ISD::AND:
22896   case X86ISD::AND:
22897     isAnd = true;
22898     // fallthru
22899   case ISD::OR:
22900   case X86ISD::OR:
22901     SetCC0 = Cond->getOperand(0);
22902     SetCC1 = Cond->getOperand(1);
22903     break;
22904   };
22905
22906   // Make sure we have SETCC nodes, using the same flags value.
22907   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22908       SetCC1.getOpcode() != X86ISD::SETCC ||
22909       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22910     return false;
22911
22912   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22913   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22914   Flags = SetCC0->getOperand(1);
22915   return true;
22916 }
22917
22918 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22919 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22920                                   TargetLowering::DAGCombinerInfo &DCI,
22921                                   const X86Subtarget *Subtarget) {
22922   SDLoc DL(N);
22923
22924   // If the flag operand isn't dead, don't touch this CMOV.
22925   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22926     return SDValue();
22927
22928   SDValue FalseOp = N->getOperand(0);
22929   SDValue TrueOp = N->getOperand(1);
22930   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22931   SDValue Cond = N->getOperand(3);
22932
22933   if (CC == X86::COND_E || CC == X86::COND_NE) {
22934     switch (Cond.getOpcode()) {
22935     default: break;
22936     case X86ISD::BSR:
22937     case X86ISD::BSF:
22938       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22939       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22940         return (CC == X86::COND_E) ? FalseOp : TrueOp;
22941     }
22942   }
22943
22944   SDValue Flags;
22945
22946   Flags = checkBoolTestSetCCCombine(Cond, CC);
22947   if (Flags.getNode() &&
22948       // Extra check as FCMOV only supports a subset of X86 cond.
22949       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22950     SDValue Ops[] = { FalseOp, TrueOp,
22951                       DAG.getConstant(CC, DL, MVT::i8), Flags };
22952     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22953   }
22954
22955   // If this is a select between two integer constants, try to do some
22956   // optimizations.  Note that the operands are ordered the opposite of SELECT
22957   // operands.
22958   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22959     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22960       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22961       // larger than FalseC (the false value).
22962       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22963         CC = X86::GetOppositeBranchCondition(CC);
22964         std::swap(TrueC, FalseC);
22965         std::swap(TrueOp, FalseOp);
22966       }
22967
22968       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22969       // This is efficient for any integer data type (including i8/i16) and
22970       // shift amount.
22971       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22972         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22973                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22974
22975         // Zero extend the condition if needed.
22976         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22977
22978         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22979         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22980                            DAG.getConstant(ShAmt, DL, MVT::i8));
22981         if (N->getNumValues() == 2)  // Dead flag value?
22982           return DCI.CombineTo(N, Cond, SDValue());
22983         return Cond;
22984       }
22985
22986       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22987       // for any integer data type, including i8/i16.
22988       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22989         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22990                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22991
22992         // Zero extend the condition if needed.
22993         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22994                            FalseC->getValueType(0), Cond);
22995         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22996                            SDValue(FalseC, 0));
22997
22998         if (N->getNumValues() == 2)  // Dead flag value?
22999           return DCI.CombineTo(N, Cond, SDValue());
23000         return Cond;
23001       }
23002
23003       // Optimize cases that will turn into an LEA instruction.  This requires
23004       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23005       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23006         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23007         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23008
23009         bool isFastMultiplier = false;
23010         if (Diff < 10) {
23011           switch ((unsigned char)Diff) {
23012           default: break;
23013           case 1:  // result = add base, cond
23014           case 2:  // result = lea base(    , cond*2)
23015           case 3:  // result = lea base(cond, cond*2)
23016           case 4:  // result = lea base(    , cond*4)
23017           case 5:  // result = lea base(cond, cond*4)
23018           case 8:  // result = lea base(    , cond*8)
23019           case 9:  // result = lea base(cond, cond*8)
23020             isFastMultiplier = true;
23021             break;
23022           }
23023         }
23024
23025         if (isFastMultiplier) {
23026           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23027           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23028                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23029           // Zero extend the condition if needed.
23030           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23031                              Cond);
23032           // Scale the condition by the difference.
23033           if (Diff != 1)
23034             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23035                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23036
23037           // Add the base if non-zero.
23038           if (FalseC->getAPIntValue() != 0)
23039             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23040                                SDValue(FalseC, 0));
23041           if (N->getNumValues() == 2)  // Dead flag value?
23042             return DCI.CombineTo(N, Cond, SDValue());
23043           return Cond;
23044         }
23045       }
23046     }
23047   }
23048
23049   // Handle these cases:
23050   //   (select (x != c), e, c) -> select (x != c), e, x),
23051   //   (select (x == c), c, e) -> select (x == c), x, e)
23052   // where the c is an integer constant, and the "select" is the combination
23053   // of CMOV and CMP.
23054   //
23055   // The rationale for this change is that the conditional-move from a constant
23056   // needs two instructions, however, conditional-move from a register needs
23057   // only one instruction.
23058   //
23059   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23060   //  some instruction-combining opportunities. This opt needs to be
23061   //  postponed as late as possible.
23062   //
23063   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23064     // the DCI.xxxx conditions are provided to postpone the optimization as
23065     // late as possible.
23066
23067     ConstantSDNode *CmpAgainst = nullptr;
23068     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23069         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23070         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23071
23072       if (CC == X86::COND_NE &&
23073           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23074         CC = X86::GetOppositeBranchCondition(CC);
23075         std::swap(TrueOp, FalseOp);
23076       }
23077
23078       if (CC == X86::COND_E &&
23079           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23080         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23081                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23082         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23083       }
23084     }
23085   }
23086
23087   // Fold and/or of setcc's to double CMOV:
23088   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23089   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23090   //
23091   // This combine lets us generate:
23092   //   cmovcc1 (jcc1 if we don't have CMOV)
23093   //   cmovcc2 (same)
23094   // instead of:
23095   //   setcc1
23096   //   setcc2
23097   //   and/or
23098   //   cmovne (jne if we don't have CMOV)
23099   // When we can't use the CMOV instruction, it might increase branch
23100   // mispredicts.
23101   // When we can use CMOV, or when there is no mispredict, this improves
23102   // throughput and reduces register pressure.
23103   //
23104   if (CC == X86::COND_NE) {
23105     SDValue Flags;
23106     X86::CondCode CC0, CC1;
23107     bool isAndSetCC;
23108     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23109       if (isAndSetCC) {
23110         std::swap(FalseOp, TrueOp);
23111         CC0 = X86::GetOppositeBranchCondition(CC0);
23112         CC1 = X86::GetOppositeBranchCondition(CC1);
23113       }
23114
23115       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23116         Flags};
23117       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23118       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23119       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23120       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23121       return CMOV;
23122     }
23123   }
23124
23125   return SDValue();
23126 }
23127
23128 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23129                                                 const X86Subtarget *Subtarget) {
23130   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23131   switch (IntNo) {
23132   default: return SDValue();
23133   // SSE/AVX/AVX2 blend intrinsics.
23134   case Intrinsic::x86_avx2_pblendvb:
23135     // Don't try to simplify this intrinsic if we don't have AVX2.
23136     if (!Subtarget->hasAVX2())
23137       return SDValue();
23138     // FALL-THROUGH
23139   case Intrinsic::x86_avx_blendv_pd_256:
23140   case Intrinsic::x86_avx_blendv_ps_256:
23141     // Don't try to simplify this intrinsic if we don't have AVX.
23142     if (!Subtarget->hasAVX())
23143       return SDValue();
23144     // FALL-THROUGH
23145   case Intrinsic::x86_sse41_blendvps:
23146   case Intrinsic::x86_sse41_blendvpd:
23147   case Intrinsic::x86_sse41_pblendvb: {
23148     SDValue Op0 = N->getOperand(1);
23149     SDValue Op1 = N->getOperand(2);
23150     SDValue Mask = N->getOperand(3);
23151
23152     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23153     if (!Subtarget->hasSSE41())
23154       return SDValue();
23155
23156     // fold (blend A, A, Mask) -> A
23157     if (Op0 == Op1)
23158       return Op0;
23159     // fold (blend A, B, allZeros) -> A
23160     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23161       return Op0;
23162     // fold (blend A, B, allOnes) -> B
23163     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23164       return Op1;
23165
23166     // Simplify the case where the mask is a constant i32 value.
23167     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23168       if (C->isNullValue())
23169         return Op0;
23170       if (C->isAllOnesValue())
23171         return Op1;
23172     }
23173
23174     return SDValue();
23175   }
23176
23177   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23178   case Intrinsic::x86_sse2_psrai_w:
23179   case Intrinsic::x86_sse2_psrai_d:
23180   case Intrinsic::x86_avx2_psrai_w:
23181   case Intrinsic::x86_avx2_psrai_d:
23182   case Intrinsic::x86_sse2_psra_w:
23183   case Intrinsic::x86_sse2_psra_d:
23184   case Intrinsic::x86_avx2_psra_w:
23185   case Intrinsic::x86_avx2_psra_d: {
23186     SDValue Op0 = N->getOperand(1);
23187     SDValue Op1 = N->getOperand(2);
23188     EVT VT = Op0.getValueType();
23189     assert(VT.isVector() && "Expected a vector type!");
23190
23191     if (isa<BuildVectorSDNode>(Op1))
23192       Op1 = Op1.getOperand(0);
23193
23194     if (!isa<ConstantSDNode>(Op1))
23195       return SDValue();
23196
23197     EVT SVT = VT.getVectorElementType();
23198     unsigned SVTBits = SVT.getSizeInBits();
23199
23200     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23201     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23202     uint64_t ShAmt = C.getZExtValue();
23203
23204     // Don't try to convert this shift into a ISD::SRA if the shift
23205     // count is bigger than or equal to the element size.
23206     if (ShAmt >= SVTBits)
23207       return SDValue();
23208
23209     // Trivial case: if the shift count is zero, then fold this
23210     // into the first operand.
23211     if (ShAmt == 0)
23212       return Op0;
23213
23214     // Replace this packed shift intrinsic with a target independent
23215     // shift dag node.
23216     SDLoc DL(N);
23217     SDValue Splat = DAG.getConstant(C, DL, VT);
23218     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23219   }
23220   }
23221 }
23222
23223 /// PerformMulCombine - Optimize a single multiply with constant into two
23224 /// in order to implement it with two cheaper instructions, e.g.
23225 /// LEA + SHL, LEA + LEA.
23226 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23227                                  TargetLowering::DAGCombinerInfo &DCI) {
23228   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23229     return SDValue();
23230
23231   EVT VT = N->getValueType(0);
23232   if (VT != MVT::i64 && VT != MVT::i32)
23233     return SDValue();
23234
23235   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23236   if (!C)
23237     return SDValue();
23238   uint64_t MulAmt = C->getZExtValue();
23239   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23240     return SDValue();
23241
23242   uint64_t MulAmt1 = 0;
23243   uint64_t MulAmt2 = 0;
23244   if ((MulAmt % 9) == 0) {
23245     MulAmt1 = 9;
23246     MulAmt2 = MulAmt / 9;
23247   } else if ((MulAmt % 5) == 0) {
23248     MulAmt1 = 5;
23249     MulAmt2 = MulAmt / 5;
23250   } else if ((MulAmt % 3) == 0) {
23251     MulAmt1 = 3;
23252     MulAmt2 = MulAmt / 3;
23253   }
23254   if (MulAmt2 &&
23255       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23256     SDLoc DL(N);
23257
23258     if (isPowerOf2_64(MulAmt2) &&
23259         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23260       // If second multiplifer is pow2, issue it first. We want the multiply by
23261       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23262       // is an add.
23263       std::swap(MulAmt1, MulAmt2);
23264
23265     SDValue NewMul;
23266     if (isPowerOf2_64(MulAmt1))
23267       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23268                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23269     else
23270       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23271                            DAG.getConstant(MulAmt1, DL, VT));
23272
23273     if (isPowerOf2_64(MulAmt2))
23274       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23275                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23276     else
23277       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23278                            DAG.getConstant(MulAmt2, DL, VT));
23279
23280     // Do not add new nodes to DAG combiner worklist.
23281     DCI.CombineTo(N, NewMul, false);
23282   }
23283   return SDValue();
23284 }
23285
23286 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23287   SDValue N0 = N->getOperand(0);
23288   SDValue N1 = N->getOperand(1);
23289   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23290   EVT VT = N0.getValueType();
23291
23292   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23293   // since the result of setcc_c is all zero's or all ones.
23294   if (VT.isInteger() && !VT.isVector() &&
23295       N1C && N0.getOpcode() == ISD::AND &&
23296       N0.getOperand(1).getOpcode() == ISD::Constant) {
23297     SDValue N00 = N0.getOperand(0);
23298     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23299         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23300           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23301          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23302       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23303       APInt ShAmt = N1C->getAPIntValue();
23304       Mask = Mask.shl(ShAmt);
23305       if (Mask != 0) {
23306         SDLoc DL(N);
23307         return DAG.getNode(ISD::AND, DL, VT,
23308                            N00, DAG.getConstant(Mask, DL, VT));
23309       }
23310     }
23311   }
23312
23313   // Hardware support for vector shifts is sparse which makes us scalarize the
23314   // vector operations in many cases. Also, on sandybridge ADD is faster than
23315   // shl.
23316   // (shl V, 1) -> add V,V
23317   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23318     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23319       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23320       // We shift all of the values by one. In many cases we do not have
23321       // hardware support for this operation. This is better expressed as an ADD
23322       // of two values.
23323       if (N1SplatC->getAPIntValue() == 1)
23324         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23325     }
23326
23327   return SDValue();
23328 }
23329
23330 /// \brief Returns a vector of 0s if the node in input is a vector logical
23331 /// shift by a constant amount which is known to be bigger than or equal
23332 /// to the vector element size in bits.
23333 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23334                                       const X86Subtarget *Subtarget) {
23335   EVT VT = N->getValueType(0);
23336
23337   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23338       (!Subtarget->hasInt256() ||
23339        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23340     return SDValue();
23341
23342   SDValue Amt = N->getOperand(1);
23343   SDLoc DL(N);
23344   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23345     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23346       APInt ShiftAmt = AmtSplat->getAPIntValue();
23347       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23348
23349       // SSE2/AVX2 logical shifts always return a vector of 0s
23350       // if the shift amount is bigger than or equal to
23351       // the element size. The constant shift amount will be
23352       // encoded as a 8-bit immediate.
23353       if (ShiftAmt.trunc(8).uge(MaxAmount))
23354         return getZeroVector(VT, Subtarget, DAG, DL);
23355     }
23356
23357   return SDValue();
23358 }
23359
23360 /// PerformShiftCombine - Combine shifts.
23361 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23362                                    TargetLowering::DAGCombinerInfo &DCI,
23363                                    const X86Subtarget *Subtarget) {
23364   if (N->getOpcode() == ISD::SHL)
23365     if (SDValue V = PerformSHLCombine(N, DAG))
23366       return V;
23367
23368   // Try to fold this logical shift into a zero vector.
23369   if (N->getOpcode() != ISD::SRA)
23370     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23371       return V;
23372
23373   return SDValue();
23374 }
23375
23376 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23377 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23378 // and friends.  Likewise for OR -> CMPNEQSS.
23379 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23380                             TargetLowering::DAGCombinerInfo &DCI,
23381                             const X86Subtarget *Subtarget) {
23382   unsigned opcode;
23383
23384   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23385   // we're requiring SSE2 for both.
23386   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23387     SDValue N0 = N->getOperand(0);
23388     SDValue N1 = N->getOperand(1);
23389     SDValue CMP0 = N0->getOperand(1);
23390     SDValue CMP1 = N1->getOperand(1);
23391     SDLoc DL(N);
23392
23393     // The SETCCs should both refer to the same CMP.
23394     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23395       return SDValue();
23396
23397     SDValue CMP00 = CMP0->getOperand(0);
23398     SDValue CMP01 = CMP0->getOperand(1);
23399     EVT     VT    = CMP00.getValueType();
23400
23401     if (VT == MVT::f32 || VT == MVT::f64) {
23402       bool ExpectingFlags = false;
23403       // Check for any users that want flags:
23404       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23405            !ExpectingFlags && UI != UE; ++UI)
23406         switch (UI->getOpcode()) {
23407         default:
23408         case ISD::BR_CC:
23409         case ISD::BRCOND:
23410         case ISD::SELECT:
23411           ExpectingFlags = true;
23412           break;
23413         case ISD::CopyToReg:
23414         case ISD::SIGN_EXTEND:
23415         case ISD::ZERO_EXTEND:
23416         case ISD::ANY_EXTEND:
23417           break;
23418         }
23419
23420       if (!ExpectingFlags) {
23421         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23422         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23423
23424         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23425           X86::CondCode tmp = cc0;
23426           cc0 = cc1;
23427           cc1 = tmp;
23428         }
23429
23430         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23431             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23432           // FIXME: need symbolic constants for these magic numbers.
23433           // See X86ATTInstPrinter.cpp:printSSECC().
23434           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23435           if (Subtarget->hasAVX512()) {
23436             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23437                                          CMP01,
23438                                          DAG.getConstant(x86cc, DL, MVT::i8));
23439             if (N->getValueType(0) != MVT::i1)
23440               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23441                                  FSetCC);
23442             return FSetCC;
23443           }
23444           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23445                                               CMP00.getValueType(), CMP00, CMP01,
23446                                               DAG.getConstant(x86cc, DL,
23447                                                               MVT::i8));
23448
23449           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23450           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23451
23452           if (is64BitFP && !Subtarget->is64Bit()) {
23453             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23454             // 64-bit integer, since that's not a legal type. Since
23455             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23456             // bits, but can do this little dance to extract the lowest 32 bits
23457             // and work with those going forward.
23458             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23459                                            OnesOrZeroesF);
23460             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23461             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23462                                         Vector32, DAG.getIntPtrConstant(0, DL));
23463             IntVT = MVT::i32;
23464           }
23465
23466           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23467           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23468                                       DAG.getConstant(1, DL, IntVT));
23469           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23470                                               ANDed);
23471           return OneBitOfTruth;
23472         }
23473       }
23474     }
23475   }
23476   return SDValue();
23477 }
23478
23479 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23480 /// so it can be folded inside ANDNP.
23481 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23482   EVT VT = N->getValueType(0);
23483
23484   // Match direct AllOnes for 128 and 256-bit vectors
23485   if (ISD::isBuildVectorAllOnes(N))
23486     return true;
23487
23488   // Look through a bit convert.
23489   if (N->getOpcode() == ISD::BITCAST)
23490     N = N->getOperand(0).getNode();
23491
23492   // Sometimes the operand may come from a insert_subvector building a 256-bit
23493   // allones vector
23494   if (VT.is256BitVector() &&
23495       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23496     SDValue V1 = N->getOperand(0);
23497     SDValue V2 = N->getOperand(1);
23498
23499     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23500         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23501         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23502         ISD::isBuildVectorAllOnes(V2.getNode()))
23503       return true;
23504   }
23505
23506   return false;
23507 }
23508
23509 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23510 // register. In most cases we actually compare or select YMM-sized registers
23511 // and mixing the two types creates horrible code. This method optimizes
23512 // some of the transition sequences.
23513 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23514                                  TargetLowering::DAGCombinerInfo &DCI,
23515                                  const X86Subtarget *Subtarget) {
23516   EVT VT = N->getValueType(0);
23517   if (!VT.is256BitVector())
23518     return SDValue();
23519
23520   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23521           N->getOpcode() == ISD::ZERO_EXTEND ||
23522           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23523
23524   SDValue Narrow = N->getOperand(0);
23525   EVT NarrowVT = Narrow->getValueType(0);
23526   if (!NarrowVT.is128BitVector())
23527     return SDValue();
23528
23529   if (Narrow->getOpcode() != ISD::XOR &&
23530       Narrow->getOpcode() != ISD::AND &&
23531       Narrow->getOpcode() != ISD::OR)
23532     return SDValue();
23533
23534   SDValue N0  = Narrow->getOperand(0);
23535   SDValue N1  = Narrow->getOperand(1);
23536   SDLoc DL(Narrow);
23537
23538   // The Left side has to be a trunc.
23539   if (N0.getOpcode() != ISD::TRUNCATE)
23540     return SDValue();
23541
23542   // The type of the truncated inputs.
23543   EVT WideVT = N0->getOperand(0)->getValueType(0);
23544   if (WideVT != VT)
23545     return SDValue();
23546
23547   // The right side has to be a 'trunc' or a constant vector.
23548   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23549   ConstantSDNode *RHSConstSplat = nullptr;
23550   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23551     RHSConstSplat = RHSBV->getConstantSplatNode();
23552   if (!RHSTrunc && !RHSConstSplat)
23553     return SDValue();
23554
23555   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23556
23557   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23558     return SDValue();
23559
23560   // Set N0 and N1 to hold the inputs to the new wide operation.
23561   N0 = N0->getOperand(0);
23562   if (RHSConstSplat) {
23563     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23564                      SDValue(RHSConstSplat, 0));
23565     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23566     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23567   } else if (RHSTrunc) {
23568     N1 = N1->getOperand(0);
23569   }
23570
23571   // Generate the wide operation.
23572   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23573   unsigned Opcode = N->getOpcode();
23574   switch (Opcode) {
23575   case ISD::ANY_EXTEND:
23576     return Op;
23577   case ISD::ZERO_EXTEND: {
23578     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23579     APInt Mask = APInt::getAllOnesValue(InBits);
23580     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23581     return DAG.getNode(ISD::AND, DL, VT,
23582                        Op, DAG.getConstant(Mask, DL, VT));
23583   }
23584   case ISD::SIGN_EXTEND:
23585     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23586                        Op, DAG.getValueType(NarrowVT));
23587   default:
23588     llvm_unreachable("Unexpected opcode");
23589   }
23590 }
23591
23592 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23593                                  TargetLowering::DAGCombinerInfo &DCI,
23594                                  const X86Subtarget *Subtarget) {
23595   SDValue N0 = N->getOperand(0);
23596   SDValue N1 = N->getOperand(1);
23597   SDLoc DL(N);
23598
23599   // A vector zext_in_reg may be represented as a shuffle,
23600   // feeding into a bitcast (this represents anyext) feeding into
23601   // an and with a mask.
23602   // We'd like to try to combine that into a shuffle with zero
23603   // plus a bitcast, removing the and.
23604   if (N0.getOpcode() != ISD::BITCAST ||
23605       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23606     return SDValue();
23607
23608   // The other side of the AND should be a splat of 2^C, where C
23609   // is the number of bits in the source type.
23610   if (N1.getOpcode() == ISD::BITCAST)
23611     N1 = N1.getOperand(0);
23612   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23613     return SDValue();
23614   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23615
23616   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23617   EVT SrcType = Shuffle->getValueType(0);
23618
23619   // We expect a single-source shuffle
23620   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23621     return SDValue();
23622
23623   unsigned SrcSize = SrcType.getScalarSizeInBits();
23624
23625   APInt SplatValue, SplatUndef;
23626   unsigned SplatBitSize;
23627   bool HasAnyUndefs;
23628   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23629                                 SplatBitSize, HasAnyUndefs))
23630     return SDValue();
23631
23632   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23633   // Make sure the splat matches the mask we expect
23634   if (SplatBitSize > ResSize ||
23635       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23636     return SDValue();
23637
23638   // Make sure the input and output size make sense
23639   if (SrcSize >= ResSize || ResSize % SrcSize)
23640     return SDValue();
23641
23642   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23643   // The number of u's between each two values depends on the ratio between
23644   // the source and dest type.
23645   unsigned ZextRatio = ResSize / SrcSize;
23646   bool IsZext = true;
23647   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23648     if (i % ZextRatio) {
23649       if (Shuffle->getMaskElt(i) > 0) {
23650         // Expected undef
23651         IsZext = false;
23652         break;
23653       }
23654     } else {
23655       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23656         // Expected element number
23657         IsZext = false;
23658         break;
23659       }
23660     }
23661   }
23662
23663   if (!IsZext)
23664     return SDValue();
23665
23666   // Ok, perform the transformation - replace the shuffle with
23667   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23668   // (instead of undef) where the k elements come from the zero vector.
23669   SmallVector<int, 8> Mask;
23670   unsigned NumElems = SrcType.getVectorNumElements();
23671   for (unsigned i = 0; i < NumElems; ++i)
23672     if (i % ZextRatio)
23673       Mask.push_back(NumElems);
23674     else
23675       Mask.push_back(i / ZextRatio);
23676
23677   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23678     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23679   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23680 }
23681
23682 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23683                                  TargetLowering::DAGCombinerInfo &DCI,
23684                                  const X86Subtarget *Subtarget) {
23685   if (DCI.isBeforeLegalizeOps())
23686     return SDValue();
23687
23688   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23689     return Zext;
23690
23691   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23692     return R;
23693
23694   EVT VT = N->getValueType(0);
23695   SDValue N0 = N->getOperand(0);
23696   SDValue N1 = N->getOperand(1);
23697   SDLoc DL(N);
23698
23699   // Create BEXTR instructions
23700   // BEXTR is ((X >> imm) & (2**size-1))
23701   if (VT == MVT::i32 || VT == MVT::i64) {
23702     // Check for BEXTR.
23703     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23704         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23705       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23706       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23707       if (MaskNode && ShiftNode) {
23708         uint64_t Mask = MaskNode->getZExtValue();
23709         uint64_t Shift = ShiftNode->getZExtValue();
23710         if (isMask_64(Mask)) {
23711           uint64_t MaskSize = countPopulation(Mask);
23712           if (Shift + MaskSize <= VT.getSizeInBits())
23713             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23714                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23715                                                VT));
23716         }
23717       }
23718     } // BEXTR
23719
23720     return SDValue();
23721   }
23722
23723   // Want to form ANDNP nodes:
23724   // 1) In the hopes of then easily combining them with OR and AND nodes
23725   //    to form PBLEND/PSIGN.
23726   // 2) To match ANDN packed intrinsics
23727   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23728     return SDValue();
23729
23730   // Check LHS for vnot
23731   if (N0.getOpcode() == ISD::XOR &&
23732       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23733       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23734     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23735
23736   // Check RHS for vnot
23737   if (N1.getOpcode() == ISD::XOR &&
23738       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23739       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23740     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23741
23742   return SDValue();
23743 }
23744
23745 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23746                                 TargetLowering::DAGCombinerInfo &DCI,
23747                                 const X86Subtarget *Subtarget) {
23748   if (DCI.isBeforeLegalizeOps())
23749     return SDValue();
23750
23751   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23752     return R;
23753
23754   SDValue N0 = N->getOperand(0);
23755   SDValue N1 = N->getOperand(1);
23756   EVT VT = N->getValueType(0);
23757
23758   // look for psign/blend
23759   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23760     if (!Subtarget->hasSSSE3() ||
23761         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23762       return SDValue();
23763
23764     // Canonicalize pandn to RHS
23765     if (N0.getOpcode() == X86ISD::ANDNP)
23766       std::swap(N0, N1);
23767     // or (and (m, y), (pandn m, x))
23768     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23769       SDValue Mask = N1.getOperand(0);
23770       SDValue X    = N1.getOperand(1);
23771       SDValue Y;
23772       if (N0.getOperand(0) == Mask)
23773         Y = N0.getOperand(1);
23774       if (N0.getOperand(1) == Mask)
23775         Y = N0.getOperand(0);
23776
23777       // Check to see if the mask appeared in both the AND and ANDNP and
23778       if (!Y.getNode())
23779         return SDValue();
23780
23781       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23782       // Look through mask bitcast.
23783       if (Mask.getOpcode() == ISD::BITCAST)
23784         Mask = Mask.getOperand(0);
23785       if (X.getOpcode() == ISD::BITCAST)
23786         X = X.getOperand(0);
23787       if (Y.getOpcode() == ISD::BITCAST)
23788         Y = Y.getOperand(0);
23789
23790       EVT MaskVT = Mask.getValueType();
23791
23792       // Validate that the Mask operand is a vector sra node.
23793       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23794       // there is no psrai.b
23795       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23796       unsigned SraAmt = ~0;
23797       if (Mask.getOpcode() == ISD::SRA) {
23798         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23799           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23800             SraAmt = AmtConst->getZExtValue();
23801       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23802         SDValue SraC = Mask.getOperand(1);
23803         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23804       }
23805       if ((SraAmt + 1) != EltBits)
23806         return SDValue();
23807
23808       SDLoc DL(N);
23809
23810       // Now we know we at least have a plendvb with the mask val.  See if
23811       // we can form a psignb/w/d.
23812       // psign = x.type == y.type == mask.type && y = sub(0, x);
23813       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23814           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23815           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23816         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23817                "Unsupported VT for PSIGN");
23818         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23819         return DAG.getBitcast(VT, Mask);
23820       }
23821       // PBLENDVB only available on SSE 4.1
23822       if (!Subtarget->hasSSE41())
23823         return SDValue();
23824
23825       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23826
23827       X = DAG.getBitcast(BlendVT, X);
23828       Y = DAG.getBitcast(BlendVT, Y);
23829       Mask = DAG.getBitcast(BlendVT, Mask);
23830       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23831       return DAG.getBitcast(VT, Mask);
23832     }
23833   }
23834
23835   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23836     return SDValue();
23837
23838   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23839   MachineFunction &MF = DAG.getMachineFunction();
23840   bool OptForSize =
23841       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23842
23843   // SHLD/SHRD instructions have lower register pressure, but on some
23844   // platforms they have higher latency than the equivalent
23845   // series of shifts/or that would otherwise be generated.
23846   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23847   // have higher latencies and we are not optimizing for size.
23848   if (!OptForSize && Subtarget->isSHLDSlow())
23849     return SDValue();
23850
23851   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23852     std::swap(N0, N1);
23853   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23854     return SDValue();
23855   if (!N0.hasOneUse() || !N1.hasOneUse())
23856     return SDValue();
23857
23858   SDValue ShAmt0 = N0.getOperand(1);
23859   if (ShAmt0.getValueType() != MVT::i8)
23860     return SDValue();
23861   SDValue ShAmt1 = N1.getOperand(1);
23862   if (ShAmt1.getValueType() != MVT::i8)
23863     return SDValue();
23864   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23865     ShAmt0 = ShAmt0.getOperand(0);
23866   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23867     ShAmt1 = ShAmt1.getOperand(0);
23868
23869   SDLoc DL(N);
23870   unsigned Opc = X86ISD::SHLD;
23871   SDValue Op0 = N0.getOperand(0);
23872   SDValue Op1 = N1.getOperand(0);
23873   if (ShAmt0.getOpcode() == ISD::SUB) {
23874     Opc = X86ISD::SHRD;
23875     std::swap(Op0, Op1);
23876     std::swap(ShAmt0, ShAmt1);
23877   }
23878
23879   unsigned Bits = VT.getSizeInBits();
23880   if (ShAmt1.getOpcode() == ISD::SUB) {
23881     SDValue Sum = ShAmt1.getOperand(0);
23882     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23883       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23884       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23885         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23886       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23887         return DAG.getNode(Opc, DL, VT,
23888                            Op0, Op1,
23889                            DAG.getNode(ISD::TRUNCATE, DL,
23890                                        MVT::i8, ShAmt0));
23891     }
23892   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23893     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23894     if (ShAmt0C &&
23895         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23896       return DAG.getNode(Opc, DL, VT,
23897                          N0.getOperand(0), N1.getOperand(0),
23898                          DAG.getNode(ISD::TRUNCATE, DL,
23899                                        MVT::i8, ShAmt0));
23900   }
23901
23902   return SDValue();
23903 }
23904
23905 // Generate NEG and CMOV for integer abs.
23906 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23907   EVT VT = N->getValueType(0);
23908
23909   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23910   // 8-bit integer abs to NEG and CMOV.
23911   if (VT.isInteger() && VT.getSizeInBits() == 8)
23912     return SDValue();
23913
23914   SDValue N0 = N->getOperand(0);
23915   SDValue N1 = N->getOperand(1);
23916   SDLoc DL(N);
23917
23918   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23919   // and change it to SUB and CMOV.
23920   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23921       N0.getOpcode() == ISD::ADD &&
23922       N0.getOperand(1) == N1 &&
23923       N1.getOpcode() == ISD::SRA &&
23924       N1.getOperand(0) == N0.getOperand(0))
23925     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23926       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23927         // Generate SUB & CMOV.
23928         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23929                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
23930
23931         SDValue Ops[] = { N0.getOperand(0), Neg,
23932                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23933                           SDValue(Neg.getNode(), 1) };
23934         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23935       }
23936   return SDValue();
23937 }
23938
23939 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23940 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23941                                  TargetLowering::DAGCombinerInfo &DCI,
23942                                  const X86Subtarget *Subtarget) {
23943   if (DCI.isBeforeLegalizeOps())
23944     return SDValue();
23945
23946   if (Subtarget->hasCMov())
23947     if (SDValue RV = performIntegerAbsCombine(N, DAG))
23948       return RV;
23949
23950   return SDValue();
23951 }
23952
23953 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23954 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23955                                   TargetLowering::DAGCombinerInfo &DCI,
23956                                   const X86Subtarget *Subtarget) {
23957   LoadSDNode *Ld = cast<LoadSDNode>(N);
23958   EVT RegVT = Ld->getValueType(0);
23959   EVT MemVT = Ld->getMemoryVT();
23960   SDLoc dl(Ld);
23961   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23962
23963   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23964   // into two 16-byte operations.
23965   ISD::LoadExtType Ext = Ld->getExtensionType();
23966   unsigned Alignment = Ld->getAlignment();
23967   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23968   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23969       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23970     unsigned NumElems = RegVT.getVectorNumElements();
23971     if (NumElems < 2)
23972       return SDValue();
23973
23974     SDValue Ptr = Ld->getBasePtr();
23975     SDValue Increment =
23976         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
23977
23978     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23979                                   NumElems/2);
23980     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23981                                 Ld->getPointerInfo(), Ld->isVolatile(),
23982                                 Ld->isNonTemporal(), Ld->isInvariant(),
23983                                 Alignment);
23984     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23985     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23986                                 Ld->getPointerInfo(), Ld->isVolatile(),
23987                                 Ld->isNonTemporal(), Ld->isInvariant(),
23988                                 std::min(16U, Alignment));
23989     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23990                              Load1.getValue(1),
23991                              Load2.getValue(1));
23992
23993     SDValue NewVec = DAG.getUNDEF(RegVT);
23994     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23995     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23996     return DCI.CombineTo(N, NewVec, TF, true);
23997   }
23998
23999   return SDValue();
24000 }
24001
24002 /// PerformMLOADCombine - Resolve extending loads
24003 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24004                                    TargetLowering::DAGCombinerInfo &DCI,
24005                                    const X86Subtarget *Subtarget) {
24006   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24007   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24008     return SDValue();
24009
24010   EVT VT = Mld->getValueType(0);
24011   unsigned NumElems = VT.getVectorNumElements();
24012   EVT LdVT = Mld->getMemoryVT();
24013   SDLoc dl(Mld);
24014
24015   assert(LdVT != VT && "Cannot extend to the same type");
24016   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24017   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24018   // From, To sizes and ElemCount must be pow of two
24019   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24020     "Unexpected size for extending masked load");
24021
24022   unsigned SizeRatio  = ToSz / FromSz;
24023   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24024
24025   // Create a type on which we perform the shuffle
24026   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24027           LdVT.getScalarType(), NumElems*SizeRatio);
24028   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24029
24030   // Convert Src0 value
24031   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24032   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24033     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24034     for (unsigned i = 0; i != NumElems; ++i)
24035       ShuffleVec[i] = i * SizeRatio;
24036
24037     // Can't shuffle using an illegal type.
24038     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24039             && "WideVecVT should be legal");
24040     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24041                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24042   }
24043   // Prepare the new mask
24044   SDValue NewMask;
24045   SDValue Mask = Mld->getMask();
24046   if (Mask.getValueType() == VT) {
24047     // Mask and original value have the same type
24048     NewMask = DAG.getBitcast(WideVecVT, Mask);
24049     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24050     for (unsigned i = 0; i != NumElems; ++i)
24051       ShuffleVec[i] = i * SizeRatio;
24052     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24053       ShuffleVec[i] = NumElems*SizeRatio;
24054     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24055                                    DAG.getConstant(0, dl, WideVecVT),
24056                                    &ShuffleVec[0]);
24057   }
24058   else {
24059     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24060     unsigned WidenNumElts = NumElems*SizeRatio;
24061     unsigned MaskNumElts = VT.getVectorNumElements();
24062     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24063                                      WidenNumElts);
24064
24065     unsigned NumConcat = WidenNumElts / MaskNumElts;
24066     SmallVector<SDValue, 16> Ops(NumConcat);
24067     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24068     Ops[0] = Mask;
24069     for (unsigned i = 1; i != NumConcat; ++i)
24070       Ops[i] = ZeroVal;
24071
24072     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24073   }
24074
24075   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24076                                      Mld->getBasePtr(), NewMask, WideSrc0,
24077                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24078                                      ISD::NON_EXTLOAD);
24079   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24080   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24081
24082 }
24083 /// PerformMSTORECombine - Resolve truncating stores
24084 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24085                                     const X86Subtarget *Subtarget) {
24086   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24087   if (!Mst->isTruncatingStore())
24088     return SDValue();
24089
24090   EVT VT = Mst->getValue().getValueType();
24091   unsigned NumElems = VT.getVectorNumElements();
24092   EVT StVT = Mst->getMemoryVT();
24093   SDLoc dl(Mst);
24094
24095   assert(StVT != VT && "Cannot truncate to the same type");
24096   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24097   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24098
24099   // From, To sizes and ElemCount must be pow of two
24100   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24101     "Unexpected size for truncating masked store");
24102   // We are going to use the original vector elt for storing.
24103   // Accumulated smaller vector elements must be a multiple of the store size.
24104   assert (((NumElems * FromSz) % ToSz) == 0 &&
24105           "Unexpected ratio for truncating masked store");
24106
24107   unsigned SizeRatio  = FromSz / ToSz;
24108   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24109
24110   // Create a type on which we perform the shuffle
24111   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24112           StVT.getScalarType(), NumElems*SizeRatio);
24113
24114   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24115
24116   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24117   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24118   for (unsigned i = 0; i != NumElems; ++i)
24119     ShuffleVec[i] = i * SizeRatio;
24120
24121   // Can't shuffle using an illegal type.
24122   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24123           && "WideVecVT should be legal");
24124
24125   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24126                                         DAG.getUNDEF(WideVecVT),
24127                                         &ShuffleVec[0]);
24128
24129   SDValue NewMask;
24130   SDValue Mask = Mst->getMask();
24131   if (Mask.getValueType() == VT) {
24132     // Mask and original value have the same type
24133     NewMask = DAG.getBitcast(WideVecVT, Mask);
24134     for (unsigned i = 0; i != NumElems; ++i)
24135       ShuffleVec[i] = i * SizeRatio;
24136     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24137       ShuffleVec[i] = NumElems*SizeRatio;
24138     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24139                                    DAG.getConstant(0, dl, WideVecVT),
24140                                    &ShuffleVec[0]);
24141   }
24142   else {
24143     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24144     unsigned WidenNumElts = NumElems*SizeRatio;
24145     unsigned MaskNumElts = VT.getVectorNumElements();
24146     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24147                                      WidenNumElts);
24148
24149     unsigned NumConcat = WidenNumElts / MaskNumElts;
24150     SmallVector<SDValue, 16> Ops(NumConcat);
24151     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24152     Ops[0] = Mask;
24153     for (unsigned i = 1; i != NumConcat; ++i)
24154       Ops[i] = ZeroVal;
24155
24156     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24157   }
24158
24159   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24160                             NewMask, StVT, Mst->getMemOperand(), false);
24161 }
24162 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24163 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24164                                    const X86Subtarget *Subtarget) {
24165   StoreSDNode *St = cast<StoreSDNode>(N);
24166   EVT VT = St->getValue().getValueType();
24167   EVT StVT = St->getMemoryVT();
24168   SDLoc dl(St);
24169   SDValue StoredVal = St->getOperand(1);
24170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24171
24172   // If we are saving a concatenation of two XMM registers and 32-byte stores
24173   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24174   unsigned Alignment = St->getAlignment();
24175   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24176   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24177       StVT == VT && !IsAligned) {
24178     unsigned NumElems = VT.getVectorNumElements();
24179     if (NumElems < 2)
24180       return SDValue();
24181
24182     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24183     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24184
24185     SDValue Stride =
24186         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24187     SDValue Ptr0 = St->getBasePtr();
24188     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24189
24190     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24191                                 St->getPointerInfo(), St->isVolatile(),
24192                                 St->isNonTemporal(), Alignment);
24193     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24194                                 St->getPointerInfo(), St->isVolatile(),
24195                                 St->isNonTemporal(),
24196                                 std::min(16U, Alignment));
24197     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24198   }
24199
24200   // Optimize trunc store (of multiple scalars) to shuffle and store.
24201   // First, pack all of the elements in one place. Next, store to memory
24202   // in fewer chunks.
24203   if (St->isTruncatingStore() && VT.isVector()) {
24204     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24205     unsigned NumElems = VT.getVectorNumElements();
24206     assert(StVT != VT && "Cannot truncate to the same type");
24207     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24208     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24209
24210     // From, To sizes and ElemCount must be pow of two
24211     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24212     // We are going to use the original vector elt for storing.
24213     // Accumulated smaller vector elements must be a multiple of the store size.
24214     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24215
24216     unsigned SizeRatio  = FromSz / ToSz;
24217
24218     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24219
24220     // Create a type on which we perform the shuffle
24221     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24222             StVT.getScalarType(), NumElems*SizeRatio);
24223
24224     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24225
24226     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24227     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24228     for (unsigned i = 0; i != NumElems; ++i)
24229       ShuffleVec[i] = i * SizeRatio;
24230
24231     // Can't shuffle using an illegal type.
24232     if (!TLI.isTypeLegal(WideVecVT))
24233       return SDValue();
24234
24235     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24236                                          DAG.getUNDEF(WideVecVT),
24237                                          &ShuffleVec[0]);
24238     // At this point all of the data is stored at the bottom of the
24239     // register. We now need to save it to mem.
24240
24241     // Find the largest store unit
24242     MVT StoreType = MVT::i8;
24243     for (MVT Tp : MVT::integer_valuetypes()) {
24244       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24245         StoreType = Tp;
24246     }
24247
24248     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24249     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24250         (64 <= NumElems * ToSz))
24251       StoreType = MVT::f64;
24252
24253     // Bitcast the original vector into a vector of store-size units
24254     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24255             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24256     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24257     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24258     SmallVector<SDValue, 8> Chains;
24259     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24260                                         TLI.getPointerTy(DAG.getDataLayout()));
24261     SDValue Ptr = St->getBasePtr();
24262
24263     // Perform one or more big stores into memory.
24264     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24265       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24266                                    StoreType, ShuffWide,
24267                                    DAG.getIntPtrConstant(i, dl));
24268       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24269                                 St->getPointerInfo(), St->isVolatile(),
24270                                 St->isNonTemporal(), St->getAlignment());
24271       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24272       Chains.push_back(Ch);
24273     }
24274
24275     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24276   }
24277
24278   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24279   // the FP state in cases where an emms may be missing.
24280   // A preferable solution to the general problem is to figure out the right
24281   // places to insert EMMS.  This qualifies as a quick hack.
24282
24283   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24284   if (VT.getSizeInBits() != 64)
24285     return SDValue();
24286
24287   const Function *F = DAG.getMachineFunction().getFunction();
24288   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24289   bool F64IsLegal =
24290       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24291   if ((VT.isVector() ||
24292        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24293       isa<LoadSDNode>(St->getValue()) &&
24294       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24295       St->getChain().hasOneUse() && !St->isVolatile()) {
24296     SDNode* LdVal = St->getValue().getNode();
24297     LoadSDNode *Ld = nullptr;
24298     int TokenFactorIndex = -1;
24299     SmallVector<SDValue, 8> Ops;
24300     SDNode* ChainVal = St->getChain().getNode();
24301     // Must be a store of a load.  We currently handle two cases:  the load
24302     // is a direct child, and it's under an intervening TokenFactor.  It is
24303     // possible to dig deeper under nested TokenFactors.
24304     if (ChainVal == LdVal)
24305       Ld = cast<LoadSDNode>(St->getChain());
24306     else if (St->getValue().hasOneUse() &&
24307              ChainVal->getOpcode() == ISD::TokenFactor) {
24308       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24309         if (ChainVal->getOperand(i).getNode() == LdVal) {
24310           TokenFactorIndex = i;
24311           Ld = cast<LoadSDNode>(St->getValue());
24312         } else
24313           Ops.push_back(ChainVal->getOperand(i));
24314       }
24315     }
24316
24317     if (!Ld || !ISD::isNormalLoad(Ld))
24318       return SDValue();
24319
24320     // If this is not the MMX case, i.e. we are just turning i64 load/store
24321     // into f64 load/store, avoid the transformation if there are multiple
24322     // uses of the loaded value.
24323     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24324       return SDValue();
24325
24326     SDLoc LdDL(Ld);
24327     SDLoc StDL(N);
24328     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24329     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24330     // pair instead.
24331     if (Subtarget->is64Bit() || F64IsLegal) {
24332       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24333       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24334                                   Ld->getPointerInfo(), Ld->isVolatile(),
24335                                   Ld->isNonTemporal(), Ld->isInvariant(),
24336                                   Ld->getAlignment());
24337       SDValue NewChain = NewLd.getValue(1);
24338       if (TokenFactorIndex != -1) {
24339         Ops.push_back(NewChain);
24340         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24341       }
24342       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24343                           St->getPointerInfo(),
24344                           St->isVolatile(), St->isNonTemporal(),
24345                           St->getAlignment());
24346     }
24347
24348     // Otherwise, lower to two pairs of 32-bit loads / stores.
24349     SDValue LoAddr = Ld->getBasePtr();
24350     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24351                                  DAG.getConstant(4, LdDL, MVT::i32));
24352
24353     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24354                                Ld->getPointerInfo(),
24355                                Ld->isVolatile(), Ld->isNonTemporal(),
24356                                Ld->isInvariant(), Ld->getAlignment());
24357     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24358                                Ld->getPointerInfo().getWithOffset(4),
24359                                Ld->isVolatile(), Ld->isNonTemporal(),
24360                                Ld->isInvariant(),
24361                                MinAlign(Ld->getAlignment(), 4));
24362
24363     SDValue NewChain = LoLd.getValue(1);
24364     if (TokenFactorIndex != -1) {
24365       Ops.push_back(LoLd);
24366       Ops.push_back(HiLd);
24367       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24368     }
24369
24370     LoAddr = St->getBasePtr();
24371     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24372                          DAG.getConstant(4, StDL, MVT::i32));
24373
24374     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24375                                 St->getPointerInfo(),
24376                                 St->isVolatile(), St->isNonTemporal(),
24377                                 St->getAlignment());
24378     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24379                                 St->getPointerInfo().getWithOffset(4),
24380                                 St->isVolatile(),
24381                                 St->isNonTemporal(),
24382                                 MinAlign(St->getAlignment(), 4));
24383     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24384   }
24385
24386   // This is similar to the above case, but here we handle a scalar 64-bit
24387   // integer store that is extracted from a vector on a 32-bit target.
24388   // If we have SSE2, then we can treat it like a floating-point double
24389   // to get past legalization. The execution dependencies fixup pass will
24390   // choose the optimal machine instruction for the store if this really is
24391   // an integer or v2f32 rather than an f64.
24392   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24393       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24394     SDValue OldExtract = St->getOperand(1);
24395     SDValue ExtOp0 = OldExtract.getOperand(0);
24396     unsigned VecSize = ExtOp0.getValueSizeInBits();
24397     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24398     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24399     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24400                                      BitCast, OldExtract.getOperand(1));
24401     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24402                         St->getPointerInfo(), St->isVolatile(),
24403                         St->isNonTemporal(), St->getAlignment());
24404   }
24405
24406   return SDValue();
24407 }
24408
24409 /// Return 'true' if this vector operation is "horizontal"
24410 /// and return the operands for the horizontal operation in LHS and RHS.  A
24411 /// horizontal operation performs the binary operation on successive elements
24412 /// of its first operand, then on successive elements of its second operand,
24413 /// returning the resulting values in a vector.  For example, if
24414 ///   A = < float a0, float a1, float a2, float a3 >
24415 /// and
24416 ///   B = < float b0, float b1, float b2, float b3 >
24417 /// then the result of doing a horizontal operation on A and B is
24418 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24419 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24420 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24421 /// set to A, RHS to B, and the routine returns 'true'.
24422 /// Note that the binary operation should have the property that if one of the
24423 /// operands is UNDEF then the result is UNDEF.
24424 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24425   // Look for the following pattern: if
24426   //   A = < float a0, float a1, float a2, float a3 >
24427   //   B = < float b0, float b1, float b2, float b3 >
24428   // and
24429   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24430   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24431   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24432   // which is A horizontal-op B.
24433
24434   // At least one of the operands should be a vector shuffle.
24435   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24436       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24437     return false;
24438
24439   MVT VT = LHS.getSimpleValueType();
24440
24441   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24442          "Unsupported vector type for horizontal add/sub");
24443
24444   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24445   // operate independently on 128-bit lanes.
24446   unsigned NumElts = VT.getVectorNumElements();
24447   unsigned NumLanes = VT.getSizeInBits()/128;
24448   unsigned NumLaneElts = NumElts / NumLanes;
24449   assert((NumLaneElts % 2 == 0) &&
24450          "Vector type should have an even number of elements in each lane");
24451   unsigned HalfLaneElts = NumLaneElts/2;
24452
24453   // View LHS in the form
24454   //   LHS = VECTOR_SHUFFLE A, B, LMask
24455   // If LHS is not a shuffle then pretend it is the shuffle
24456   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24457   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24458   // type VT.
24459   SDValue A, B;
24460   SmallVector<int, 16> LMask(NumElts);
24461   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24462     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24463       A = LHS.getOperand(0);
24464     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24465       B = LHS.getOperand(1);
24466     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24467     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24468   } else {
24469     if (LHS.getOpcode() != ISD::UNDEF)
24470       A = LHS;
24471     for (unsigned i = 0; i != NumElts; ++i)
24472       LMask[i] = i;
24473   }
24474
24475   // Likewise, view RHS in the form
24476   //   RHS = VECTOR_SHUFFLE C, D, RMask
24477   SDValue C, D;
24478   SmallVector<int, 16> RMask(NumElts);
24479   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24480     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24481       C = RHS.getOperand(0);
24482     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24483       D = RHS.getOperand(1);
24484     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24485     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24486   } else {
24487     if (RHS.getOpcode() != ISD::UNDEF)
24488       C = RHS;
24489     for (unsigned i = 0; i != NumElts; ++i)
24490       RMask[i] = i;
24491   }
24492
24493   // Check that the shuffles are both shuffling the same vectors.
24494   if (!(A == C && B == D) && !(A == D && B == C))
24495     return false;
24496
24497   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24498   if (!A.getNode() && !B.getNode())
24499     return false;
24500
24501   // If A and B occur in reverse order in RHS, then "swap" them (which means
24502   // rewriting the mask).
24503   if (A != C)
24504     ShuffleVectorSDNode::commuteMask(RMask);
24505
24506   // At this point LHS and RHS are equivalent to
24507   //   LHS = VECTOR_SHUFFLE A, B, LMask
24508   //   RHS = VECTOR_SHUFFLE A, B, RMask
24509   // Check that the masks correspond to performing a horizontal operation.
24510   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24511     for (unsigned i = 0; i != NumLaneElts; ++i) {
24512       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24513
24514       // Ignore any UNDEF components.
24515       if (LIdx < 0 || RIdx < 0 ||
24516           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24517           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24518         continue;
24519
24520       // Check that successive elements are being operated on.  If not, this is
24521       // not a horizontal operation.
24522       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24523       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24524       if (!(LIdx == Index && RIdx == Index + 1) &&
24525           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24526         return false;
24527     }
24528   }
24529
24530   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24531   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24532   return true;
24533 }
24534
24535 /// Do target-specific dag combines on floating point adds.
24536 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24537                                   const X86Subtarget *Subtarget) {
24538   EVT VT = N->getValueType(0);
24539   SDValue LHS = N->getOperand(0);
24540   SDValue RHS = N->getOperand(1);
24541
24542   // Try to synthesize horizontal adds from adds of shuffles.
24543   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24544        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24545       isHorizontalBinOp(LHS, RHS, true))
24546     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24547   return SDValue();
24548 }
24549
24550 /// Do target-specific dag combines on floating point subs.
24551 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24552                                   const X86Subtarget *Subtarget) {
24553   EVT VT = N->getValueType(0);
24554   SDValue LHS = N->getOperand(0);
24555   SDValue RHS = N->getOperand(1);
24556
24557   // Try to synthesize horizontal subs from subs of shuffles.
24558   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24559        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24560       isHorizontalBinOp(LHS, RHS, false))
24561     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24562   return SDValue();
24563 }
24564
24565 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24566 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24567   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24568
24569   // F[X]OR(0.0, x) -> x
24570   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24571     if (C->getValueAPF().isPosZero())
24572       return N->getOperand(1);
24573
24574   // F[X]OR(x, 0.0) -> x
24575   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24576     if (C->getValueAPF().isPosZero())
24577       return N->getOperand(0);
24578   return SDValue();
24579 }
24580
24581 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24582 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24583   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24584
24585   // Only perform optimizations if UnsafeMath is used.
24586   if (!DAG.getTarget().Options.UnsafeFPMath)
24587     return SDValue();
24588
24589   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24590   // into FMINC and FMAXC, which are Commutative operations.
24591   unsigned NewOp = 0;
24592   switch (N->getOpcode()) {
24593     default: llvm_unreachable("unknown opcode");
24594     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24595     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24596   }
24597
24598   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24599                      N->getOperand(0), N->getOperand(1));
24600 }
24601
24602 /// Do target-specific dag combines on X86ISD::FAND nodes.
24603 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24604   // FAND(0.0, x) -> 0.0
24605   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24606     if (C->getValueAPF().isPosZero())
24607       return N->getOperand(0);
24608
24609   // FAND(x, 0.0) -> 0.0
24610   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24611     if (C->getValueAPF().isPosZero())
24612       return N->getOperand(1);
24613
24614   return SDValue();
24615 }
24616
24617 /// Do target-specific dag combines on X86ISD::FANDN nodes
24618 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24619   // FANDN(0.0, x) -> x
24620   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24621     if (C->getValueAPF().isPosZero())
24622       return N->getOperand(1);
24623
24624   // FANDN(x, 0.0) -> 0.0
24625   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24626     if (C->getValueAPF().isPosZero())
24627       return N->getOperand(1);
24628
24629   return SDValue();
24630 }
24631
24632 static SDValue PerformBTCombine(SDNode *N,
24633                                 SelectionDAG &DAG,
24634                                 TargetLowering::DAGCombinerInfo &DCI) {
24635   // BT ignores high bits in the bit index operand.
24636   SDValue Op1 = N->getOperand(1);
24637   if (Op1.hasOneUse()) {
24638     unsigned BitWidth = Op1.getValueSizeInBits();
24639     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24640     APInt KnownZero, KnownOne;
24641     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24642                                           !DCI.isBeforeLegalizeOps());
24643     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24644     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24645         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24646       DCI.CommitTargetLoweringOpt(TLO);
24647   }
24648   return SDValue();
24649 }
24650
24651 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24652   SDValue Op = N->getOperand(0);
24653   if (Op.getOpcode() == ISD::BITCAST)
24654     Op = Op.getOperand(0);
24655   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24656   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24657       VT.getVectorElementType().getSizeInBits() ==
24658       OpVT.getVectorElementType().getSizeInBits()) {
24659     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24660   }
24661   return SDValue();
24662 }
24663
24664 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24665                                                const X86Subtarget *Subtarget) {
24666   EVT VT = N->getValueType(0);
24667   if (!VT.isVector())
24668     return SDValue();
24669
24670   SDValue N0 = N->getOperand(0);
24671   SDValue N1 = N->getOperand(1);
24672   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24673   SDLoc dl(N);
24674
24675   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24676   // both SSE and AVX2 since there is no sign-extended shift right
24677   // operation on a vector with 64-bit elements.
24678   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24679   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24680   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24681       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24682     SDValue N00 = N0.getOperand(0);
24683
24684     // EXTLOAD has a better solution on AVX2,
24685     // it may be replaced with X86ISD::VSEXT node.
24686     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24687       if (!ISD::isNormalLoad(N00.getNode()))
24688         return SDValue();
24689
24690     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24691         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24692                                   N00, N1);
24693       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24694     }
24695   }
24696   return SDValue();
24697 }
24698
24699 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24700                                   TargetLowering::DAGCombinerInfo &DCI,
24701                                   const X86Subtarget *Subtarget) {
24702   SDValue N0 = N->getOperand(0);
24703   EVT VT = N->getValueType(0);
24704   EVT SVT = VT.getScalarType();
24705   EVT InVT = N0.getValueType();
24706   EVT InSVT = InVT.getScalarType();
24707   SDLoc DL(N);
24708
24709   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24710   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24711   // This exposes the sext to the sdivrem lowering, so that it directly extends
24712   // from AH (which we otherwise need to do contortions to access).
24713   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24714       InVT == MVT::i8 && VT == MVT::i32) {
24715     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24716     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24717                             N0.getOperand(0), N0.getOperand(1));
24718     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24719     return R.getValue(1);
24720   }
24721
24722   if (!DCI.isBeforeLegalizeOps()) {
24723     if (InVT == MVT::i1) {
24724       SDValue Zero = DAG.getConstant(0, DL, VT);
24725       SDValue AllOnes =
24726         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24727       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24728     }
24729     return SDValue();
24730   }
24731
24732   if (VT.isVector() && Subtarget->hasSSE2()) {
24733     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24734       EVT InVT = N.getValueType();
24735       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24736                                    Size / InVT.getScalarSizeInBits());
24737       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24738                                     DAG.getUNDEF(InVT));
24739       Opnds[0] = N;
24740       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24741     };
24742
24743     // If target-size is less than 128-bits, extend to a type that would extend
24744     // to 128 bits, extend that and extract the original target vector.
24745     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24746         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24747         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24748       unsigned Scale = 128 / VT.getSizeInBits();
24749       EVT ExVT =
24750           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24751       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24752       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24753       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24754                          DAG.getIntPtrConstant(0, DL));
24755     }
24756
24757     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24758     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24759     if (VT.getSizeInBits() == 128 &&
24760         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24761         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24762       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24763       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24764     }
24765
24766     // On pre-AVX2 targets, split into 128-bit nodes of
24767     // ISD::SIGN_EXTEND_VECTOR_INREG.
24768     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24769         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24770         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24771       unsigned NumVecs = VT.getSizeInBits() / 128;
24772       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24773       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24774       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24775
24776       SmallVector<SDValue, 8> Opnds;
24777       for (unsigned i = 0, Offset = 0; i != NumVecs;
24778            ++i, Offset += NumSubElts) {
24779         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24780                                      DAG.getIntPtrConstant(Offset, DL));
24781         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24782         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24783         Opnds.push_back(SrcVec);
24784       }
24785       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24786     }
24787   }
24788
24789   if (!Subtarget->hasFp256())
24790     return SDValue();
24791
24792   if (VT.isVector() && VT.getSizeInBits() == 256)
24793     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24794       return R;
24795
24796   return SDValue();
24797 }
24798
24799 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24800                                  const X86Subtarget* Subtarget) {
24801   SDLoc dl(N);
24802   EVT VT = N->getValueType(0);
24803
24804   // Let legalize expand this if it isn't a legal type yet.
24805   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24806     return SDValue();
24807
24808   EVT ScalarVT = VT.getScalarType();
24809   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24810       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24811        !Subtarget->hasAVX512()))
24812     return SDValue();
24813
24814   SDValue A = N->getOperand(0);
24815   SDValue B = N->getOperand(1);
24816   SDValue C = N->getOperand(2);
24817
24818   bool NegA = (A.getOpcode() == ISD::FNEG);
24819   bool NegB = (B.getOpcode() == ISD::FNEG);
24820   bool NegC = (C.getOpcode() == ISD::FNEG);
24821
24822   // Negative multiplication when NegA xor NegB
24823   bool NegMul = (NegA != NegB);
24824   if (NegA)
24825     A = A.getOperand(0);
24826   if (NegB)
24827     B = B.getOperand(0);
24828   if (NegC)
24829     C = C.getOperand(0);
24830
24831   unsigned Opcode;
24832   if (!NegMul)
24833     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24834   else
24835     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24836
24837   return DAG.getNode(Opcode, dl, VT, A, B, C);
24838 }
24839
24840 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24841                                   TargetLowering::DAGCombinerInfo &DCI,
24842                                   const X86Subtarget *Subtarget) {
24843   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24844   //           (and (i32 x86isd::setcc_carry), 1)
24845   // This eliminates the zext. This transformation is necessary because
24846   // ISD::SETCC is always legalized to i8.
24847   SDLoc dl(N);
24848   SDValue N0 = N->getOperand(0);
24849   EVT VT = N->getValueType(0);
24850
24851   if (N0.getOpcode() == ISD::AND &&
24852       N0.hasOneUse() &&
24853       N0.getOperand(0).hasOneUse()) {
24854     SDValue N00 = N0.getOperand(0);
24855     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24856       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24857       if (!C || C->getZExtValue() != 1)
24858         return SDValue();
24859       return DAG.getNode(ISD::AND, dl, VT,
24860                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24861                                      N00.getOperand(0), N00.getOperand(1)),
24862                          DAG.getConstant(1, dl, VT));
24863     }
24864   }
24865
24866   if (N0.getOpcode() == ISD::TRUNCATE &&
24867       N0.hasOneUse() &&
24868       N0.getOperand(0).hasOneUse()) {
24869     SDValue N00 = N0.getOperand(0);
24870     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24871       return DAG.getNode(ISD::AND, dl, VT,
24872                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24873                                      N00.getOperand(0), N00.getOperand(1)),
24874                          DAG.getConstant(1, dl, VT));
24875     }
24876   }
24877
24878   if (VT.is256BitVector())
24879     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24880       return R;
24881
24882   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24883   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24884   // This exposes the zext to the udivrem lowering, so that it directly extends
24885   // from AH (which we otherwise need to do contortions to access).
24886   if (N0.getOpcode() == ISD::UDIVREM &&
24887       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24888       (VT == MVT::i32 || VT == MVT::i64)) {
24889     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24890     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24891                             N0.getOperand(0), N0.getOperand(1));
24892     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24893     return R.getValue(1);
24894   }
24895
24896   return SDValue();
24897 }
24898
24899 // Optimize x == -y --> x+y == 0
24900 //          x != -y --> x+y != 0
24901 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24902                                       const X86Subtarget* Subtarget) {
24903   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24904   SDValue LHS = N->getOperand(0);
24905   SDValue RHS = N->getOperand(1);
24906   EVT VT = N->getValueType(0);
24907   SDLoc DL(N);
24908
24909   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24910     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24911       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24912         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24913                                    LHS.getOperand(1));
24914         return DAG.getSetCC(DL, N->getValueType(0), addV,
24915                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24916       }
24917   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24918     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24919       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24920         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24921                                    RHS.getOperand(1));
24922         return DAG.getSetCC(DL, N->getValueType(0), addV,
24923                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24924       }
24925
24926   if (VT.getScalarType() == MVT::i1 &&
24927       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24928     bool IsSEXT0 =
24929         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24930         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24931     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24932
24933     if (!IsSEXT0 || !IsVZero1) {
24934       // Swap the operands and update the condition code.
24935       std::swap(LHS, RHS);
24936       CC = ISD::getSetCCSwappedOperands(CC);
24937
24938       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24939                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24940       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24941     }
24942
24943     if (IsSEXT0 && IsVZero1) {
24944       assert(VT == LHS.getOperand(0).getValueType() &&
24945              "Uexpected operand type");
24946       if (CC == ISD::SETGT)
24947         return DAG.getConstant(0, DL, VT);
24948       if (CC == ISD::SETLE)
24949         return DAG.getConstant(1, DL, VT);
24950       if (CC == ISD::SETEQ || CC == ISD::SETGE)
24951         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24952
24953       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24954              "Unexpected condition code!");
24955       return LHS.getOperand(0);
24956     }
24957   }
24958
24959   return SDValue();
24960 }
24961
24962 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24963                                          SelectionDAG &DAG) {
24964   SDLoc dl(Load);
24965   MVT VT = Load->getSimpleValueType(0);
24966   MVT EVT = VT.getVectorElementType();
24967   SDValue Addr = Load->getOperand(1);
24968   SDValue NewAddr = DAG.getNode(
24969       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24970       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24971                       Addr.getSimpleValueType()));
24972
24973   SDValue NewLoad =
24974       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24975                   DAG.getMachineFunction().getMachineMemOperand(
24976                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24977   return NewLoad;
24978 }
24979
24980 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24981                                       const X86Subtarget *Subtarget) {
24982   SDLoc dl(N);
24983   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24984   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24985          "X86insertps is only defined for v4x32");
24986
24987   SDValue Ld = N->getOperand(1);
24988   if (MayFoldLoad(Ld)) {
24989     // Extract the countS bits from the immediate so we can get the proper
24990     // address when narrowing the vector load to a specific element.
24991     // When the second source op is a memory address, insertps doesn't use
24992     // countS and just gets an f32 from that address.
24993     unsigned DestIndex =
24994         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24995
24996     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24997
24998     // Create this as a scalar to vector to match the instruction pattern.
24999     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25000     // countS bits are ignored when loading from memory on insertps, which
25001     // means we don't need to explicitly set them to 0.
25002     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25003                        LoadScalarToVector, N->getOperand(2));
25004   }
25005   return SDValue();
25006 }
25007
25008 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25009   SDValue V0 = N->getOperand(0);
25010   SDValue V1 = N->getOperand(1);
25011   SDLoc DL(N);
25012   EVT VT = N->getValueType(0);
25013
25014   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25015   // operands and changing the mask to 1. This saves us a bunch of
25016   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25017   // x86InstrInfo knows how to commute this back after instruction selection
25018   // if it would help register allocation.
25019
25020   // TODO: If optimizing for size or a processor that doesn't suffer from
25021   // partial register update stalls, this should be transformed into a MOVSD
25022   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25023
25024   if (VT == MVT::v2f64)
25025     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25026       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25027         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25028         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25029       }
25030
25031   return SDValue();
25032 }
25033
25034 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25035 // as "sbb reg,reg", since it can be extended without zext and produces
25036 // an all-ones bit which is more useful than 0/1 in some cases.
25037 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25038                                MVT VT) {
25039   if (VT == MVT::i8)
25040     return DAG.getNode(ISD::AND, DL, VT,
25041                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25042                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25043                                    EFLAGS),
25044                        DAG.getConstant(1, DL, VT));
25045   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25046   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25047                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25048                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25049                                  EFLAGS));
25050 }
25051
25052 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25053 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25054                                    TargetLowering::DAGCombinerInfo &DCI,
25055                                    const X86Subtarget *Subtarget) {
25056   SDLoc DL(N);
25057   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25058   SDValue EFLAGS = N->getOperand(1);
25059
25060   if (CC == X86::COND_A) {
25061     // Try to convert COND_A into COND_B in an attempt to facilitate
25062     // materializing "setb reg".
25063     //
25064     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25065     // cannot take an immediate as its first operand.
25066     //
25067     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25068         EFLAGS.getValueType().isInteger() &&
25069         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25070       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25071                                    EFLAGS.getNode()->getVTList(),
25072                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25073       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25074       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25075     }
25076   }
25077
25078   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25079   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25080   // cases.
25081   if (CC == X86::COND_B)
25082     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25083
25084   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25085     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25086     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25087   }
25088
25089   return SDValue();
25090 }
25091
25092 // Optimize branch condition evaluation.
25093 //
25094 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25095                                     TargetLowering::DAGCombinerInfo &DCI,
25096                                     const X86Subtarget *Subtarget) {
25097   SDLoc DL(N);
25098   SDValue Chain = N->getOperand(0);
25099   SDValue Dest = N->getOperand(1);
25100   SDValue EFLAGS = N->getOperand(3);
25101   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25102
25103   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25104     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25105     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25106                        Flags);
25107   }
25108
25109   return SDValue();
25110 }
25111
25112 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25113                                                          SelectionDAG &DAG) {
25114   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25115   // optimize away operation when it's from a constant.
25116   //
25117   // The general transformation is:
25118   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25119   //       AND(VECTOR_CMP(x,y), constant2)
25120   //    constant2 = UNARYOP(constant)
25121
25122   // Early exit if this isn't a vector operation, the operand of the
25123   // unary operation isn't a bitwise AND, or if the sizes of the operations
25124   // aren't the same.
25125   EVT VT = N->getValueType(0);
25126   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25127       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25128       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25129     return SDValue();
25130
25131   // Now check that the other operand of the AND is a constant. We could
25132   // make the transformation for non-constant splats as well, but it's unclear
25133   // that would be a benefit as it would not eliminate any operations, just
25134   // perform one more step in scalar code before moving to the vector unit.
25135   if (BuildVectorSDNode *BV =
25136           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25137     // Bail out if the vector isn't a constant.
25138     if (!BV->isConstant())
25139       return SDValue();
25140
25141     // Everything checks out. Build up the new and improved node.
25142     SDLoc DL(N);
25143     EVT IntVT = BV->getValueType(0);
25144     // Create a new constant of the appropriate type for the transformed
25145     // DAG.
25146     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25147     // The AND node needs bitcasts to/from an integer vector type around it.
25148     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25149     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25150                                  N->getOperand(0)->getOperand(0), MaskConst);
25151     SDValue Res = DAG.getBitcast(VT, NewAnd);
25152     return Res;
25153   }
25154
25155   return SDValue();
25156 }
25157
25158 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25159                                         const X86Subtarget *Subtarget) {
25160   SDValue Op0 = N->getOperand(0);
25161   EVT VT = N->getValueType(0);
25162   EVT InVT = Op0.getValueType();
25163   EVT InSVT = InVT.getScalarType();
25164   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25165
25166   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25167   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25168   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25169     SDLoc dl(N);
25170     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25171                                  InVT.getVectorNumElements());
25172     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25173
25174     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25175       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25176
25177     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25178   }
25179
25180   return SDValue();
25181 }
25182
25183 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25184                                         const X86Subtarget *Subtarget) {
25185   // First try to optimize away the conversion entirely when it's
25186   // conditionally from a constant. Vectors only.
25187   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25188     return Res;
25189
25190   // Now move on to more general possibilities.
25191   SDValue Op0 = N->getOperand(0);
25192   EVT VT = N->getValueType(0);
25193   EVT InVT = Op0.getValueType();
25194   EVT InSVT = InVT.getScalarType();
25195
25196   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25197   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25198   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25199     SDLoc dl(N);
25200     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25201                                  InVT.getVectorNumElements());
25202     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25203     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25204   }
25205
25206   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25207   // a 32-bit target where SSE doesn't support i64->FP operations.
25208   if (Op0.getOpcode() == ISD::LOAD) {
25209     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25210     EVT LdVT = Ld->getValueType(0);
25211
25212     // This transformation is not supported if the result type is f16
25213     if (VT == MVT::f16)
25214       return SDValue();
25215
25216     if (!Ld->isVolatile() && !VT.isVector() &&
25217         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25218         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25219       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25220           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25221       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25222       return FILDChain;
25223     }
25224   }
25225   return SDValue();
25226 }
25227
25228 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25229 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25230                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25231   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25232   // the result is either zero or one (depending on the input carry bit).
25233   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25234   if (X86::isZeroNode(N->getOperand(0)) &&
25235       X86::isZeroNode(N->getOperand(1)) &&
25236       // We don't have a good way to replace an EFLAGS use, so only do this when
25237       // dead right now.
25238       SDValue(N, 1).use_empty()) {
25239     SDLoc DL(N);
25240     EVT VT = N->getValueType(0);
25241     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25242     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25243                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25244                                            DAG.getConstant(X86::COND_B, DL,
25245                                                            MVT::i8),
25246                                            N->getOperand(2)),
25247                                DAG.getConstant(1, DL, VT));
25248     return DCI.CombineTo(N, Res1, CarryOut);
25249   }
25250
25251   return SDValue();
25252 }
25253
25254 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25255 //      (add Y, (setne X, 0)) -> sbb -1, Y
25256 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25257 //      (sub (setne X, 0), Y) -> adc -1, Y
25258 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25259   SDLoc DL(N);
25260
25261   // Look through ZExts.
25262   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25263   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25264     return SDValue();
25265
25266   SDValue SetCC = Ext.getOperand(0);
25267   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25268     return SDValue();
25269
25270   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25271   if (CC != X86::COND_E && CC != X86::COND_NE)
25272     return SDValue();
25273
25274   SDValue Cmp = SetCC.getOperand(1);
25275   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25276       !X86::isZeroNode(Cmp.getOperand(1)) ||
25277       !Cmp.getOperand(0).getValueType().isInteger())
25278     return SDValue();
25279
25280   SDValue CmpOp0 = Cmp.getOperand(0);
25281   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25282                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25283
25284   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25285   if (CC == X86::COND_NE)
25286     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25287                        DL, OtherVal.getValueType(), OtherVal,
25288                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25289                        NewCmp);
25290   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25291                      DL, OtherVal.getValueType(), OtherVal,
25292                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25293 }
25294
25295 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25296 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25297                                  const X86Subtarget *Subtarget) {
25298   EVT VT = N->getValueType(0);
25299   SDValue Op0 = N->getOperand(0);
25300   SDValue Op1 = N->getOperand(1);
25301
25302   // Try to synthesize horizontal adds from adds of shuffles.
25303   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25304        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25305       isHorizontalBinOp(Op0, Op1, true))
25306     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25307
25308   return OptimizeConditionalInDecrement(N, DAG);
25309 }
25310
25311 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25312                                  const X86Subtarget *Subtarget) {
25313   SDValue Op0 = N->getOperand(0);
25314   SDValue Op1 = N->getOperand(1);
25315
25316   // X86 can't encode an immediate LHS of a sub. See if we can push the
25317   // negation into a preceding instruction.
25318   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25319     // If the RHS of the sub is a XOR with one use and a constant, invert the
25320     // immediate. Then add one to the LHS of the sub so we can turn
25321     // X-Y -> X+~Y+1, saving one register.
25322     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25323         isa<ConstantSDNode>(Op1.getOperand(1))) {
25324       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25325       EVT VT = Op0.getValueType();
25326       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25327                                    Op1.getOperand(0),
25328                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25329       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25330                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25331     }
25332   }
25333
25334   // Try to synthesize horizontal adds from adds of shuffles.
25335   EVT VT = N->getValueType(0);
25336   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25337        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25338       isHorizontalBinOp(Op0, Op1, true))
25339     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25340
25341   return OptimizeConditionalInDecrement(N, DAG);
25342 }
25343
25344 /// performVZEXTCombine - Performs build vector combines
25345 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25346                                    TargetLowering::DAGCombinerInfo &DCI,
25347                                    const X86Subtarget *Subtarget) {
25348   SDLoc DL(N);
25349   MVT VT = N->getSimpleValueType(0);
25350   SDValue Op = N->getOperand(0);
25351   MVT OpVT = Op.getSimpleValueType();
25352   MVT OpEltVT = OpVT.getVectorElementType();
25353   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25354
25355   // (vzext (bitcast (vzext (x)) -> (vzext x)
25356   SDValue V = Op;
25357   while (V.getOpcode() == ISD::BITCAST)
25358     V = V.getOperand(0);
25359
25360   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25361     MVT InnerVT = V.getSimpleValueType();
25362     MVT InnerEltVT = InnerVT.getVectorElementType();
25363
25364     // If the element sizes match exactly, we can just do one larger vzext. This
25365     // is always an exact type match as vzext operates on integer types.
25366     if (OpEltVT == InnerEltVT) {
25367       assert(OpVT == InnerVT && "Types must match for vzext!");
25368       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25369     }
25370
25371     // The only other way we can combine them is if only a single element of the
25372     // inner vzext is used in the input to the outer vzext.
25373     if (InnerEltVT.getSizeInBits() < InputBits)
25374       return SDValue();
25375
25376     // In this case, the inner vzext is completely dead because we're going to
25377     // only look at bits inside of the low element. Just do the outer vzext on
25378     // a bitcast of the input to the inner.
25379     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25380   }
25381
25382   // Check if we can bypass extracting and re-inserting an element of an input
25383   // vector. Essentialy:
25384   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25385   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25386       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25387       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25388     SDValue ExtractedV = V.getOperand(0);
25389     SDValue OrigV = ExtractedV.getOperand(0);
25390     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25391       if (ExtractIdx->getZExtValue() == 0) {
25392         MVT OrigVT = OrigV.getSimpleValueType();
25393         // Extract a subvector if necessary...
25394         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25395           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25396           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25397                                     OrigVT.getVectorNumElements() / Ratio);
25398           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25399                               DAG.getIntPtrConstant(0, DL));
25400         }
25401         Op = DAG.getBitcast(OpVT, OrigV);
25402         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25403       }
25404   }
25405
25406   return SDValue();
25407 }
25408
25409 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25410                                              DAGCombinerInfo &DCI) const {
25411   SelectionDAG &DAG = DCI.DAG;
25412   switch (N->getOpcode()) {
25413   default: break;
25414   case ISD::EXTRACT_VECTOR_ELT:
25415     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25416   case ISD::VSELECT:
25417   case ISD::SELECT:
25418   case X86ISD::SHRUNKBLEND:
25419     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25420   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25421   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25422   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25423   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25424   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25425   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25426   case ISD::SHL:
25427   case ISD::SRA:
25428   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25429   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25430   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25431   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25432   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25433   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25434   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25435   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25436   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25437   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25438   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25439   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25440   case X86ISD::FXOR:
25441   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25442   case X86ISD::FMIN:
25443   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25444   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25445   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25446   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25447   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25448   case ISD::ANY_EXTEND:
25449   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25450   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25451   case ISD::SIGN_EXTEND_INREG:
25452     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25453   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25454   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25455   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25456   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25457   case X86ISD::SHUFP:       // Handle all target specific shuffles
25458   case X86ISD::PALIGNR:
25459   case X86ISD::UNPCKH:
25460   case X86ISD::UNPCKL:
25461   case X86ISD::MOVHLPS:
25462   case X86ISD::MOVLHPS:
25463   case X86ISD::PSHUFB:
25464   case X86ISD::PSHUFD:
25465   case X86ISD::PSHUFHW:
25466   case X86ISD::PSHUFLW:
25467   case X86ISD::MOVSS:
25468   case X86ISD::MOVSD:
25469   case X86ISD::VPERMILPI:
25470   case X86ISD::VPERM2X128:
25471   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25472   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25473   case ISD::INTRINSIC_WO_CHAIN:
25474     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25475   case X86ISD::INSERTPS: {
25476     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25477       return PerformINSERTPSCombine(N, DAG, Subtarget);
25478     break;
25479   }
25480   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25481   }
25482
25483   return SDValue();
25484 }
25485
25486 /// isTypeDesirableForOp - Return true if the target has native support for
25487 /// the specified value type and it is 'desirable' to use the type for the
25488 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25489 /// instruction encodings are longer and some i16 instructions are slow.
25490 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25491   if (!isTypeLegal(VT))
25492     return false;
25493   if (VT != MVT::i16)
25494     return true;
25495
25496   switch (Opc) {
25497   default:
25498     return true;
25499   case ISD::LOAD:
25500   case ISD::SIGN_EXTEND:
25501   case ISD::ZERO_EXTEND:
25502   case ISD::ANY_EXTEND:
25503   case ISD::SHL:
25504   case ISD::SRL:
25505   case ISD::SUB:
25506   case ISD::ADD:
25507   case ISD::MUL:
25508   case ISD::AND:
25509   case ISD::OR:
25510   case ISD::XOR:
25511     return false;
25512   }
25513 }
25514
25515 /// IsDesirableToPromoteOp - This method query the target whether it is
25516 /// beneficial for dag combiner to promote the specified node. If true, it
25517 /// should return the desired promotion type by reference.
25518 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25519   EVT VT = Op.getValueType();
25520   if (VT != MVT::i16)
25521     return false;
25522
25523   bool Promote = false;
25524   bool Commute = false;
25525   switch (Op.getOpcode()) {
25526   default: break;
25527   case ISD::LOAD: {
25528     LoadSDNode *LD = cast<LoadSDNode>(Op);
25529     // If the non-extending load has a single use and it's not live out, then it
25530     // might be folded.
25531     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25532                                                      Op.hasOneUse()*/) {
25533       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25534              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25535         // The only case where we'd want to promote LOAD (rather then it being
25536         // promoted as an operand is when it's only use is liveout.
25537         if (UI->getOpcode() != ISD::CopyToReg)
25538           return false;
25539       }
25540     }
25541     Promote = true;
25542     break;
25543   }
25544   case ISD::SIGN_EXTEND:
25545   case ISD::ZERO_EXTEND:
25546   case ISD::ANY_EXTEND:
25547     Promote = true;
25548     break;
25549   case ISD::SHL:
25550   case ISD::SRL: {
25551     SDValue N0 = Op.getOperand(0);
25552     // Look out for (store (shl (load), x)).
25553     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25554       return false;
25555     Promote = true;
25556     break;
25557   }
25558   case ISD::ADD:
25559   case ISD::MUL:
25560   case ISD::AND:
25561   case ISD::OR:
25562   case ISD::XOR:
25563     Commute = true;
25564     // fallthrough
25565   case ISD::SUB: {
25566     SDValue N0 = Op.getOperand(0);
25567     SDValue N1 = Op.getOperand(1);
25568     if (!Commute && MayFoldLoad(N1))
25569       return false;
25570     // Avoid disabling potential load folding opportunities.
25571     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25572       return false;
25573     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25574       return false;
25575     Promote = true;
25576   }
25577   }
25578
25579   PVT = MVT::i32;
25580   return Promote;
25581 }
25582
25583 //===----------------------------------------------------------------------===//
25584 //                           X86 Inline Assembly Support
25585 //===----------------------------------------------------------------------===//
25586
25587 // Helper to match a string separated by whitespace.
25588 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25589   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25590
25591   for (StringRef Piece : Pieces) {
25592     if (!S.startswith(Piece)) // Check if the piece matches.
25593       return false;
25594
25595     S = S.substr(Piece.size());
25596     StringRef::size_type Pos = S.find_first_not_of(" \t");
25597     if (Pos == 0) // We matched a prefix.
25598       return false;
25599
25600     S = S.substr(Pos);
25601   }
25602
25603   return S.empty();
25604 }
25605
25606 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25607
25608   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25609     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25610         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25611         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25612
25613       if (AsmPieces.size() == 3)
25614         return true;
25615       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25616         return true;
25617     }
25618   }
25619   return false;
25620 }
25621
25622 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25623   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25624
25625   std::string AsmStr = IA->getAsmString();
25626
25627   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25628   if (!Ty || Ty->getBitWidth() % 16 != 0)
25629     return false;
25630
25631   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25632   SmallVector<StringRef, 4> AsmPieces;
25633   SplitString(AsmStr, AsmPieces, ";\n");
25634
25635   switch (AsmPieces.size()) {
25636   default: return false;
25637   case 1:
25638     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25639     // we will turn this bswap into something that will be lowered to logical
25640     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25641     // lower so don't worry about this.
25642     // bswap $0
25643     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25644         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25645         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25646         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25647         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25648         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25649       // No need to check constraints, nothing other than the equivalent of
25650       // "=r,0" would be valid here.
25651       return IntrinsicLowering::LowerToByteSwap(CI);
25652     }
25653
25654     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25655     if (CI->getType()->isIntegerTy(16) &&
25656         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25657         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25658          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25659       AsmPieces.clear();
25660       StringRef ConstraintsStr = IA->getConstraintString();
25661       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25662       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25663       if (clobbersFlagRegisters(AsmPieces))
25664         return IntrinsicLowering::LowerToByteSwap(CI);
25665     }
25666     break;
25667   case 3:
25668     if (CI->getType()->isIntegerTy(32) &&
25669         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25670         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25671         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25672         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25673       AsmPieces.clear();
25674       StringRef ConstraintsStr = IA->getConstraintString();
25675       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25676       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25677       if (clobbersFlagRegisters(AsmPieces))
25678         return IntrinsicLowering::LowerToByteSwap(CI);
25679     }
25680
25681     if (CI->getType()->isIntegerTy(64)) {
25682       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25683       if (Constraints.size() >= 2 &&
25684           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25685           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25686         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25687         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25688             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25689             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25690           return IntrinsicLowering::LowerToByteSwap(CI);
25691       }
25692     }
25693     break;
25694   }
25695   return false;
25696 }
25697
25698 /// getConstraintType - Given a constraint letter, return the type of
25699 /// constraint it is for this target.
25700 X86TargetLowering::ConstraintType
25701 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25702   if (Constraint.size() == 1) {
25703     switch (Constraint[0]) {
25704     case 'R':
25705     case 'q':
25706     case 'Q':
25707     case 'f':
25708     case 't':
25709     case 'u':
25710     case 'y':
25711     case 'x':
25712     case 'Y':
25713     case 'l':
25714       return C_RegisterClass;
25715     case 'a':
25716     case 'b':
25717     case 'c':
25718     case 'd':
25719     case 'S':
25720     case 'D':
25721     case 'A':
25722       return C_Register;
25723     case 'I':
25724     case 'J':
25725     case 'K':
25726     case 'L':
25727     case 'M':
25728     case 'N':
25729     case 'G':
25730     case 'C':
25731     case 'e':
25732     case 'Z':
25733       return C_Other;
25734     default:
25735       break;
25736     }
25737   }
25738   return TargetLowering::getConstraintType(Constraint);
25739 }
25740
25741 /// Examine constraint type and operand type and determine a weight value.
25742 /// This object must already have been set up with the operand type
25743 /// and the current alternative constraint selected.
25744 TargetLowering::ConstraintWeight
25745   X86TargetLowering::getSingleConstraintMatchWeight(
25746     AsmOperandInfo &info, const char *constraint) const {
25747   ConstraintWeight weight = CW_Invalid;
25748   Value *CallOperandVal = info.CallOperandVal;
25749     // If we don't have a value, we can't do a match,
25750     // but allow it at the lowest weight.
25751   if (!CallOperandVal)
25752     return CW_Default;
25753   Type *type = CallOperandVal->getType();
25754   // Look at the constraint type.
25755   switch (*constraint) {
25756   default:
25757     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25758   case 'R':
25759   case 'q':
25760   case 'Q':
25761   case 'a':
25762   case 'b':
25763   case 'c':
25764   case 'd':
25765   case 'S':
25766   case 'D':
25767   case 'A':
25768     if (CallOperandVal->getType()->isIntegerTy())
25769       weight = CW_SpecificReg;
25770     break;
25771   case 'f':
25772   case 't':
25773   case 'u':
25774     if (type->isFloatingPointTy())
25775       weight = CW_SpecificReg;
25776     break;
25777   case 'y':
25778     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25779       weight = CW_SpecificReg;
25780     break;
25781   case 'x':
25782   case 'Y':
25783     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25784         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25785       weight = CW_Register;
25786     break;
25787   case 'I':
25788     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25789       if (C->getZExtValue() <= 31)
25790         weight = CW_Constant;
25791     }
25792     break;
25793   case 'J':
25794     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25795       if (C->getZExtValue() <= 63)
25796         weight = CW_Constant;
25797     }
25798     break;
25799   case 'K':
25800     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25801       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25802         weight = CW_Constant;
25803     }
25804     break;
25805   case 'L':
25806     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25807       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25808         weight = CW_Constant;
25809     }
25810     break;
25811   case 'M':
25812     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25813       if (C->getZExtValue() <= 3)
25814         weight = CW_Constant;
25815     }
25816     break;
25817   case 'N':
25818     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25819       if (C->getZExtValue() <= 0xff)
25820         weight = CW_Constant;
25821     }
25822     break;
25823   case 'G':
25824   case 'C':
25825     if (isa<ConstantFP>(CallOperandVal)) {
25826       weight = CW_Constant;
25827     }
25828     break;
25829   case 'e':
25830     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25831       if ((C->getSExtValue() >= -0x80000000LL) &&
25832           (C->getSExtValue() <= 0x7fffffffLL))
25833         weight = CW_Constant;
25834     }
25835     break;
25836   case 'Z':
25837     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25838       if (C->getZExtValue() <= 0xffffffff)
25839         weight = CW_Constant;
25840     }
25841     break;
25842   }
25843   return weight;
25844 }
25845
25846 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25847 /// with another that has more specific requirements based on the type of the
25848 /// corresponding operand.
25849 const char *X86TargetLowering::
25850 LowerXConstraint(EVT ConstraintVT) const {
25851   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25852   // 'f' like normal targets.
25853   if (ConstraintVT.isFloatingPoint()) {
25854     if (Subtarget->hasSSE2())
25855       return "Y";
25856     if (Subtarget->hasSSE1())
25857       return "x";
25858   }
25859
25860   return TargetLowering::LowerXConstraint(ConstraintVT);
25861 }
25862
25863 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25864 /// vector.  If it is invalid, don't add anything to Ops.
25865 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25866                                                      std::string &Constraint,
25867                                                      std::vector<SDValue>&Ops,
25868                                                      SelectionDAG &DAG) const {
25869   SDValue Result;
25870
25871   // Only support length 1 constraints for now.
25872   if (Constraint.length() > 1) return;
25873
25874   char ConstraintLetter = Constraint[0];
25875   switch (ConstraintLetter) {
25876   default: break;
25877   case 'I':
25878     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25879       if (C->getZExtValue() <= 31) {
25880         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25881                                        Op.getValueType());
25882         break;
25883       }
25884     }
25885     return;
25886   case 'J':
25887     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25888       if (C->getZExtValue() <= 63) {
25889         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25890                                        Op.getValueType());
25891         break;
25892       }
25893     }
25894     return;
25895   case 'K':
25896     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25897       if (isInt<8>(C->getSExtValue())) {
25898         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25899                                        Op.getValueType());
25900         break;
25901       }
25902     }
25903     return;
25904   case 'L':
25905     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25906       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
25907           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
25908         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
25909                                        Op.getValueType());
25910         break;
25911       }
25912     }
25913     return;
25914   case 'M':
25915     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25916       if (C->getZExtValue() <= 3) {
25917         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25918                                        Op.getValueType());
25919         break;
25920       }
25921     }
25922     return;
25923   case 'N':
25924     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25925       if (C->getZExtValue() <= 255) {
25926         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25927                                        Op.getValueType());
25928         break;
25929       }
25930     }
25931     return;
25932   case 'O':
25933     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25934       if (C->getZExtValue() <= 127) {
25935         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25936                                        Op.getValueType());
25937         break;
25938       }
25939     }
25940     return;
25941   case 'e': {
25942     // 32-bit signed value
25943     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25944       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25945                                            C->getSExtValue())) {
25946         // Widen to 64 bits here to get it sign extended.
25947         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25948         break;
25949       }
25950     // FIXME gcc accepts some relocatable values here too, but only in certain
25951     // memory models; it's complicated.
25952     }
25953     return;
25954   }
25955   case 'Z': {
25956     // 32-bit unsigned value
25957     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25958       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25959                                            C->getZExtValue())) {
25960         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25961                                        Op.getValueType());
25962         break;
25963       }
25964     }
25965     // FIXME gcc accepts some relocatable values here too, but only in certain
25966     // memory models; it's complicated.
25967     return;
25968   }
25969   case 'i': {
25970     // Literal immediates are always ok.
25971     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25972       // Widen to 64 bits here to get it sign extended.
25973       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25974       break;
25975     }
25976
25977     // In any sort of PIC mode addresses need to be computed at runtime by
25978     // adding in a register or some sort of table lookup.  These can't
25979     // be used as immediates.
25980     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25981       return;
25982
25983     // If we are in non-pic codegen mode, we allow the address of a global (with
25984     // an optional displacement) to be used with 'i'.
25985     GlobalAddressSDNode *GA = nullptr;
25986     int64_t Offset = 0;
25987
25988     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25989     while (1) {
25990       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25991         Offset += GA->getOffset();
25992         break;
25993       } else if (Op.getOpcode() == ISD::ADD) {
25994         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25995           Offset += C->getZExtValue();
25996           Op = Op.getOperand(0);
25997           continue;
25998         }
25999       } else if (Op.getOpcode() == ISD::SUB) {
26000         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26001           Offset += -C->getZExtValue();
26002           Op = Op.getOperand(0);
26003           continue;
26004         }
26005       }
26006
26007       // Otherwise, this isn't something we can handle, reject it.
26008       return;
26009     }
26010
26011     const GlobalValue *GV = GA->getGlobal();
26012     // If we require an extra load to get this address, as in PIC mode, we
26013     // can't accept it.
26014     if (isGlobalStubReference(
26015             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26016       return;
26017
26018     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26019                                         GA->getValueType(0), Offset);
26020     break;
26021   }
26022   }
26023
26024   if (Result.getNode()) {
26025     Ops.push_back(Result);
26026     return;
26027   }
26028   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26029 }
26030
26031 std::pair<unsigned, const TargetRegisterClass *>
26032 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26033                                                 StringRef Constraint,
26034                                                 MVT VT) const {
26035   // First, see if this is a constraint that directly corresponds to an LLVM
26036   // register class.
26037   if (Constraint.size() == 1) {
26038     // GCC Constraint Letters
26039     switch (Constraint[0]) {
26040     default: break;
26041       // TODO: Slight differences here in allocation order and leaving
26042       // RIP in the class. Do they matter any more here than they do
26043       // in the normal allocation?
26044     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26045       if (Subtarget->is64Bit()) {
26046         if (VT == MVT::i32 || VT == MVT::f32)
26047           return std::make_pair(0U, &X86::GR32RegClass);
26048         if (VT == MVT::i16)
26049           return std::make_pair(0U, &X86::GR16RegClass);
26050         if (VT == MVT::i8 || VT == MVT::i1)
26051           return std::make_pair(0U, &X86::GR8RegClass);
26052         if (VT == MVT::i64 || VT == MVT::f64)
26053           return std::make_pair(0U, &X86::GR64RegClass);
26054         break;
26055       }
26056       // 32-bit fallthrough
26057     case 'Q':   // Q_REGS
26058       if (VT == MVT::i32 || VT == MVT::f32)
26059         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26060       if (VT == MVT::i16)
26061         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26062       if (VT == MVT::i8 || VT == MVT::i1)
26063         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26064       if (VT == MVT::i64)
26065         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26066       break;
26067     case 'r':   // GENERAL_REGS
26068     case 'l':   // INDEX_REGS
26069       if (VT == MVT::i8 || VT == MVT::i1)
26070         return std::make_pair(0U, &X86::GR8RegClass);
26071       if (VT == MVT::i16)
26072         return std::make_pair(0U, &X86::GR16RegClass);
26073       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26074         return std::make_pair(0U, &X86::GR32RegClass);
26075       return std::make_pair(0U, &X86::GR64RegClass);
26076     case 'R':   // LEGACY_REGS
26077       if (VT == MVT::i8 || VT == MVT::i1)
26078         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26079       if (VT == MVT::i16)
26080         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26081       if (VT == MVT::i32 || !Subtarget->is64Bit())
26082         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26083       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26084     case 'f':  // FP Stack registers.
26085       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26086       // value to the correct fpstack register class.
26087       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26088         return std::make_pair(0U, &X86::RFP32RegClass);
26089       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26090         return std::make_pair(0U, &X86::RFP64RegClass);
26091       return std::make_pair(0U, &X86::RFP80RegClass);
26092     case 'y':   // MMX_REGS if MMX allowed.
26093       if (!Subtarget->hasMMX()) break;
26094       return std::make_pair(0U, &X86::VR64RegClass);
26095     case 'Y':   // SSE_REGS if SSE2 allowed
26096       if (!Subtarget->hasSSE2()) break;
26097       // FALL THROUGH.
26098     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26099       if (!Subtarget->hasSSE1()) break;
26100
26101       switch (VT.SimpleTy) {
26102       default: break;
26103       // Scalar SSE types.
26104       case MVT::f32:
26105       case MVT::i32:
26106         return std::make_pair(0U, &X86::FR32RegClass);
26107       case MVT::f64:
26108       case MVT::i64:
26109         return std::make_pair(0U, &X86::FR64RegClass);
26110       // Vector types.
26111       case MVT::v16i8:
26112       case MVT::v8i16:
26113       case MVT::v4i32:
26114       case MVT::v2i64:
26115       case MVT::v4f32:
26116       case MVT::v2f64:
26117         return std::make_pair(0U, &X86::VR128RegClass);
26118       // AVX types.
26119       case MVT::v32i8:
26120       case MVT::v16i16:
26121       case MVT::v8i32:
26122       case MVT::v4i64:
26123       case MVT::v8f32:
26124       case MVT::v4f64:
26125         return std::make_pair(0U, &X86::VR256RegClass);
26126       case MVT::v8f64:
26127       case MVT::v16f32:
26128       case MVT::v16i32:
26129       case MVT::v8i64:
26130         return std::make_pair(0U, &X86::VR512RegClass);
26131       }
26132       break;
26133     }
26134   }
26135
26136   // Use the default implementation in TargetLowering to convert the register
26137   // constraint into a member of a register class.
26138   std::pair<unsigned, const TargetRegisterClass*> Res;
26139   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26140
26141   // Not found as a standard register?
26142   if (!Res.second) {
26143     // Map st(0) -> st(7) -> ST0
26144     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26145         tolower(Constraint[1]) == 's' &&
26146         tolower(Constraint[2]) == 't' &&
26147         Constraint[3] == '(' &&
26148         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26149         Constraint[5] == ')' &&
26150         Constraint[6] == '}') {
26151
26152       Res.first = X86::FP0+Constraint[4]-'0';
26153       Res.second = &X86::RFP80RegClass;
26154       return Res;
26155     }
26156
26157     // GCC allows "st(0)" to be called just plain "st".
26158     if (StringRef("{st}").equals_lower(Constraint)) {
26159       Res.first = X86::FP0;
26160       Res.second = &X86::RFP80RegClass;
26161       return Res;
26162     }
26163
26164     // flags -> EFLAGS
26165     if (StringRef("{flags}").equals_lower(Constraint)) {
26166       Res.first = X86::EFLAGS;
26167       Res.second = &X86::CCRRegClass;
26168       return Res;
26169     }
26170
26171     // 'A' means EAX + EDX.
26172     if (Constraint == "A") {
26173       Res.first = X86::EAX;
26174       Res.second = &X86::GR32_ADRegClass;
26175       return Res;
26176     }
26177     return Res;
26178   }
26179
26180   // Otherwise, check to see if this is a register class of the wrong value
26181   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26182   // turn into {ax},{dx}.
26183   // MVT::Other is used to specify clobber names.
26184   if (Res.second->hasType(VT) || VT == MVT::Other)
26185     return Res;   // Correct type already, nothing to do.
26186
26187   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26188   // return "eax". This should even work for things like getting 64bit integer
26189   // registers when given an f64 type.
26190   const TargetRegisterClass *Class = Res.second;
26191   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26192       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26193     unsigned Size = VT.getSizeInBits();
26194     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26195                                   : Size == 16 ? MVT::i16
26196                                   : Size == 32 ? MVT::i32
26197                                   : Size == 64 ? MVT::i64
26198                                   : MVT::Other;
26199     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26200     if (DestReg > 0) {
26201       Res.first = DestReg;
26202       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26203                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26204                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26205                  : &X86::GR64RegClass;
26206       assert(Res.second->contains(Res.first) && "Register in register class");
26207     } else {
26208       // No register found/type mismatch.
26209       Res.first = 0;
26210       Res.second = nullptr;
26211     }
26212   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26213              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26214              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26215              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26216              Class == &X86::VR512RegClass) {
26217     // Handle references to XMM physical registers that got mapped into the
26218     // wrong class.  This can happen with constraints like {xmm0} where the
26219     // target independent register mapper will just pick the first match it can
26220     // find, ignoring the required type.
26221
26222     if (VT == MVT::f32 || VT == MVT::i32)
26223       Res.second = &X86::FR32RegClass;
26224     else if (VT == MVT::f64 || VT == MVT::i64)
26225       Res.second = &X86::FR64RegClass;
26226     else if (X86::VR128RegClass.hasType(VT))
26227       Res.second = &X86::VR128RegClass;
26228     else if (X86::VR256RegClass.hasType(VT))
26229       Res.second = &X86::VR256RegClass;
26230     else if (X86::VR512RegClass.hasType(VT))
26231       Res.second = &X86::VR512RegClass;
26232     else {
26233       // Type mismatch and not a clobber: Return an error;
26234       Res.first = 0;
26235       Res.second = nullptr;
26236     }
26237   }
26238
26239   return Res;
26240 }
26241
26242 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26243                                             const AddrMode &AM, Type *Ty,
26244                                             unsigned AS) const {
26245   // Scaling factors are not free at all.
26246   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26247   // will take 2 allocations in the out of order engine instead of 1
26248   // for plain addressing mode, i.e. inst (reg1).
26249   // E.g.,
26250   // vaddps (%rsi,%drx), %ymm0, %ymm1
26251   // Requires two allocations (one for the load, one for the computation)
26252   // whereas:
26253   // vaddps (%rsi), %ymm0, %ymm1
26254   // Requires just 1 allocation, i.e., freeing allocations for other operations
26255   // and having less micro operations to execute.
26256   //
26257   // For some X86 architectures, this is even worse because for instance for
26258   // stores, the complex addressing mode forces the instruction to use the
26259   // "load" ports instead of the dedicated "store" port.
26260   // E.g., on Haswell:
26261   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26262   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26263   if (isLegalAddressingMode(DL, AM, Ty, AS))
26264     // Scale represents reg2 * scale, thus account for 1
26265     // as soon as we use a second register.
26266     return AM.Scale != 0;
26267   return -1;
26268 }
26269
26270 bool X86TargetLowering::isTargetFTOL() const {
26271   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26272 }